Annotation of loncom/homework/grades.pm, revision 1.530

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.530   ! jms         4: # $Id: grades.pm,v 1.529 2008/11/11 16:40:47 jms Exp $
1.17      albertel    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: #
1.1       albertel   28: 
1.529     jms        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: 
1.530   ! jms        86: =head1 SUBROUTINES
1.529     jms        87: 
                     88: =over
                     89: 
1.530   ! jms        90: =item scantron_get_correction() : 
1.529     jms        91: 
                     92:    Builds the interface screen to interact with the operator to fix a
                     93:    specific error condition in a specific scanline
                     94: 
                     95:  Arguments:
                     96:     $r           - Apache request object
                     97:     $i           - number of the current scanline
                     98:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                     99:     $scan_config - hash ref as returned from &get_scantron_config()
                    100:     $line        - full contents of the current scanline
                    101:     $error       - error condition, valid values are
                    102:                    'incorrectCODE', 'duplicateCODE',
                    103:                    'doublebubble', 'missingbubble',
                    104:                    'duplicateID', 'incorrectID'
                    105:     $arg         - extra information needed
                    106:        For errors:
                    107:          - duplicateID   - paper number that this studentID was seen before on
                    108:          - duplicateCODE - array ref of the paper numbers this CODE was
                    109:                            seen on before
                    110:          - incorrectCODE - current incorrect CODE 
                    111:          - doublebubble  - array ref of the bubble lines that have double
                    112:                            bubble errors
                    113:          - missingbubble - array ref of the bubble lines that have missing
                    114:                            bubble errors
                    115: 
1.530   ! jms       116: =item  scantron_get_maxbubble() : 
1.529     jms       117: 
                    118:    Returns the maximum number of bubble lines that are expected to
                    119:    occur. Does this by walking the selected sequence rendering the
                    120:    resource and then checking &Apache::lonxml::get_problem_counter()
                    121:    for what the current value of the problem counter is.
                    122: 
                    123:    Caches the results to $env{'form.scantron_maxbubble'},
                    124:    $env{'form.scantron.bubble_lines.n'}, 
                    125:    $env{'form.scantron.first_bubble_line.n'} and
                    126:    $env{"form.scantron.sub_bubblelines.n"}
                    127:    which are the total number of bubble, lines, the number of bubble
                    128:    lines for response n and number of the first bubble line for response n,
                    129:    and a comma separated list of numbers of bubble lines for sub-questions
                    130:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
                    131: 
                    132: 
1.530   ! jms       133: =item  scantron_validate_missingbubbles() : 
1.529     jms       134: 
                    135:    Validates all scanlines in the selected file to not have any
                    136:     answers that don't have bubbles that have not been verified
                    137:     to be bubble free.
                    138: 
1.530   ! jms       139: =item  scantron_process_students() : 
1.529     jms       140: 
                    141:    Routine that does the actual grading of the bubble sheet information.
                    142: 
                    143:    The parsed scanline hash is added to %env 
                    144: 
                    145:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                    146:    foreach resource , with the form data of
                    147: 
                    148: 	'submitted'     =>'scantron' 
                    149: 	'grade_target'  =>'grade',
                    150: 	'grade_username'=> username of student
                    151: 	'grade_domain'  => domain of student
                    152: 	'grade_courseid'=> of course
                    153: 	'grade_symb'    => symb of resource to grade
                    154: 
                    155:     This triggers a grading pass. The problem grading code takes care
                    156:     of converting the bubbled letter information (now in %env) into a
                    157:     valid submission.
                    158: 
1.530   ! jms       159: =item  scantron_upload_scantron_data() :
1.529     jms       160: 
                    161:     Creates the screen for adding a new bubble sheet data file to a course.
                    162: 
1.530   ! jms       163: =item  scantron_upload_scantron_data_save() : 
1.529     jms       164: 
                    165:    Adds a provided bubble information data file to the course if user
                    166:    has the correct privileges to do so. 
                    167: 
1.530   ! jms       168: =item  valid_file() :
1.529     jms       169: 
                    170:    Validates that the requested bubble data file exists in the course.
                    171: 
1.530   ! jms       172: =item  scantron_download_scantron_data() : 
1.529     jms       173: 
                    174:    Shows a list of the three internal files (original, corrected,
                    175:    skipped) for a specific bubble sheet data file that exists in the
                    176:    course.
                    177: 
1.530   ! jms       178: =item  scantron_validate_ID() : 
1.529     jms       179: 
                    180:    Validates all scanlines in the selected file to not have any
                    181:    invalid or underspecified student IDs
                    182: 
                    183: =back
                    184: 
                    185: =cut
                    186: 
1.1       albertel  187: package Apache::grades;
                    188: use strict;
                    189: use Apache::style;
                    190: use Apache::lonxml;
                    191: use Apache::lonnet;
1.3       albertel  192: use Apache::loncommon;
1.112     ng        193: use Apache::lonhtmlcommon;
1.68      ng        194: use Apache::lonnavmaps;
1.1       albertel  195: use Apache::lonhomework;
1.456     banghart  196: use Apache::lonpickcode;
1.55      matthew   197: use Apache::loncoursedata;
1.362     albertel  198: use Apache::lonmsg();
1.1       albertel  199: use Apache::Constants qw(:common);
1.167     sakharuk  200: use Apache::lonlocal;
1.386     raeburn   201: use Apache::lonenc;
1.170     albertel  202: use String::Similarity;
1.359     www       203: use LONCAPA;
                    204: 
1.315     bowersj2  205: use POSIX qw(floor);
1.87      www       206: 
1.435     foxr      207: 
1.513     foxr      208: 
1.435     foxr      209: my %perm=();
1.447     foxr      210: 
1.513     foxr      211: #  These variables are used to recover from ssi errors
                    212: 
                    213: my $ssi_retries = 5;
                    214: my $ssi_error;
                    215: my $ssi_error_resource;
                    216: my $ssi_error_message;
                    217: 
                    218: 
                    219: sub ssi_with_retries {
                    220:     my ($resource, $retries, %form) = @_;
                    221:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                    222:     if ($response->is_error) {
                    223: 	$ssi_error          = 1;
                    224: 	$ssi_error_resource = $resource;
                    225: 	$ssi_error_message  = $response->code . " " . $response->message;
                    226:     }
                    227: 
                    228:     return $content;
                    229: 
                    230: }
                    231: #
                    232: #  Prodcuces an ssi retry failure error message to the user:
                    233: #
                    234: 
                    235: sub ssi_print_error {
                    236:     my ($r) = @_;
1.516     raeburn   237:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                    238:     $r->print('
                    239: <br />
                    240: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                    241: <p>
                    242: '.&mt('Unable to retrieve a resource from a server:').'<br />
                    243: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                    244: '.&mt('Error:').' '.$ssi_error_message.'
                    245: </p>
                    246: <p>'.
                    247: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                    248: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    249: '</p>');
                    250:     return;
1.513     foxr      251: }
                    252: 
1.44      ng        253: #
1.146     albertel  254: # --- Retrieve the parts from the metadata file.---
1.44      ng        255: sub getpartlist {
1.324     albertel  256:     my ($symb) = @_;
1.439     albertel  257: 
                    258:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    259:     my $res      = $navmap->getBySymb($symb);
                    260:     my $partlist = $res->parts();
                    261:     my $url      = $res->src();
                    262:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    263: 
1.146     albertel  264:     my @stores;
1.439     albertel  265:     foreach my $part (@{ $partlist }) {
1.146     albertel  266: 	foreach my $key (@metakeys) {
                    267: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    268: 	}
                    269:     }
                    270:     return @stores;
1.2       albertel  271: }
                    272: 
1.44      ng        273: # --- Get the symbolic name of a problem and the url
1.324     albertel  274: sub get_symb {
1.173     albertel  275:     my ($request,$silent) = @_;
1.257     albertel  276:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    277:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  278:     if ($symb eq '') { 
                    279: 	if (!$silent) {
                    280: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    281: 	    return ();
                    282: 	}
                    283:     }
1.418     albertel  284:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  285:     return ($symb);
1.32      ng        286: }
                    287: 
1.129     ng        288: #--- Format fullname, username:domain if different for display
                    289: #--- Use anywhere where the student names are listed
                    290: sub nameUserString {
                    291:     my ($type,$fullname,$uname,$udom) = @_;
                    292:     if ($type eq 'header') {
1.485     albertel  293: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        294:     } else {
1.398     albertel  295: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    296: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        297:     }
                    298: }
                    299: 
1.44      ng        300: #--- Get the partlist and the response type for a given problem. ---
                    301: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        302: sub response_type {
1.324     albertel  303:     my ($symb) = shift;
1.377     albertel  304: 
                    305:     my $navmap = Apache::lonnavmaps::navmap->new();
                    306:     my $res = $navmap->getBySymb($symb);
                    307:     my $partlist = $res->parts();
1.392     albertel  308:     my %vPart = 
                    309: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  310:     my (%response_types,%handgrade);
                    311:     foreach my $part (@{ $partlist }) {
1.392     albertel  312: 	next if (%vPart && !exists($vPart{$part}));
                    313: 
1.377     albertel  314: 	my @types = $res->responseType($part);
                    315: 	my @ids = $res->responseIds($part);
                    316: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    317: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    318: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    319: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    320: 				     '.handgrade',$symb);
1.41      ng        321: 	}
                    322:     }
1.377     albertel  323:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        324: }
                    325: 
1.375     albertel  326: sub flatten_responseType {
                    327:     my ($responseType) = @_;
                    328:     my @part_response_id =
                    329: 	map { 
                    330: 	    my $part = $_;
                    331: 	    map {
                    332: 		[$part,$_]
                    333: 		} sort(keys(%{ $responseType->{$part} }));
                    334: 	} sort(keys(%$responseType));
                    335:     return @part_response_id;
                    336: }
                    337: 
1.207     albertel  338: sub get_display_part {
1.324     albertel  339:     my ($partID,$symb)=@_;
1.207     albertel  340:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    341:     if (defined($display) and $display ne '') {
1.398     albertel  342: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  343:     } else {
                    344: 	$display=$partID;
                    345:     }
                    346:     return $display;
                    347: }
1.269     raeburn   348: 
1.118     ng        349: #--- Show resource title
                    350: #--- and parts and response type
                    351: sub showResourceInfo {
1.324     albertel  352:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  353:     my $col=3;
                    354:     if ($checkboxes) { $col=4; }
1.398     albertel  355:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    356:     $result .='<table border="0">';
1.324     albertel  357:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        358:     my %resptype = ();
1.122     ng        359:     my $hdgrade='no';
1.154     albertel  360:     my %partsseen;
1.524     raeburn   361:     foreach my $partID (sort(keys(%$responseType))) {
                    362: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  363: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    364: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    365: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    366: 	    $result.='<tr>';
                    367: 	    if ($checkboxes) {
                    368: 		if (exists($partsseen{$partID})) {
                    369: 		    $result.="<td>&nbsp;</td>";
                    370: 		} else {
1.401     albertel  371: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  372: 		}
                    373: 		$partsseen{$partID}=1;
1.154     albertel  374: 	    }
1.375     albertel  375: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  376: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  377: 		$resID.'</span></td>'.
1.485     albertel  378: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    379: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  380: 	}
1.118     ng        381:     }
                    382:     $result.='</table>'."\n";
1.147     albertel  383:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        384: }
                    385: 
1.434     albertel  386: sub reset_caches {
                    387:     &reset_analyze_cache();
                    388:     &reset_perm();
                    389: }
                    390: 
                    391: {
                    392:     my %analyze_cache;
1.148     albertel  393: 
1.434     albertel  394:     sub reset_analyze_cache {
                    395: 	undef(%analyze_cache);
                    396:     }
                    397: 
                    398:     sub get_analyze {
1.525     raeburn   399: 	my ($symb,$uname,$udom,$no_increment)=@_;
1.434     albertel  400: 	my $key = "$symb\0$uname\0$udom";
                    401: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    402: 
                    403: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    404: 	$url=&Apache::lonnet::clutter($url);
1.513     foxr      405: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
1.516     raeburn   406: 					   ('grade_target' => 'analyze',
                    407: 					    'grade_domain' => $udom,
                    408: 					    'grade_symb' => $symb,
                    409: 					    'grade_courseid' => 
                    410: 					    $env{'request.course.id'},
1.525     raeburn   411: 					    'grade_username' => $uname,
                    412:                                             'grade_noincrement' => $no_increment));
1.434     albertel  413: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    414: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    415: 	return $analyze_cache{$key} = \%analyze;
                    416:     }
                    417: 
                    418:     sub get_order {
1.525     raeburn   419: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    420: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  421: 	return $analyze->{"$partid.$respid.shown"};
                    422:     }
                    423: 
                    424:     sub get_radiobutton_correct_foil {
                    425: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    426: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    427: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    428: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    429: 		return $foil;
                    430: 	    }
                    431: 	}
                    432:     }
1.148     albertel  433: }
1.434     albertel  434: 
1.118     ng        435: #--- Clean response type for display
1.335     albertel  436: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    437: #        response types only.
1.118     ng        438: sub cleanRecord {
1.336     albertel  439:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    440: 	$uname,$udom) = @_;
1.398     albertel  441:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  442:     if ($response =~ /^(option|rank)$/) {
                    443: 	my %answer=&Apache::lonnet::str2hash($answer);
                    444: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    445: 	my ($toprow,$bottomrow);
                    446: 	foreach my $foil (@$order) {
                    447: 	    if ($grading{$foil} == 1) {
                    448: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    449: 	    } else {
                    450: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    451: 	    }
1.398     albertel  452: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  453: 	}
                    454: 	return '<blockquote><table border="1">'.
1.466     albertel  455: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    456: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  457: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    458:     } elsif ($response eq 'match') {
                    459: 	my %answer=&Apache::lonnet::str2hash($answer);
                    460: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    461: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    462: 	my ($toprow,$middlerow,$bottomrow);
                    463: 	foreach my $foil (@$order) {
                    464: 	    my $item=shift(@items);
                    465: 	    if ($grading{$foil} == 1) {
                    466: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  467: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  468: 	    } else {
                    469: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  470: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  471: 	    }
1.398     albertel  472: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        473: 	}
1.126     ng        474: 	return '<blockquote><table border="1">'.
1.466     albertel  475: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    476: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  477: 	    $middlerow.'</tr>'.
1.466     albertel  478: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  479: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    480:     } elsif ($response eq 'radiobutton') {
                    481: 	my %answer=&Apache::lonnet::str2hash($answer);
                    482: 	my ($toprow,$bottomrow);
1.434     albertel  483: 	my $correct = 
                    484: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    485: 	foreach my $foil (@$order) {
1.148     albertel  486: 	    if (exists($answer{$foil})) {
1.434     albertel  487: 		if ($foil eq $correct) {
1.466     albertel  488: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  489: 		} else {
1.466     albertel  490: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  491: 		}
                    492: 	    } else {
1.466     albertel  493: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  494: 	    }
1.398     albertel  495: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  496: 	}
                    497: 	return '<blockquote><table border="1">'.
1.466     albertel  498: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    499: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  500: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    501:     } elsif ($response eq 'essay') {
1.257     albertel  502: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        503: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  504: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    505: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        506: 
1.257     albertel  507: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    508: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    509: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    510: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    511: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    512: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        513: 	}
1.166     albertel  514: 	$answer =~ s-\n-<br />-g;
                    515: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  516:     } elsif ( $response eq 'organic') {
                    517: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    518: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    519: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    520: 	return $result;
1.335     albertel  521:     } elsif ( $response eq 'Task') {
                    522: 	if ( $answer eq 'SUBMITTED') {
                    523: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  524: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  525: 	    return $result;
                    526: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    527: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    528: 			       keys(%{$record}));
                    529: 	    return join('<br />',($version,@matches));
                    530: 			       
                    531: 			       
                    532: 	} else {
                    533: 	    my $result =
                    534: 		'<p>'
                    535: 		.&mt('Overall result: [_1]',
                    536: 		     $record->{$version."resource.$respid.$partid.status"})
                    537: 		.'</p>';
                    538: 	    
                    539: 	    $result .= '<ul>';
                    540: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    541: 			     keys(%{$record}));
                    542: 	    foreach my $grade (sort(@grade)) {
                    543: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    544: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    545: 				     $dim, $record->{$grade}).
                    546: 			  '</li>';
                    547: 	    }
                    548: 	    $result.='</ul>';
                    549: 	    return $result;
                    550: 	}
1.440     albertel  551:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    552: 	$answer = 
                    553: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    554: 							      $answer);
1.122     ng        555:     }
1.118     ng        556:     return $answer;
                    557: }
                    558: 
                    559: #-- A couple of common js functions
                    560: sub commonJSfunctions {
                    561:     my $request = shift;
                    562:     $request->print(<<COMMONJSFUNCTIONS);
                    563: <script type="text/javascript" language="javascript">
                    564:     function radioSelection(radioButton) {
                    565: 	var selection=null;
                    566: 	if (radioButton.length > 1) {
                    567: 	    for (var i=0; i<radioButton.length; i++) {
                    568: 		if (radioButton[i].checked) {
                    569: 		    return radioButton[i].value;
                    570: 		}
                    571: 	    }
                    572: 	} else {
                    573: 	    if (radioButton.checked) return radioButton.value;
                    574: 	}
                    575: 	return selection;
                    576:     }
                    577: 
                    578:     function pullDownSelection(selectOne) {
                    579: 	var selection="";
                    580: 	if (selectOne.length > 1) {
                    581: 	    for (var i=0; i<selectOne.length; i++) {
                    582: 		if (selectOne[i].selected) {
                    583: 		    return selectOne[i].value;
                    584: 		}
                    585: 	    }
                    586: 	} else {
1.138     albertel  587:             // only one value it must be the selected one
                    588: 	    return selectOne.value;
1.118     ng        589: 	}
                    590:     }
                    591: </script>
                    592: COMMONJSFUNCTIONS
                    593: }
                    594: 
1.44      ng        595: #--- Dumps the class list with usernames,list of sections,
                    596: #--- section, ids and fullnames for each user.
                    597: sub getclasslist {
1.449     banghart  598:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  599:     my @getsec;
1.450     banghart  600:     my @getgroup;
1.442     banghart  601:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  602:     if (!ref($getsec)) {
                    603: 	if ($getsec ne '' && $getsec ne 'all') {
                    604: 	    @getsec=($getsec);
                    605: 	}
                    606:     } else {
                    607: 	@getsec=@{$getsec};
                    608:     }
                    609:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  610:     if (!ref($getgroup)) {
                    611: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    612: 	    @getgroup=($getgroup);
                    613: 	}
                    614:     } else {
                    615: 	@getgroup=@{$getgroup};
                    616:     }
                    617:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  618: 
1.449     banghart  619:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  620:     # Bail out if we were unable to get the classlist
1.56      matthew   621:     return if (! defined($classlist));
1.449     banghart  622:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   623:     #
                    624:     my %sections;
                    625:     my %fullnames;
1.205     matthew   626:     foreach my $student (keys(%$classlist)) {
                    627:         my $end      = 
                    628:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    629:         my $start    = 
                    630:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    631:         my $id       = 
                    632:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    633:         my $section  = 
                    634:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    635:         my $fullname = 
                    636:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    637:         my $status   = 
                    638:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  639:         my $group   = 
                    640:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        641: 	# filter students according to status selected
1.442     banghart  642: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    643: 	    if (!($stu_status =~ $status)) {
1.450     banghart  644: 		delete($classlist->{$student});
1.76      ng        645: 		next;
                    646: 	    }
                    647: 	}
1.450     banghart  648: 	# filter students according to groups selected
1.453     banghart  649: 	my @stu_groups = split(/,/,$group);
1.450     banghart  650: 	if (@getgroup) {
                    651: 	    my $exclude = 1;
1.454     banghart  652: 	    foreach my $grp (@getgroup) {
                    653: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  654: 	            if ($stu_group eq $grp) {
                    655: 	                $exclude = 0;
                    656:     	            } 
1.450     banghart  657: 	        }
1.453     banghart  658:     	        if (($grp eq 'none') && !$group) {
                    659:         	        $exclude = 0;
                    660:         	}
1.450     banghart  661: 	    }
                    662: 	    if ($exclude) {
                    663: 	        delete($classlist->{$student});
                    664: 	    }
                    665: 	}
1.205     matthew   666: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  667: 	if (&canview($section)) {
1.291     albertel  668: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  669: 		$sections{$section}++;
1.450     banghart  670: 		if ($classlist->{$student}) {
                    671: 		    $fullnames{$student}=$fullname;
                    672: 		}
1.103     albertel  673: 	    } else {
1.205     matthew   674: 		delete($classlist->{$student});
1.103     albertel  675: 	    }
                    676: 	} else {
1.205     matthew   677: 	    delete($classlist->{$student});
1.103     albertel  678: 	}
1.44      ng        679:     }
                    680:     my %seen = ();
1.56      matthew   681:     my @sections = sort(keys(%sections));
                    682:     return ($classlist,\@sections,\%fullnames);
1.44      ng        683: }
                    684: 
1.103     albertel  685: sub canmodify {
                    686:     my ($sec)=@_;
                    687:     if ($perm{'mgr'}) {
                    688: 	if (!defined($perm{'mgr_section'})) {
                    689: 	    # can modify whole class
                    690: 	    return 1;
                    691: 	} else {
                    692: 	    if ($sec eq $perm{'mgr_section'}) {
                    693: 		#can modify the requested section
                    694: 		return 1;
                    695: 	    } else {
                    696: 		# can't modify the request section
                    697: 		return 0;
                    698: 	    }
                    699: 	}
                    700:     }
                    701:     #can't modify
                    702:     return 0;
                    703: }
                    704: 
                    705: sub canview {
                    706:     my ($sec)=@_;
                    707:     if ($perm{'vgr'}) {
                    708: 	if (!defined($perm{'vgr_section'})) {
                    709: 	    # can modify whole class
                    710: 	    return 1;
                    711: 	} else {
                    712: 	    if ($sec eq $perm{'vgr_section'}) {
                    713: 		#can modify the requested section
                    714: 		return 1;
                    715: 	    } else {
                    716: 		# can't modify the request section
                    717: 		return 0;
                    718: 	    }
                    719: 	}
                    720:     }
                    721:     #can't modify
                    722:     return 0;
                    723: }
                    724: 
1.44      ng        725: #--- Retrieve the grade status of a student for all the parts
                    726: sub student_gradeStatus {
1.324     albertel  727:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  728:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        729:     my %partstatus = ();
                    730:     foreach (@$partlist) {
1.128     ng        731: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        732: 	$status              = 'nothing' if ($status eq '');
                    733: 	$partstatus{$_}      = $status;
                    734: 	my $subkey           = "resource.$_.submitted_by";
                    735: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    736:     }
                    737:     return %partstatus;
                    738: }
                    739: 
1.45      ng        740: # hidden form and javascript that calls the form
                    741: # Use by verifyscript and viewgrades
                    742: # Shows a student's view of problem and submission
                    743: sub jscriptNform {
1.324     albertel  744:     my ($symb) = @_;
1.442     banghart  745:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        746:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    747: 	'    function viewOneStudent(user,domain) {'."\n".
                    748: 	'	document.onestudent.student.value = user;'."\n".
                    749: 	'	document.onestudent.userdom.value = domain;'."\n".
                    750: 	'	document.onestudent.submit();'."\n".
                    751: 	'    }'."\n".
                    752: 	'</script>'."\n";
                    753:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  754: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  755: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    756: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  757: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        758: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    759: 	'<input type="hidden" name="student" value="" />'."\n".
                    760: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    761: 	'</form>'."\n";
                    762:     return $jscript;
                    763: }
1.39      ng        764: 
1.447     foxr      765: 
                    766: 
1.315     bowersj2  767: # Given the score (as a number [0-1] and the weight) what is the final
                    768: # point value? This function will round to the nearest tenth, third,
                    769: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  770: sub compute_points {
1.315     bowersj2  771:     my ($score, $weight) = @_;
                    772:     
                    773:     my $tolerance = .00001;
                    774:     my $points = $score * $weight;
                    775: 
                    776:     # Check for nearness to 1/x.
                    777:     my $check_for_nearness = sub {
                    778:         my ($factor) = @_;
                    779:         my $num = ($points * $factor) + $tolerance;
                    780:         my $floored_num = floor($num);
1.316     albertel  781:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  782:             return $floored_num / $factor;
                    783:         }
                    784:         return $points;
                    785:     };
                    786: 
                    787:     $points = $check_for_nearness->(10);
                    788:     $points = $check_for_nearness->(3);
                    789:     $points = $check_for_nearness->(4);
                    790:     
                    791:     return $points;
                    792: }
                    793: 
1.44      ng        794: #------------------ End of general use routines --------------------
1.87      www       795: 
                    796: #
                    797: # Find most similar essay
                    798: #
                    799: 
                    800: sub most_similar {
1.426     albertel  801:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       802: 
                    803: # ignore spaces and punctuation
                    804: 
                    805:     $uessay=~s/\W+/ /gs;
                    806: 
1.282     www       807: # ignore empty submissions (occuring when only files are sent)
                    808: 
                    809:     unless ($uessay=~/\w+/) { return ''; }
                    810: 
1.87      www       811: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       812:     my $limit=0.6;
1.87      www       813:     my $sname='';
                    814:     my $sdom='';
                    815:     my $scrsid='';
                    816:     my $sessay='';
                    817: # go through all essays ...
1.426     albertel  818:     foreach my $tkey (keys(%$old_essays)) {
                    819: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       820: # ... except the same student
1.426     albertel  821:         next if (($tname eq $uname) && ($tdom eq $udom));
                    822: 	my $tessay=$old_essays->{$tkey};
                    823: 	$tessay=~s/\W+/ /gs;
1.87      www       824: # String similarity gives up if not even limit
1.426     albertel  825: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       826: # Found one
1.426     albertel  827: 	if ($tsimilar>$limit) {
                    828: 	    $limit=$tsimilar;
                    829: 	    $sname=$tname;
                    830: 	    $sdom=$tdom;
                    831: 	    $scrsid=$tcrsid;
                    832: 	    $sessay=$old_essays->{$tkey};
                    833: 	}
1.87      www       834:     }
1.88      www       835:     if ($limit>0.6) {
1.87      www       836:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    837:     } else {
                    838:        return ('','','','',0);
                    839:     }
                    840: }
                    841: 
1.44      ng        842: #-------------------------------------------------------------------
                    843: 
                    844: #------------------------------------ Receipt Verification Routines
1.45      ng        845: #
1.44      ng        846: #--- Check whether a receipt number is valid.---
                    847: sub verifyreceipt {
                    848:     my $request  = shift;
                    849: 
1.257     albertel  850:     my $courseid = $env{'request.course.id'};
1.184     www       851:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  852: 	$env{'form.receipt'};
1.44      ng        853:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  854:     my ($symb)   = &get_symb($request);
1.44      ng        855: 
1.487     albertel  856:     my $title.=
                    857: 	'<h3><span class="LC_info">'.
                    858: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    859: 	'</span></h3>'."\n".
                    860: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    861: 	'</h4>'."\n";
1.44      ng        862: 
                    863:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   864:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  865:     
                    866:     my $receiptparts=0;
1.390     albertel  867:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    868: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  869:     my $parts=['0'];
1.324     albertel  870:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  871:     
                    872:     my $header = 
                    873: 	&Apache::loncommon::start_data_table().
                    874: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  875: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    876: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    877: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  878:     if ($receiptparts) {
1.487     albertel  879: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  880:     }
                    881:     $header.=
                    882: 	&Apache::loncommon::end_data_table_header_row();
                    883: 
1.294     albertel  884:     foreach (sort 
                    885: 	     {
                    886: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    887: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    888: 		 }
                    889: 		 return $a cmp $b;
                    890: 	     } (keys(%$fullname))) {
1.44      ng        891: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  892: 	foreach my $part (@$parts) {
                    893: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  894: 		$contents.=
                    895: 		    &Apache::loncommon::start_data_table_row().
                    896: 		    '<td>&nbsp;'."\n".
1.177     albertel  897: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  898: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  899: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    900: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    901: 		if ($receiptparts) {
                    902: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    903: 		}
1.486     albertel  904: 		$contents.= 
                    905: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  906: 		
                    907: 		$matches++;
                    908: 	    }
1.44      ng        909: 	}
                    910:     }
                    911:     if ($matches == 0) {
1.487     albertel  912: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        913:     } else {
1.324     albertel  914: 	$string = &jscriptNform($symb).$title.
1.487     albertel  915: 	    '<p>'.
                    916: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    917: 	    '</p>'.
1.486     albertel  918: 	    $header.
                    919: 	    $contents.
                    920: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        921:     }
1.324     albertel  922:     return $string.&show_grading_menu_form($symb);
1.44      ng        923: }
                    924: 
                    925: #--- This is called by a number of programs.
                    926: #--- Called from the Grading Menu - View/Grade an individual student
                    927: #--- Also called directly when one clicks on the subm button 
                    928: #    on the problem page.
1.30      ng        929: sub listStudents {
1.41      ng        930:     my ($request) = shift;
1.49      albertel  931: 
1.324     albertel  932:     my ($symb) = &get_symb($request);
1.257     albertel  933:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    934:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    935:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  936:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  937:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    938:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    939:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    940: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  941: 
1.485     albertel  942:     my $result='<h3><span class="LC_info">&nbsp;'.
                    943: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    944: 	.'</span></h3>';
1.118     ng        945: 
1.324     albertel  946:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  947: 
1.485     albertel  948:     my %lt = ( 'multiple' =>
                    949: 	       "Please select a student or group of students before clicking on the Next button.",
                    950: 	       'single'   =>
                    951: 	       "Please select the student before clicking on the Next button.",
                    952: 	       );
                    953:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        954:     $request->print(<<LISTJAVASCRIPT);
                    955: <script type="text/javascript" language="javascript">
1.110     ng        956:     function checkSelect(checkBox) {
                    957: 	var ctr=0;
                    958: 	var sense="";
                    959: 	if (checkBox.length > 1) {
                    960: 	    for (var i=0; i<checkBox.length; i++) {
                    961: 		if (checkBox[i].checked) {
                    962: 		    ctr++;
                    963: 		}
                    964: 	    }
1.485     albertel  965: 	    sense = '$lt{'multiple'}';
1.110     ng        966: 	} else {
                    967: 	    if (checkBox.checked) {
                    968: 		ctr = 1;
                    969: 	    }
1.485     albertel  970: 	    sense = '$lt{'single'}';
1.110     ng        971: 	}
                    972: 	if (ctr == 0) {
1.485     albertel  973: 	    alert(sense);
1.110     ng        974: 	    return false;
                    975: 	}
                    976: 	document.gradesub.submit();
                    977:     }
                    978: 
                    979:     function reLoadList(formname) {
1.112     ng        980: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        981: 	formname.command.value = 'submission';
                    982: 	formname.submit();
                    983:     }
1.45      ng        984: </script>
                    985: LISTJAVASCRIPT
                    986: 
1.118     ng        987:     &commonJSfunctions($request);
1.41      ng        988:     $request->print($result);
1.39      ng        989: 
1.401     albertel  990:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    991:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  992:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  993: 	"\n".$table;
                    994: 	
                    995:     $gradeTable .= 
                    996: 	'&nbsp;'.
                    997: 	&mt('<b>View Problem Text: </b>[_1]',
                    998: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    999: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                   1000: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                   1001:     $gradeTable .= 
                   1002: 	'&nbsp;'.
                   1003: 	&mt('<b>View Answer: </b>[_1]',
                   1004: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                   1005: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                   1006: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                   1007: 
                   1008:     my $submission_options;
1.257     albertel 1009:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel 1010: 	$submission_options.=
                   1011: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel 1012:     }
1.442     banghart 1013:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   1014:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel 1015:     $env{'form.Status'} = $saveStatus;
1.485     albertel 1016:     $submission_options.=
                   1017: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                   1018: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                   1019: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                   1020: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                   1021:     $gradeTable .= 
                   1022: 	'&nbsp;'.
                   1023: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                   1024: 
                   1025:     $gradeTable .= 
                   1026:         '&nbsp;'.
                   1027: 	&mt('<b>Grading Increments:</b> [_1]',
                   1028: 	    '<select name="increment">'.
                   1029: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                   1030: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                   1031: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                   1032: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                   1033: 	    '</select>');
                   1034:     
                   1035:     $gradeTable .= 
1.432     banghart 1036:         &build_section_inputs().
1.45      ng       1037: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel 1038: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                   1039: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                   1040: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                   1041: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel 1042: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng       1043: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                   1044: 
1.257     albertel 1045:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart 1046: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng       1047:     } else {
1.485     albertel 1048: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                   1049: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng       1050:     }
1.112     ng       1051: 
1.485     albertel 1052:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                   1053: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng       1054: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel 1055: 
                   1056: # checkall buttons
                   1057:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng       1058:     $gradeTable.='<input type="button" '."\n".
1.45      ng       1059: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel 1060: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel 1061:     $gradeTable.=&check_buttons();
1.485     albertel 1062:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart 1063:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel 1064:     $gradeTable.= &Apache::loncommon::start_data_table().
                   1065: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng       1066:     my $loop = 0;
                   1067:     while ($loop < 2) {
1.485     albertel 1068: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                   1069: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel 1070: 	if ($env{'form.showgrading'} eq 'yes' 
                   1071: 	    && $submitonly ne 'queued'
                   1072: 	    && $submitonly ne 'all') {
1.485     albertel 1073: 	    foreach my $part (sort(@$partlist)) {
                   1074: 		my $display_part=
                   1075: 		    &get_display_part((split(/_/,$part))[0],$symb);
                   1076: 		$gradeTable.=
                   1077: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng       1078: 	    }
1.301     albertel 1079: 	} elsif ($submitonly eq 'queued') {
1.474     albertel 1080: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng       1081: 	}
                   1082: 	$loop++;
1.126     ng       1083: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng       1084:     }
1.474     albertel 1085:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng       1086: 
1.45      ng       1087:     my $ctr = 0;
1.294     albertel 1088:     foreach my $student (sort 
                   1089: 			 {
                   1090: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   1091: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   1092: 			     }
                   1093: 			     return $a cmp $b;
                   1094: 			 }
                   1095: 			 (keys(%$fullname))) {
1.41      ng       1096: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 1097: 
1.110     ng       1098: 	my %status = ();
1.301     albertel 1099: 
                   1100: 	if ($submitonly eq 'queued') {
                   1101: 	    my %queue_status = 
                   1102: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   1103: 							$udom,$uname);
                   1104: 	    next if (!defined($queue_status{'gradingqueue'}));
                   1105: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                   1106: 	}
                   1107: 
                   1108: 	if ($env{'form.showgrading'} eq 'yes' 
                   1109: 	    && $submitonly ne 'queued'
                   1110: 	    && $submitonly ne 'all') {
1.324     albertel 1111: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 1112: 	    my $submitted = 0;
1.164     albertel 1113: 	    my $graded = 0;
1.248     albertel 1114: 	    my $incorrect = 0;
1.110     ng       1115: 	    foreach (keys(%status)) {
1.145     albertel 1116: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 1117: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1118: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1119: 		
1.110     ng       1120: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1121: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1122: 		    $submitted = 0;
1.150     albertel 1123: 		    my ($part)=split(/\./,$partid);
1.110     ng       1124: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1125: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1126: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1127: 		}
1.41      ng       1128: 	    }
1.248     albertel 1129: 	    
1.156     albertel 1130: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1131: 				     $submitonly eq 'incorrect' ||
                   1132: 				     $submitonly eq 'graded'));
1.248     albertel 1133: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1134: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1135: 	}
1.34      ng       1136: 
1.45      ng       1137: 	$ctr++;
1.249     albertel 1138: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1139:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1140: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1141: 	    if ($ctr%2 ==1) {
                   1142: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1143: 	    }
1.126     ng       1144: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1145:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1146:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1147: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1148: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1149: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1150: 
1.257     albertel 1151: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1152: 		foreach (sort(keys(%status))) {
1.485     albertel 1153: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1154: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1155: 		}
1.41      ng       1156: 	    }
1.126     ng       1157: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1158: 	    if ($ctr%2 ==0) {
                   1159: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1160: 	    }
1.41      ng       1161: 	}
                   1162:     }
1.110     ng       1163:     if ($ctr%2 ==1) {
1.126     ng       1164: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1165: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1166: 		&& $submitonly ne 'queued'
                   1167: 		&& $submitonly ne 'all') {
1.110     ng       1168: 		foreach (@$partlist) {
                   1169: 		    $gradeTable.='<td>&nbsp;</td>';
                   1170: 		}
1.301     albertel 1171: 	    } elsif ($submitonly eq 'queued') {
                   1172: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1173: 	    }
1.474     albertel 1174: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1175:     }
                   1176: 
1.474     albertel 1177:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1178: 	'<input type="button" '.
                   1179: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1180: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1181:     if ($ctr == 0) {
1.96      albertel 1182: 	my $num_students=(scalar(keys(%$fullname)));
                   1183: 	if ($num_students eq 0) {
1.485     albertel 1184: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1185: 	} else {
1.171     albertel 1186: 	    my $submissions='submissions';
                   1187: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1188: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1189: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1190: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1191: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1192: 		    $num_students).
                   1193: 		'</span><br />';
1.96      albertel 1194: 	}
1.46      ng       1195:     } elsif ($ctr == 1) {
1.474     albertel 1196: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1197:     }
1.324     albertel 1198:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1199:     $request->print($gradeTable);
1.44      ng       1200:     return '';
1.10      ng       1201: }
                   1202: 
1.44      ng       1203: #---- Called from the listStudents routine
1.249     albertel 1204: 
                   1205: sub check_script {
                   1206:     my ($form, $type)=@_;
                   1207:     my $chkallscript='<script type="text/javascript">
                   1208:     function checkall() {
                   1209:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1210:             ele = document.forms.'.$form.'.elements[i];
                   1211:             if (ele.name == "'.$type.'") {
                   1212:             document.forms.'.$form.'.elements[i].checked=true;
                   1213:                                        }
                   1214:         }
                   1215:     }
                   1216: 
                   1217:     function checksec() {
                   1218:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1219:             ele = document.forms.'.$form.'.elements[i];
                   1220:            string = document.forms.'.$form.'.chksec.value;
                   1221:            if
                   1222:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1223:               document.forms.'.$form.'.elements[i].checked=true;
                   1224:             }
                   1225:         }
                   1226:     }
                   1227: 
                   1228: 
                   1229:     function uncheckall() {
                   1230:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1231:             ele = document.forms.'.$form.'.elements[i];
                   1232:             if (ele.name == "'.$type.'") {
                   1233:             document.forms.'.$form.'.elements[i].checked=false;
                   1234:                                        }
                   1235:         }
                   1236:     }
                   1237: 
                   1238: </script>'."\n";
                   1239:     return $chkallscript;
                   1240: }
                   1241: 
                   1242: sub check_buttons {
1.485     albertel 1243:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1244:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1245:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1246:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1247:     return $buttons;
                   1248: }
                   1249: 
1.44      ng       1250: #     Displays the submissions for one student or a group of students
1.34      ng       1251: sub processGroup {
1.41      ng       1252:     my ($request)  = shift;
                   1253:     my $ctr        = 0;
1.155     albertel 1254:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1255:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1256: 
1.396     banghart 1257:     foreach my $student (@stuchecked) {
                   1258: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1259: 	$env{'form.student'}        = $uname;
                   1260: 	$env{'form.userdom'}        = $udom;
                   1261: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1262: 	&submission($request,$ctr,$total);
                   1263: 	$ctr++;
                   1264:     }
                   1265:     return '';
1.35      ng       1266: }
1.34      ng       1267: 
1.44      ng       1268: #------------------------------------------------------------------------------------
                   1269: #
                   1270: #-------------------------- Next few routines handles grading by student, essentially
                   1271: #                           handles essay response type problem/part
                   1272: #
                   1273: #--- Javascript to handle the submission page functionality ---
                   1274: sub sub_page_js {
                   1275:     my $request = shift;
                   1276:     $request->print(<<SUBJAVASCRIPT);
                   1277: <script type="text/javascript" language="javascript">
1.71      ng       1278:     function updateRadio(formname,id,weight) {
1.125     ng       1279: 	var gradeBox = formname["GD_BOX"+id];
                   1280: 	var radioButton = formname["RADVAL"+id];
                   1281: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1282: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1283: 	gradeBox.value = pts;
                   1284: 	var resetbox = false;
                   1285: 	if (isNaN(pts) || pts < 0) {
                   1286: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1287: 	    for (var i=0; i<radioButton.length; i++) {
                   1288: 		if (radioButton[i].checked) {
                   1289: 		    gradeBox.value = i;
                   1290: 		    resetbox = true;
                   1291: 		}
                   1292: 	    }
                   1293: 	    if (!resetbox) {
                   1294: 		formtextbox.value = "";
                   1295: 	    }
                   1296: 	    return;
1.44      ng       1297: 	}
1.71      ng       1298: 
                   1299: 	if (pts > weight) {
                   1300: 	    var resp = confirm("You entered a value ("+pts+
                   1301: 			       ") greater than the weight for the part. Accept?");
                   1302: 	    if (resp == false) {
1.125     ng       1303: 		gradeBox.value = oldpts;
1.71      ng       1304: 		return;
                   1305: 	    }
1.44      ng       1306: 	}
1.13      albertel 1307: 
1.71      ng       1308: 	for (var i=0; i<radioButton.length; i++) {
                   1309: 	    radioButton[i].checked=false;
                   1310: 	    if (pts == i && pts != "") {
                   1311: 		radioButton[i].checked=true;
                   1312: 	    }
                   1313: 	}
                   1314: 	updateSelect(formname,id);
1.125     ng       1315: 	formname["stores"+id].value = "0";
1.41      ng       1316:     }
1.5       albertel 1317: 
1.72      ng       1318:     function writeBox(formname,id,pts) {
1.125     ng       1319: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1320: 	if (checkSolved(formname,id) == 'update') {
                   1321: 	    gradeBox.value = pts;
                   1322: 	} else {
1.125     ng       1323: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1324: 	    gradeBox.value = oldpts;
1.125     ng       1325: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1326: 	    for (var i=0; i<radioButton.length; i++) {
                   1327: 		radioButton[i].checked=false;
1.72      ng       1328: 		if (i == oldpts) {
1.71      ng       1329: 		    radioButton[i].checked=true;
                   1330: 		}
                   1331: 	    }
1.41      ng       1332: 	}
1.125     ng       1333: 	formname["stores"+id].value = "0";
1.71      ng       1334: 	updateSelect(formname,id);
                   1335: 	return;
1.41      ng       1336:     }
1.44      ng       1337: 
1.71      ng       1338:     function clearRadBox(formname,id) {
                   1339: 	if (checkSolved(formname,id) == 'noupdate') {
                   1340: 	    updateSelect(formname,id);
                   1341: 	    return;
                   1342: 	}
1.125     ng       1343: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1344: 	for (var i=0; i<gradeSelect.length; i++) {
                   1345: 	    if (gradeSelect[i].selected) {
                   1346: 		var selectx=i;
                   1347: 	    }
                   1348: 	}
1.125     ng       1349: 	var stores = formname["stores"+id];
1.71      ng       1350: 	if (selectx == stores.value) { return };
1.125     ng       1351: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1352: 	gradeBox.value = "";
1.125     ng       1353: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1354: 	for (var i=0; i<radioButton.length; i++) {
                   1355: 	    radioButton[i].checked=false;
                   1356: 	}
                   1357: 	stores.value = selectx;
                   1358:     }
1.5       albertel 1359: 
1.71      ng       1360:     function checkSolved(formname,id) {
1.125     ng       1361: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1362: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1363: 	    if (!reply) {return "noupdate";}
1.120     ng       1364: 	    formname.overRideScore.value = 'yes';
1.41      ng       1365: 	}
1.71      ng       1366: 	return "update";
1.13      albertel 1367:     }
1.71      ng       1368: 
                   1369:     function updateSelect(formname,id) {
1.125     ng       1370: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1371: 	return;
1.41      ng       1372:     }
1.33      ng       1373: 
1.121     ng       1374: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1375:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1376: 	formname.gradeOpt.value = val;
1.71      ng       1377: 	if (val == "Save & Next") {
                   1378: 	    for (i=0;i<=total;i++) {
                   1379: 		for (j=0;j<parttot;j++) {
1.125     ng       1380: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1381: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1382: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1383: 			if (points == "") {
1.125     ng       1384: 			    var name = formname["name"+i].value;
1.129     ng       1385: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1386: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1387: 					       ", part "+partid+". Continue?");
1.71      ng       1388: 			    if (resp == false) {
1.125     ng       1389: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1390: 				return false;
                   1391: 			    }
                   1392: 			}
                   1393: 		    }
                   1394: 		    
                   1395: 		}
                   1396: 	    }
                   1397: 	    
                   1398: 	}
1.121     ng       1399: 	if (val == "Grade Student") {
                   1400: 	    formname.showgrading.value = "yes";
                   1401: 	    if (formname.Status.value == "") {
                   1402: 		formname.Status.value = "Active";
                   1403: 	    }
                   1404: 	    formname.studentNo.value = total;
                   1405: 	}
1.120     ng       1406: 	formname.submit();
                   1407:     }
                   1408: 
1.71      ng       1409: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1410:     function checkSubmitPage(formname,total) {
                   1411: 	noscore = new Array(100);
                   1412: 	var ptr = 0;
                   1413: 	for (i=1;i<total;i++) {
1.125     ng       1414: 	    var partid = formname["q_"+i].value;
1.127     ng       1415: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1416: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1417: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1418: 		if (points == "" && status != "correct_by_student") {
                   1419: 		    noscore[ptr] = i;
                   1420: 		    ptr++;
                   1421: 		}
                   1422: 	    }
                   1423: 	}
                   1424: 	if (ptr != 0) {
                   1425: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1426: 	    var prolist = "";
                   1427: 	    if (ptr == 1) {
                   1428: 		prolist = noscore[0];
                   1429: 	    } else {
                   1430: 		var i = 0;
                   1431: 		while (i < ptr-1) {
                   1432: 		    prolist += noscore[i]+", ";
                   1433: 		    i++;
                   1434: 		}
                   1435: 		prolist += "and "+noscore[i];
                   1436: 	    }
                   1437: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1438: 	    if (resp == false) {
                   1439: 		return false;
                   1440: 	    }
                   1441: 	}
1.45      ng       1442: 
1.71      ng       1443: 	formname.submit();
                   1444:     }
                   1445: </script>
                   1446: SUBJAVASCRIPT
                   1447: }
1.45      ng       1448: 
1.71      ng       1449: #--- javascript for essay type problem --
                   1450: sub sub_page_kw_js {
                   1451:     my $request = shift;
1.80      ng       1452:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1453:     &commonJSfunctions($request);
1.350     albertel 1454: 
1.351     albertel 1455:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1456:     <script text="text/javascript">
                   1457:     function checkInput() {
                   1458:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1459:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1460:       var usrctr = document.msgcenter.usrctr.value;
                   1461:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1462:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1463: 
                   1464:       var msgchk = "";
                   1465:       if (document.msgcenter.subchk.checked) {
                   1466:          msgchk = "msgsub,";
                   1467:       }
                   1468:       var includemsg = 0;
                   1469:       for (var i=1; i<=nmsg; i++) {
                   1470:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1471:           var frmmsg = document.msgcenter["msg"+i];
                   1472:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1473:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1474:           showflg.value = "1";
                   1475:           var chkbox = document.msgcenter["msgn"+i];
                   1476:           if (chkbox.checked) {
                   1477:              msgchk += "savemsg"+i+",";
                   1478:              includemsg = 1;
                   1479:           }
                   1480:       }
                   1481:       if (document.msgcenter.newmsgchk.checked) {
                   1482:          msgchk += "newmsg"+usrctr;
                   1483:          includemsg = 1;
                   1484:       }
                   1485:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1486:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1487:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1488:       includemsg.value = msgchk;
                   1489: 
                   1490:       self.close()
                   1491: 
                   1492:     }
                   1493:     </script>
                   1494: INNERJS
                   1495: 
1.351     albertel 1496:     my $inner_js_highlight_central=<<INNERJS;
                   1497:  <script type="text/javascript">
                   1498:     function updateChoice(flag) {
                   1499:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1500:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1501:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1502:       opener.document.SCORE.refresh.value = "on";
                   1503:       if (opener.document.SCORE.keywords.value!=""){
                   1504:          opener.document.SCORE.submit();
                   1505:       }
                   1506:       self.close()
                   1507:     }
                   1508: </script>
                   1509: INNERJS
                   1510: 
                   1511:     my $start_page_msg_central = 
                   1512:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1513: 				       {'js_ready'  => 1,
                   1514: 					'only_body' => 1,
                   1515: 					'bgcolor'   =>'#FFFFFF',});
                   1516:     my $end_page_msg_central = 
                   1517: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1518: 
                   1519: 
                   1520:     my $start_page_highlight_central = 
                   1521:         &Apache::loncommon::start_page('Highlight Central',
                   1522: 				       $inner_js_highlight_central,
1.350     albertel 1523: 				       {'js_ready'  => 1,
                   1524: 					'only_body' => 1,
                   1525: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1526:     my $end_page_highlight_central = 
1.350     albertel 1527: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1528: 
1.219     www      1529:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1530:     $docopen=~s/^document\.//;
1.71      ng       1531:     $request->print(<<SUBJAVASCRIPT);
                   1532: <script type="text/javascript" language="javascript">
1.45      ng       1533: 
1.44      ng       1534: //===================== Show list of keywords ====================
1.122     ng       1535:   function keywords(formname) {
                   1536:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1537:     if (nret==null) return;
1.122     ng       1538:     formname.keywords.value = nret;
1.44      ng       1539: 
1.122     ng       1540:     if (formname.keywords.value != "") {
1.128     ng       1541: 	formname.refresh.value = "on";
1.122     ng       1542: 	formname.submit();
1.44      ng       1543:     }
                   1544:     return;
                   1545:   }
                   1546: 
                   1547: //===================== Script to view submitted by ==================
                   1548:   function viewSubmitter(submitter) {
                   1549:     document.SCORE.refresh.value = "on";
                   1550:     document.SCORE.NCT.value = "1";
                   1551:     document.SCORE.unamedom0.value = submitter;
                   1552:     document.SCORE.submit();
                   1553:     return;
                   1554:   }
                   1555: 
                   1556: //===================== Script to add keyword(s) ==================
                   1557:   function getSel() {
                   1558:     if (document.getSelection) txt = document.getSelection();
                   1559:     else if (document.selection) txt = document.selection.createRange().text;
                   1560:     else return;
                   1561:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1562:     if (cleantxt=="") {
1.46      ng       1563: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1564: 	return;
                   1565:     }
                   1566:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1567:     if (nret==null) return;
1.127     ng       1568:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1569:     if (document.SCORE.keywords.value != "") {
1.127     ng       1570: 	document.SCORE.refresh.value = "on";
1.44      ng       1571: 	document.SCORE.submit();
                   1572:     }
                   1573:     return;
                   1574:   }
                   1575: 
                   1576: //====================== Script for composing message ==============
1.80      ng       1577:    // preload images
                   1578:    img1 = new Image();
                   1579:    img1.src = "$iconpath/mailbkgrd.gif";
                   1580:    img2 = new Image();
                   1581:    img2.src = "$iconpath/mailto.gif";
                   1582: 
1.44      ng       1583:   function msgCenter(msgform,usrctr,fullname) {
                   1584:     var Nmsg  = msgform.savemsgN.value;
                   1585:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1586:     var subject = msgform.msgsub.value;
1.127     ng       1587:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1588:     re = /msgsub/;
                   1589:     var shwsel = "";
                   1590:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1591:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1592:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1593:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1594: 	var testmsg = "savemsg"+i+",";
                   1595: 	re = new RegExp(testmsg,"g");
1.44      ng       1596: 	shwsel = "";
                   1597: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1598: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1599: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1600: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1601: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1602:     }
1.125     ng       1603:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1604:     shwsel = "";
                   1605:     re = /newmsg/;
                   1606:     if (re.test(msgchk)) { shwsel = "checked" }
                   1607:     newMsg(newmsg,shwsel);
                   1608:     msgTail(); 
                   1609:     return;
                   1610:   }
                   1611: 
1.123     ng       1612:   function checkEntities(strx) {
                   1613:     if (strx.length == 0) return strx;
                   1614:     var orgStr = ["&", "<", ">", '"']; 
                   1615:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1616:     var counter = 0;
                   1617:     while (counter < 4) {
                   1618: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1619: 	counter++;
                   1620:     }
                   1621:     return strx;
                   1622:   }
                   1623: 
                   1624:   function strReplace(strx, orgStr, newStr) {
                   1625:     return strx.split(orgStr).join(newStr);
                   1626:   }
                   1627: 
1.44      ng       1628:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1629:     var height = 70*Nmsg+250;
1.44      ng       1630:     var scrollbar = "no";
                   1631:     if (height > 600) {
                   1632: 	height = 600;
                   1633: 	scrollbar = "yes";
                   1634:     }
1.118     ng       1635:     var xpos = (screen.width-600)/2;
                   1636:     xpos = (xpos < 0) ? '0' : xpos;
                   1637:     var ypos = (screen.height-height)/2-30;
                   1638:     ypos = (ypos < 0) ? '0' : ypos;
                   1639: 
1.206     albertel 1640:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1641:     pWin.focus();
                   1642:     pDoc = pWin.document;
1.219     www      1643:     pDoc.$docopen;
1.351     albertel 1644:     pDoc.write('$start_page_msg_central');
1.76      ng       1645: 
                   1646:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1647:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1648:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1649: 
                   1650:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1651:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1652:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1653: }
                   1654:     function displaySubject(msg,shwsel) {
1.76      ng       1655:     pDoc = pWin.document;
                   1656:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1657:     pDoc.write("<td>Subject<\\/td>");
                   1658:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1659:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1660: }
                   1661: 
1.72      ng       1662:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1663:     pDoc = pWin.document;
                   1664:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1665:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1666:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1667:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1668: }
                   1669: 
                   1670:   function newMsg(newmsg,shwsel) {
1.76      ng       1671:     pDoc = pWin.document;
                   1672:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1673:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1674:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1675:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1676: }
                   1677: 
                   1678:   function msgTail() {
1.76      ng       1679:     pDoc = pWin.document;
1.465     albertel 1680:     pDoc.write("<\\/table>");
                   1681:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1682:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1683:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1684:     pDoc.write("<\\/form>");
1.351     albertel 1685:     pDoc.write('$end_page_msg_central');
1.128     ng       1686:     pDoc.close();
1.44      ng       1687: }
                   1688: 
                   1689: //====================== Script for keyword highlight options ==============
                   1690:   function kwhighlight() {
                   1691:     var kwclr    = document.SCORE.kwclr.value;
                   1692:     var kwsize   = document.SCORE.kwsize.value;
                   1693:     var kwstyle  = document.SCORE.kwstyle.value;
                   1694:     var redsel = "";
                   1695:     var grnsel = "";
                   1696:     var blusel = "";
                   1697:     if (kwclr=="red")   {var redsel="checked"};
                   1698:     if (kwclr=="green") {var grnsel="checked"};
                   1699:     if (kwclr=="blue")  {var blusel="checked"};
                   1700:     var sznsel = "";
                   1701:     var sz1sel = "";
                   1702:     var sz2sel = "";
                   1703:     if (kwsize=="0")  {var sznsel="checked"};
                   1704:     if (kwsize=="+1") {var sz1sel="checked"};
                   1705:     if (kwsize=="+2") {var sz2sel="checked"};
                   1706:     var synsel = "";
                   1707:     var syisel = "";
                   1708:     var sybsel = "";
                   1709:     if (kwstyle=="")    {var synsel="checked"};
                   1710:     if (kwstyle=="<i>") {var syisel="checked"};
                   1711:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1712:     highlightCentral();
                   1713:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1714:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1715:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1716:     highlightend();
                   1717:     return;
                   1718:   }
                   1719: 
                   1720:   function highlightCentral() {
1.76      ng       1721: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1722:     var xpos = (screen.width-400)/2;
                   1723:     xpos = (xpos < 0) ? '0' : xpos;
                   1724:     var ypos = (screen.height-330)/2-30;
                   1725:     ypos = (ypos < 0) ? '0' : ypos;
                   1726: 
1.206     albertel 1727:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1728:     hwdWin.focus();
                   1729:     var hDoc = hwdWin.document;
1.219     www      1730:     hDoc.$docopen;
1.351     albertel 1731:     hDoc.write('$start_page_highlight_central');
1.76      ng       1732:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1733:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1734: 
                   1735:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1736:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1737:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1738:   }
                   1739: 
                   1740:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1741:     var hDoc = hwdWin.document;
                   1742:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1743:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1744:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1745:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1746:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1747:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1748:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1749:     hDoc.write("<\\/tr>");
1.44      ng       1750:   }
                   1751: 
                   1752:   function highlightend() { 
1.76      ng       1753:     var hDoc = hwdWin.document;
1.465     albertel 1754:     hDoc.write("<\\/table>");
                   1755:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1756:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1757:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1758:     hDoc.write("<\\/form>");
1.351     albertel 1759:     hDoc.write('$end_page_highlight_central');
1.128     ng       1760:     hDoc.close();
1.44      ng       1761:   }
                   1762: 
                   1763: </script>
                   1764: SUBJAVASCRIPT
                   1765: }
                   1766: 
1.349     albertel 1767: sub get_increment {
1.348     bowersj2 1768:     my $increment = $env{'form.increment'};
                   1769:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1770:         $increment != .1) {
                   1771:         $increment = 1;
                   1772:     }
                   1773:     return $increment;
                   1774: }
                   1775: 
1.71      ng       1776: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1777: sub gradeBox {
1.322     albertel 1778:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1779:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1780: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1781:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1782:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1783:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1784:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1785:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1786: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1787:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1788:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1789:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1790: 				       [$partid]);
                   1791:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1792:     if ($last_resets{$partid}) {
                   1793:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1794:     }
1.485     albertel 1795:     $result.='<table border="0"><tr>';
1.71      ng       1796:     my $ctr = 0;
1.348     bowersj2 1797:     my $thisweight = 0;
1.349     albertel 1798:     my $increment = &get_increment();
1.485     albertel 1799: 
                   1800:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1801:     while ($thisweight<=$wgt) {
1.485     albertel 1802: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1803: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1804: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1805: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1806: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1807:         $thisweight += $increment;
1.71      ng       1808: 	$ctr++;
                   1809:     }
1.485     albertel 1810:     $radio.='</tr></table>';
                   1811: 
                   1812:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1813: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1814: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1815: 	$wgt.')" /></td>'."\n";
1.485     albertel 1816:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1817: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1818: 	' </td><td>'."\n";
1.485     albertel 1819:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1820: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1821:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1822: 	$line.='<option></option>'.
                   1823: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1824:     } else {
1.485     albertel 1825: 	$line.='<option selected="selected"></option>'.
                   1826: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1827:     }
1.485     albertel 1828:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1829: 
                   1830: 
                   1831:     $result .= 
                   1832: 	&mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line);
                   1833: 
                   1834:     
                   1835:     $result.='</tr></table>'."\n";
1.71      ng       1836:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1837: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1838: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1839: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1840:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1841:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1842:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1843:         $aggtries.'" />'."\n";
1.323     banghart 1844:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1845:     return $result;
                   1846: }
1.322     albertel 1847: 
                   1848: sub handback_box {
1.323     banghart 1849:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1850:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1851:     my (@respids);
1.375     albertel 1852:      my @part_response_id = &flatten_responseType($responseType);
                   1853:     foreach my $part_response_id (@part_response_id) {
                   1854:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1855:         if ($part eq $partid) {
1.375     albertel 1856:             push(@respids,$resp);
1.323     banghart 1857:         }
                   1858:     }
1.318     banghart 1859:     my $result;
1.323     banghart 1860:     foreach my $respid (@respids) {
1.322     albertel 1861: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1862: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1863: 	next if (!@$files);
                   1864: 	my $file_counter = 1;
1.313     banghart 1865: 	foreach my $file (@$files) {
1.368     banghart 1866: 	    if ($file =~ /\/portfolio\//) {
                   1867:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1868:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1869:     	        $file_disp = "$name.$ext";
                   1870:     	        $file = $file_path.$file_disp;
                   1871:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1872:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1873:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1874:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1875:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1876:     	        $file_counter++;
                   1877: 	    }
1.322     albertel 1878: 	}
1.313     banghart 1879:     }
1.318     banghart 1880:     return $result;    
1.71      ng       1881: }
1.44      ng       1882: 
1.58      albertel 1883: sub show_problem {
1.382     albertel 1884:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1885:     my $rendered;
1.382     albertel 1886:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1887:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1888:     if ($mode eq 'both' or $mode eq 'text') {
                   1889: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1890: 						       $env{'request.course.id'},
                   1891: 						       undef,\%form);
1.144     albertel 1892:     }
1.58      albertel 1893:     if ($removeform) {
                   1894: 	$rendered=~s|<form(.*?)>||g;
                   1895: 	$rendered=~s|</form>||g;
1.374     albertel 1896: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1897:     }
1.144     albertel 1898:     my $companswer;
                   1899:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1900: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1901: 	$companswer=
                   1902: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1903: 						    $env{'request.course.id'},
                   1904: 						    %form);
1.144     albertel 1905:     }
1.58      albertel 1906:     if ($removeform) {
                   1907: 	$companswer=~s|<form(.*?)>||g;
                   1908: 	$companswer=~s|</form>||g;
1.144     albertel 1909: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1910:     }
1.468     albertel 1911:     $rendered=
                   1912: 	'<div class="LC_grade_show_problem_header">'.
                   1913: 	&mt('View of the problem').
                   1914: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1915: 	$rendered.
                   1916: 	'</div>';
                   1917:     $companswer=
                   1918: 	'<div class="LC_grade_show_problem_header">'.
                   1919: 	&mt('Correct answer').
                   1920: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1921: 	$companswer.
                   1922: 	'</div>';
                   1923:     my $result;
1.144     albertel 1924:     if ($mode eq 'both') {
1.468     albertel 1925: 	$result=$rendered.$companswer;
1.144     albertel 1926:     } elsif ($mode eq 'text') {
1.468     albertel 1927: 	$result=$rendered;
1.144     albertel 1928:     } elsif ($mode eq 'answer') {
1.468     albertel 1929: 	$result=$companswer;
1.144     albertel 1930:     }
1.468     albertel 1931:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1932:     return $result;
1.58      albertel 1933: }
1.397     albertel 1934: 
1.396     banghart 1935: sub files_exist {
                   1936:     my ($r, $symb) = @_;
                   1937:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1938: 
1.396     banghart 1939:     foreach my $student (@students) {
                   1940:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1941:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1942: 					      $udom,$uname);
1.396     banghart 1943:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1944:         foreach my $submission (@$string) {
                   1945:             my ($partid,$respid) =
                   1946: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1947:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1948: 					   \%record);
                   1949:             return 1 if (@$files);
1.396     banghart 1950:         }
                   1951:     }
1.397     albertel 1952:     return 0;
1.396     banghart 1953: }
1.397     albertel 1954: 
1.394     banghart 1955: sub download_all_link {
                   1956:     my ($r,$symb) = @_;
1.395     albertel 1957:     my $all_students = 
                   1958: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1959: 
                   1960:     my $parts =
                   1961: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1962: 
1.394     banghart 1963:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1964:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1965:                              'cgi.'.$identifier.'.symb' => $symb,
                   1966:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1967:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1968: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1969:     return
                   1970: }
1.395     albertel 1971: 
1.432     banghart 1972: sub build_section_inputs {
                   1973:     my $section_inputs;
                   1974:     if ($env{'form.section'} eq '') {
                   1975:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1976:     } else {
                   1977:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1978:         foreach my $section (@sections) {
1.432     banghart 1979:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1980:         }
                   1981:     }
                   1982:     return $section_inputs;
                   1983: }
                   1984: 
1.44      ng       1985: # --------------------------- show submissions of a student, option to grade 
                   1986: sub submission {
                   1987:     my ($request,$counter,$total) = @_;
1.257     albertel 1988:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1989:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1990:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1991:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1992:     my $symb = &get_symb($request); 
                   1993:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1994: 
                   1995:     if (!&canview($usec)) {
1.398     albertel 1996: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1997: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1998: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1999: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 2000: 	return;
                   2001:     }
                   2002: 
1.257     albertel 2003:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   2004:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   2005:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   2006:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 2007:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   2008: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       2009: 	'/check.gif" height="16" border="0" />';
1.41      ng       2010: 
1.426     albertel 2011:     my %old_essays;
1.41      ng       2012:     # header info
                   2013:     if ($counter == 0) {
                   2014: 	&sub_page_js($request);
1.257     albertel 2015: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   2016: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   2017: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 2018: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 2019: 	    &download_all_link($request, $symb);
                   2020: 	}
1.485     albertel 2021: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   2022: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       2023: 
1.44      ng       2024: 	# option to display problem, only once else it cause problems 
                   2025:         # with the form later since the problem has a form.
1.257     albertel 2026: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 2027: 	    my $mode;
1.257     albertel 2028: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 2029: 		$mode='both';
1.257     albertel 2030: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 2031: 		$mode='text';
1.257     albertel 2032: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 2033: 		$mode='answer';
                   2034: 	    }
1.329     albertel 2035: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 2036: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       2037: 	}
1.441     www      2038: 
1.44      ng       2039: 	# kwclr is the only variable that is guaranteed to be non blank 
                   2040:         # if this subroutine has been called once.
1.41      ng       2041: 	my %keyhash = ();
1.257     albertel 2042: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       2043: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 2044: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   2045: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       2046: 
1.257     albertel 2047: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   2048: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   2049: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   2050: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   2051: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   2052: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   2053: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   2054: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       2055: 	}
1.257     albertel 2056: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 2057: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 2058: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       2059: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 2060: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 2061: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       2062: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 2063: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       2064: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       2065: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   2066: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 2067: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 2068: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   2069: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   2070: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   2071: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 2072: 			&build_section_inputs().
1.326     albertel 2073: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   2074: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       2075: 			'<input type="hidden" name="NCT"'.
1.257     albertel 2076: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   2077: 	if ($env{'form.handgrade'} eq 'yes') {
                   2078: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   2079: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   2080: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   2081: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   2082: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       2083: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 2084: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 2085: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   2086: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   2087: 	    }
1.123     ng       2088: 	}
1.41      ng       2089: 	
                   2090: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 2091: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       2092: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       2093: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 2094: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       2095: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       2096: 		'" />'."\n".
                   2097: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       2098: 	    $cts++;
                   2099: 	}
                   2100: 	$request->print($prnmsg);
1.32      ng       2101: 
1.257     albertel 2102: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      2103: #
                   2104: # Print out the keyword options line
                   2105: #
1.41      ng       2106: 	    $request->print(<<KEYWORDS);
1.38      ng       2107: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 2108: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       2109: <a href="#" onMouseDown="javascript:getSel(); return false"
                   2110:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 2111: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       2112: KEYWORDS
1.88      www      2113: #
                   2114: # Load the other essays for similarity check
                   2115: #
1.324     albertel 2116:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 2117: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2118: 	    $apath=&escape($apath);
1.88      www      2119: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2120: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2121:         }
                   2122:     }
1.44      ng       2123: 
1.441     www      2124: # This is where output for one specific student would start
1.468     albertel 2125:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2126:     $request->print("\n\n".
1.468     albertel 2127:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2128: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2129: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2130: 
1.257     albertel 2131:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2132: 	my $mode;
1.257     albertel 2133: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2134: 	    $mode='both';
1.257     albertel 2135: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2136: 	    $mode='text';
1.257     albertel 2137: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2138: 	    $mode='answer';
                   2139: 	}
1.329     albertel 2140: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2141: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2142:     }
1.144     albertel 2143: 
1.257     albertel 2144:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2145:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2146: 
1.44      ng       2147:     # Display student info
1.41      ng       2148:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2149:     my $result='<div class="LC_grade_submissions">';
                   2150:     
                   2151:     $result.='<div class="LC_grade_submissions_header">';
                   2152:     $result.= &mt('Submissions');
1.45      ng       2153:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2154: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2155:     if ($env{'form.handgrade'} eq 'no') {
                   2156: 	$result.='<span class="LC_grade_check_note">'.
                   2157: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2158: 
                   2159:     }
                   2160: 
                   2161: 
1.41      ng       2162: 
1.118     ng       2163:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2164:     my $fullname;
                   2165:     my $col_fullnames = [];
1.257     albertel 2166:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2167: 	(my $sub_result,$fullname,$col_fullnames)=
                   2168: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2169: 				 $counter);
                   2170: 	$result.=$sub_result;
1.41      ng       2171:     }
1.44      ng       2172:     $request->print($result."\n");
1.468     albertel 2173:     $request->print('</div>'."\n");
1.44      ng       2174:     # print student answer/submission
                   2175:     # Options are (1) Handgaded submission only
                   2176:     #             (2) Last submission, includes submission that is not handgraded 
                   2177:     #                  (for multi-response type part)
                   2178:     #             (3) Last submission plus the parts info
                   2179:     #             (4) The whole record for this student
1.257     albertel 2180:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2181: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2182: 	
                   2183: 	my $lastsubonly;
                   2184: 
1.151     albertel 2185: 	if ($$timestamp eq '') {
1.468     albertel 2186: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2187: 	} else {
1.468     albertel 2188: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2189: 
1.151     albertel 2190: 	    my %seenparts;
1.375     albertel 2191: 	    my @part_response_id = &flatten_responseType($responseType);
                   2192: 	    foreach my $part (@part_response_id) {
1.393     albertel 2193: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2194: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2195: 
1.375     albertel 2196: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2197: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2198: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2199: 		    if (exists($seenparts{$partid})) { next; }
                   2200: 		    $seenparts{$partid}=1;
1.207     albertel 2201: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2202: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2203: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2204: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2205: 			'\');" target="_self">'.
1.257     albertel 2206: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2207: 		    $request->print($submitby);
                   2208: 		    next;
                   2209: 		}
                   2210: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2211: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2212: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2213: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2214: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2215: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2216: 		    next;
                   2217: 		}
1.468     albertel 2218: 		foreach my $submission (@$string) {
                   2219: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2220: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2221: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2222: 		    # Similarity check
                   2223: 		    my $similar='';
1.257     albertel 2224: 		    if($env{'form.checkPlag'}){
1.151     albertel 2225: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2226: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2227: 			if ($osim) {
                   2228: 			    $osim=int($osim*100.0);
1.426     albertel 2229: 			    my %old_course_desc = 
                   2230: 				&Apache::lonnet::coursedescription($ocrsid,
                   2231: 								   {'one_time' => 1});
                   2232: 
                   2233: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2234: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2235: 				    $osim,
                   2236: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2237: 				    $oname,$odom,
1.426     albertel 2238: 				    $old_course_desc{'description'},
1.427     albertel 2239: 				    $old_course_desc{'num'},
1.426     albertel 2240: 				    $old_course_desc{'domain'}).
1.398     albertel 2241: 				'</span></h3><blockquote><i>'.
1.151     albertel 2242: 				&keywords_highlight($oessay).
                   2243: 				'</i></blockquote><hr />';
                   2244: 			}
1.150     albertel 2245: 		    }
1.151     albertel 2246: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2247: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2248: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2249: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2250: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2251: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2252: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2253: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2254: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2255: 			if (@$files) {
1.468     albertel 2256: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2257: 			    my $file_counter = 0;
1.313     banghart 2258: 			    foreach my $file (@$files) {
1.468     albertel 2259: 			        $file_counter++;
1.232     albertel 2260: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2261: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2262: 			    }
1.236     albertel 2263: 			    $lastsubonly.='<br />';
1.41      ng       2264: 			}
1.468     albertel 2265: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2266: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2267: 					 $respid,\%record,$order);
                   2268: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2269: 			$lastsubonly.='</div>';
1.41      ng       2270: 		    }
                   2271: 		}
                   2272: 	    }
1.468     albertel 2273: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2274: 	}
                   2275: 	$request->print($lastsubonly);
1.468     albertel 2276:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2277: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2278: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2279:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2280: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2281: 								 $env{'request.course.id'},
1.44      ng       2282: 								 $last,'.submission',
                   2283: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2284:     }
1.120     ng       2285: 
1.121     ng       2286:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2287: 	.$udom.'" />'."\n");
1.44      ng       2288:     # return if view submission with no grading option
1.257     albertel 2289:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2290: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2291: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2292: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2293: 	$toGrade.='</div>'."\n";
1.257     albertel 2294: 	if (($env{'form.command'} eq 'submission') || 
                   2295: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2296: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2297: 	}
1.180     albertel 2298: 	$request->print($toGrade);
1.41      ng       2299: 	return;
1.180     albertel 2300:     } else {
1.468     albertel 2301: 	$request->print('</div>'."\n");
1.41      ng       2302:     }
1.33      ng       2303: 
1.121     ng       2304:     # essay grading message center
1.257     albertel 2305:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2306: 	my $result='<div class="LC_grade_message_center">';
                   2307:     
                   2308: 	$result.='<div class="LC_grade_message_center_header">'.
                   2309: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2310: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2311: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2312: 	if (scalar(@$col_fullnames) > 0) {
                   2313: 	    my $lastone = pop(@$col_fullnames);
                   2314: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2315: 	}
                   2316: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2317: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2318: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2319: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2320: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2321: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2322: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2323: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2324: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2325: 	    '<br />&nbsp;('.
1.468     albertel 2326: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2327: 	$result.='</div></div>';
1.121     ng       2328: 	$request->print($result);
1.118     ng       2329:     }
1.41      ng       2330: 
                   2331:     my %seen = ();
                   2332:     my @partlist;
1.129     ng       2333:     my @gradePartRespid;
1.375     albertel 2334:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2335:     $request->print('<div class="LC_grade_assign">'.
                   2336: 		    
                   2337: 		    '<div class="LC_grade_assign_header">'.
                   2338: 		    &mt('Assign Grades').'</div>'.
                   2339: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2340:     foreach my $part_response_id (@part_response_id) {
                   2341:     	my ($partid,$respid) = @{ $part_response_id };
                   2342: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2343: 	next if ($seen{$partid} > 0);
1.41      ng       2344: 	$seen{$partid}++;
1.393     albertel 2345: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2346: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2347: 	push(@partlist,$partid);
                   2348: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2349: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2350:     }
1.468     albertel 2351:     $request->print('</div></div>');
                   2352: 
                   2353:     $request->print('<div class="LC_grade_info_links">');
                   2354:     if ($perm{'vgr'}) {
                   2355: 	$request->print(
                   2356: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2357: 						   $uname,$udom,'check'));
                   2358:     }
                   2359:     if ($perm{'opa'}) {
                   2360: 	$request->print(
                   2361: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2362: 					 $uname,$udom,$symb,'check'));
                   2363:     }
                   2364:     $request->print('</div>');
                   2365: 
1.45      ng       2366:     $result='<input type="hidden" name="partlist'.$counter.
                   2367: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2368:     $result.='<input type="hidden" name="gradePartRespid'.
                   2369: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2370:     my $ctr = 0;
                   2371:     while ($ctr < scalar(@partlist)) {
                   2372: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2373: 	    $partlist[$ctr].'" />'."\n";
                   2374: 	$ctr++;
                   2375:     }
1.468     albertel 2376:     $request->print($result.''."\n");
1.41      ng       2377: 
1.441     www      2378: # Done with printing info for one student
                   2379: 
1.468     albertel 2380:     $request->print('</div>');#LC_grade_show_user_body
                   2381:     $request->print('</div>');#LC_grade_show_user
1.441     www      2382: 
                   2383: 
1.41      ng       2384:     # print end of form
                   2385:     if ($counter == $total) {
1.297     www      2386: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2387: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2388: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2389: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2390: 	my $ntstu ='<select name="NTSTU">'.
                   2391: 	    '<option>1</option><option>2</option>'.
                   2392: 	    '<option>3</option><option>5</option>'.
                   2393: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2394: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2395: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2396: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2397: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2398: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2399: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2400: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2401: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2402:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2403:             "' name='increment' />";
1.485     albertel 2404: 	$endform.='</td></tr></table></form>';
1.324     albertel 2405: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2406: 	$request->print($endform);
                   2407:     }
                   2408:     return '';
1.38      ng       2409: }
                   2410: 
1.464     albertel 2411: sub check_collaborators {
                   2412:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2413:     my ($result,@col_fullnames);
                   2414:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2415:     foreach my $part (keys(%$handgrade)) {
                   2416: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2417: 					'.maxcollaborators',
                   2418: 					$symb,$udom,$uname);
                   2419: 	next if ($ncol <= 0);
                   2420: 	$part =~ s/\_/\./g;
                   2421: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2422: 	my (@good_collaborators, @bad_collaborators);
                   2423: 	foreach my $possible_collaborator
                   2424: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2425: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2426: 	    next if ($possible_collaborator eq '');
                   2427: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2428: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2429: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2430: 	    # Doing this grep allows 'fuzzy' specification
                   2431: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2432: 			       keys(%$classlist));
                   2433: 	    if (! scalar(@matches)) {
                   2434: 		push(@bad_collaborators, $possible_collaborator);
                   2435: 	    } else {
                   2436: 		push(@good_collaborators, @matches);
                   2437: 	    }
                   2438: 	}
                   2439: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2440: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2441: 	    foreach my $name (@good_collaborators) {
                   2442: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2443: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2444: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2445: 	    }
                   2446: 	    $result.='<br />'."\n";
1.466     albertel 2447: 	    my ($part)=split(/\./,$part);
1.464     albertel 2448: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2449: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2450: 		"\n";
                   2451: 	}
                   2452: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2453: 	    $result.='<div class="LC_warning">';
1.464     albertel 2454: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2455: 	    $result .= '</div>';
                   2456: 	}         
                   2457: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2458: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2459: 	    $result .= &mt('This student has submitted too many '.
                   2460: 		'collaborators.  Maximum is [_1].',$ncol);
                   2461: 	    $result .= '</div>';
                   2462: 	}
                   2463:     }
                   2464:     return ($result,$fullname,\@col_fullnames);
                   2465: }
                   2466: 
1.44      ng       2467: #--- Retrieve the last submission for all the parts
1.38      ng       2468: sub get_last_submission {
1.119     ng       2469:     my ($returnhash)=@_;
1.46      ng       2470:     my (@string,$timestamp);
1.119     ng       2471:     if ($$returnhash{'version'}) {
1.46      ng       2472: 	my %lasthash=();
                   2473: 	my ($version);
1.119     ng       2474: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2475: 	    foreach my $key (sort(split(/\:/,
                   2476: 					$$returnhash{$version.':keys'}))) {
                   2477: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2478: 		$timestamp = 
                   2479: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2480: 	    }
                   2481: 	}
1.397     albertel 2482: 	foreach my $key (keys(%lasthash)) {
                   2483: 	    next if ($key !~ /\.submission$/);
                   2484: 
                   2485: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2486: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2487: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2488: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2489: 	}
                   2490:     }
1.397     albertel 2491:     if (!@string) {
                   2492: 	$string[0] =
1.398     albertel 2493: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2494:     }
                   2495:     return (\@string,\$timestamp);
1.38      ng       2496: }
1.35      ng       2497: 
1.44      ng       2498: #--- High light keywords, with style choosen by user.
1.38      ng       2499: sub keywords_highlight {
1.44      ng       2500:     my $string    = shift;
1.257     albertel 2501:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2502:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2503:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2504:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2505:     foreach my $keyword (@keylist) {
                   2506: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2507:     }
                   2508:     return $string;
1.38      ng       2509: }
1.36      ng       2510: 
1.44      ng       2511: #--- Called from submission routine
1.38      ng       2512: sub processHandGrade {
1.41      ng       2513:     my ($request) = shift;
1.324     albertel 2514:     my $symb   = &get_symb($request);
                   2515:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2516:     my $button = $env{'form.gradeOpt'};
                   2517:     my $ngrade = $env{'form.NCT'};
                   2518:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2519:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2520:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2521: 
1.44      ng       2522:     if ($button eq 'Save & Next') {
                   2523: 	my $ctr = 0;
                   2524: 	while ($ctr < $ngrade) {
1.257     albertel 2525: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2526: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2527: 	    if ($errorflag eq 'no_score') {
                   2528: 		$ctr++;
                   2529: 		next;
                   2530: 	    }
1.104     albertel 2531: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2532: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2533: 		$ctr++;
                   2534: 		next;
                   2535: 	    }
1.257     albertel 2536: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2537: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2538: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2539:             my ($feedurl,$showsymb) =
                   2540: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2541: 	    my $messagetail;
1.62      albertel 2542: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2543: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2544: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2545: 		$subject.=' ['.$restitle.']';
1.44      ng       2546: 		my (@msgnum) = split(/,/,$includemsg);
                   2547: 		foreach (@msgnum) {
1.257     albertel 2548: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2549: 		}
1.80      ng       2550: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2551: 		if ($env{'form.withgrades'.$ctr}) {
                   2552: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2553: 		    $messagetail = " for <a href=\"".
1.418     albertel 2554: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2555: 		}
                   2556: 		$msgstatus = 
                   2557:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2558: 						     $message.$messagetail,
1.418     albertel 2559:                                                      undef,$feedurl,undef,
1.386     raeburn  2560:                                                      undef,undef,$showsymb,
                   2561:                                                      $restitle);
                   2562: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2563: 				$msgstatus);
1.44      ng       2564: 	    }
1.257     albertel 2565: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2566: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2567: 		foreach my $collabstr (@collabstrs) {
                   2568: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2569: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2570: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2571: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2572: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2573: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2574: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2575: 			    next;
1.418     albertel 2576: 			} elsif ($message ne '') {
                   2577: 			    my ($baseurl,$showsymb) = 
                   2578: 				&get_feedurl_and_symb($symb,$collaborator,
                   2579: 						      $udom);
                   2580: 			    if ($env{'form.withgrades'.$ctr}) {
                   2581: 				$messagetail = " for <a href=\"".
1.386     raeburn  2582:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2583: 			    }
1.418     albertel 2584: 			    $msgstatus = 
                   2585: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2586: 			}
1.44      ng       2587: 		    }
                   2588: 		}
                   2589: 	    }
                   2590: 	    $ctr++;
                   2591: 	}
                   2592:     }
                   2593: 
1.257     albertel 2594:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2595: 	# Keywords sorted in alphabatical order
1.257     albertel 2596: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2597: 	my %keyhash = ();
1.257     albertel 2598: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2599: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2600: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2601: 	$env{'form.keywords'} = join(' ',@keywords);
                   2602: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2603: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2604: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2605: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2606: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2607: 
                   2608: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2609: 	# New messages are saved in env for the next student.
1.119     ng       2610: 	# All messages are saved in nohist_handgrade.db
                   2611: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2612: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2613: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2614: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2615: 		$idx++;
                   2616: 	    }
                   2617: 	    $ctr++;
1.41      ng       2618: 	}
1.119     ng       2619: 	$ctr = 0;
                   2620: 	while ($ctr < $ngrade) {
1.257     albertel 2621: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2622: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2623: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2624: 		$idx++;
                   2625: 	    }
                   2626: 	    $ctr++;
1.41      ng       2627: 	}
1.257     albertel 2628: 	$env{'form.savemsgN'} = --$idx;
                   2629: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2630: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2631: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2632:     }
1.44      ng       2633:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2634:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2635:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2636: 	my ($ctr,$total) = (0,0);
                   2637: 	while ($ctr < $ngrade) {
1.257     albertel 2638: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2639: 	    $ctr++;
                   2640: 	}
1.257     albertel 2641: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2642: 	$ctr = 0;
                   2643: 	while ($ctr < $total) {
1.257     albertel 2644: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2645: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2646: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2647: 	    &submission($request,$ctr,$total-1);
1.41      ng       2648: 	    $ctr++;
                   2649: 	}
                   2650: 	return '';
                   2651:     }
1.36      ng       2652: 
1.121     ng       2653: # Go directly to grade student - from submission or link from chart page
1.120     ng       2654:     if ($button eq 'Grade Student') {
1.324     albertel 2655: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2656: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2657: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2658: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2659: 	&submission($request,0,0);
                   2660: 	return '';
                   2661:     }
                   2662: 
1.44      ng       2663:     # Get the next/previous one or group of students
1.257     albertel 2664:     my $firststu = $env{'form.unamedom0'};
                   2665:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2666:     my $ctr = 2;
1.41      ng       2667:     while ($laststu eq '') {
1.257     albertel 2668: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2669: 	$ctr++;
                   2670: 	$laststu = $firststu if ($ctr > $ngrade);
                   2671:     }
1.44      ng       2672: 
1.41      ng       2673:     my (@parsedlist,@nextlist);
                   2674:     my ($nextflg) = 0;
1.524     raeburn  2675:     foreach my $item (sort 
1.294     albertel 2676: 	     {
                   2677: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2678: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2679: 		 }
                   2680: 		 return $a cmp $b;
                   2681: 	     } (keys(%$fullname))) {
1.41      ng       2682: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2683: 	    push(@parsedlist,$item);
1.41      ng       2684: 	}
1.524     raeburn  2685: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2686: 	if ($button eq 'Previous') {
1.524     raeburn  2687: 	    last if ($item eq $firststu);
                   2688: 	    push(@parsedlist,$item);
1.41      ng       2689: 	}
                   2690:     }
                   2691:     $ctr = 0;
                   2692:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2693:     my ($partlist) = &response_type($symb);
1.41      ng       2694:     foreach my $student (@parsedlist) {
1.257     albertel 2695: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2696: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2697: 	
                   2698: 	if ($submitonly eq 'queued') {
                   2699: 	    my %queue_status = 
                   2700: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2701: 							$udom,$uname);
                   2702: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2703: 	}
                   2704: 
1.156     albertel 2705: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2706: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2707: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2708: 	    my $submitted = 0;
1.248     albertel 2709: 	    my $ungraded = 0;
                   2710: 	    my $incorrect = 0;
1.524     raeburn  2711: 	    foreach my $item (keys(%status)) {
                   2712: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2713: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2714: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2715: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2716: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2717: 		    $submitted = 0;
                   2718: 		}
1.41      ng       2719: 	    }
1.156     albertel 2720: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2721: 				     $submitonly eq 'incorrect' ||
                   2722: 				     $submitonly eq 'graded'));
1.248     albertel 2723: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2724: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2725: 	}
1.524     raeburn  2726: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2727: 	last if ($ctr == $ntstu);
1.41      ng       2728: 	$ctr++;
                   2729:     }
1.36      ng       2730: 
1.41      ng       2731:     $ctr = 0;
                   2732:     my $total = scalar(@nextlist)-1;
1.39      ng       2733: 
1.524     raeburn  2734:     foreach (sort(@nextlist)) {
1.41      ng       2735: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2736: 	$env{'form.student'}  = $uname;
                   2737: 	$env{'form.userdom'}  = $udom;
                   2738: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2739: 	&submission($request,$ctr,$total);
                   2740: 	$ctr++;
                   2741:     }
                   2742:     if ($total < 0) {
1.485     albertel 2743: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2744: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2745: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2746: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2747: 	$request->print($the_end);
                   2748:     }
                   2749:     return '';
1.38      ng       2750: }
1.36      ng       2751: 
1.44      ng       2752: #---- Save the score and award for each student, if changed
1.38      ng       2753: sub saveHandGrade {
1.324     albertel 2754:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2755:     my @version_parts;
1.104     albertel 2756:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2757: 					   $env{'request.course.id'});
1.104     albertel 2758:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2759:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2760:     my @parts_graded;
1.77      ng       2761:     my %newrecord  = ();
                   2762:     my ($pts,$wgt) = ('','');
1.269     raeburn  2763:     my %aggregate = ();
                   2764:     my $aggregateflag = 0;
1.301     albertel 2765:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2766:     foreach my $new_part (@parts) {
1.337     banghart 2767: 	#collaborator ($submi may vary for different parts
1.259     banghart 2768: 	if ($submitter && $new_part ne $part) { next; }
                   2769: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2770: 	if ($dropMenu eq 'excused') {
1.259     banghart 2771: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2772: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2773: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2774: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2775: 		}
1.364     banghart 2776: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2777: 	    }
1.125     ng       2778: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2779: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2780: 	    foreach my $key (keys(%record)) {
1.259     banghart 2781: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2782: 	    }
1.259     banghart 2783: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2784: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2785:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2786: 
                   2787:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2788: 					       [$new_part]);
                   2789:             my $aggtries =$totaltries;
1.269     raeburn  2790:             if ($last_resets{$new_part}) {
1.270     albertel 2791:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2792: 					   $new_part);
1.269     raeburn  2793:             }
1.270     albertel 2794: 
                   2795:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2796:             if ($aggtries > 0) {
1.327     albertel 2797:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2798:                 $aggregateflag = 1;
                   2799:             }
1.125     ng       2800: 	} elsif ($dropMenu eq '') {
1.259     banghart 2801: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2802: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2803: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2804: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2805: 		next;
                   2806: 	    }
1.259     banghart 2807: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2808: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2809: 	    my $partial= $pts/$wgt;
1.259     banghart 2810: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2811: 		#do not update score for part if not changed.
1.346     banghart 2812:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2813: 		next;
1.251     banghart 2814: 	    } else {
1.524     raeburn  2815: 	        push(@parts_graded,$new_part);
1.153     albertel 2816: 	    }
1.259     banghart 2817: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2818: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2819: 	    }
1.259     banghart 2820: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2821: 	    if ($partial == 0) {
1.153     albertel 2822: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2823: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2824: 		}
1.41      ng       2825: 	    } else {
1.153     albertel 2826: 		if ($record{$reckey} ne 'correct_by_override') {
                   2827: 		    $newrecord{$reckey} = 'correct_by_override';
                   2828: 		}
                   2829: 	    }	    
                   2830: 	    if ($submitter && 
1.259     banghart 2831: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2832: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2833: 	    }
1.259     banghart 2834: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2835: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2836: 	}
1.259     banghart 2837: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2838: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2839: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2840: 	        $dropMenu eq 'reset status')
                   2841: 	   {
1.524     raeburn  2842: 	    push(@version_parts,$new_part);
1.259     banghart 2843: 	}
1.41      ng       2844:     }
1.301     albertel 2845:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2846:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2847: 
1.344     albertel 2848:     if (%newrecord) {
                   2849:         if (@version_parts) {
1.364     banghart 2850:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2851:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2852: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2853: 	    foreach my $new_part (@version_parts) {
                   2854: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2855: 				$new_part,\%newrecord);
                   2856: 	    }
1.259     banghart 2857:         }
1.44      ng       2858: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2859: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2860: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2861: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2862:     }
1.269     raeburn  2863:     if ($aggregateflag) {
                   2864:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2865: 			      $cdom,$cnum);
1.269     raeburn  2866:     }
1.301     albertel 2867:     return ('',$pts,$wgt);
1.36      ng       2868: }
1.322     albertel 2869: 
1.380     albertel 2870: sub check_and_remove_from_queue {
                   2871:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2872:     my @ungraded_parts;
                   2873:     foreach my $part (@{$parts}) {
                   2874: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2875: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2876: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2877: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2878: 		) {
                   2879: 	    push(@ungraded_parts, $part);
                   2880: 	}
                   2881:     }
                   2882:     if ( !@ungraded_parts ) {
                   2883: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2884: 					       $cnum,$domain,$stuname);
                   2885:     }
                   2886: }
                   2887: 
1.337     banghart 2888: sub handback_files {
                   2889:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2890:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2891:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2892: 
                   2893:     my @part_response_id = &flatten_responseType($responseType);
                   2894:     foreach my $part_response_id (@part_response_id) {
                   2895:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2896: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2897:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2898:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2899:                 my $file_counter = 1;
1.367     albertel 2900: 		my $file_msg;
1.337     banghart 2901:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2902:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2903:                     my ($directory,$answer_file) = 
                   2904:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2905:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2906: 		        &file_name_version_ext($answer_file);
1.355     banghart 2907: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2908:                     my $getpropath = 1;
                   2909: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2910: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2911:                     # fix file name
                   2912:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2913:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2914:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2915:             	                                $save_file_name);
1.337     banghart 2916:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2917:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2918:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2919:                     } else {
1.360     banghart 2920:                         # mark the file as read only
                   2921:                         my @files = ($save_file_name);
1.372     albertel 2922:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2923:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2924: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2925: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2926: 			}
                   2927:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2928: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2929: 
1.337     banghart 2930:                     }
                   2931:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2932:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2933:                     $file_counter++;
                   2934:                 }
1.367     albertel 2935: 		my $subject = "File Handed Back by Instructor ";
                   2936: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2937: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2938: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2939: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2940: 		my ($feedurl,$showsymb) = 
                   2941: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2942:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2943: 		my $msgstatus = 
                   2944:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2945: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2946:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2947:             }
                   2948:         }
1.338     banghart 2949:     return;
1.337     banghart 2950: }
                   2951: 
1.418     albertel 2952: sub get_feedurl_and_symb {
                   2953:     my ($symb,$uname,$udom) = @_;
                   2954:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2955:     $url = &Apache::lonnet::clutter($url);
                   2956:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2957: 					$symb,$udom,$uname);
                   2958:     if ($encrypturl =~ /^yes$/i) {
                   2959: 	&Apache::lonenc::encrypted(\$url,1);
                   2960: 	&Apache::lonenc::encrypted(\$symb,1);
                   2961:     }
                   2962:     return ($url,$symb);
                   2963: }
                   2964: 
1.313     banghart 2965: sub get_submitted_files {
                   2966:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2967:     my @files;
                   2968:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2969:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2970:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2971:     	    push(@files,$file_url.$file);
                   2972:         }
                   2973:     }
                   2974:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2975:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2976:     }
                   2977:     return (\@files);
                   2978: }
1.322     albertel 2979: 
1.269     raeburn  2980: # ----------- Provides number of tries since last reset.
                   2981: sub get_num_tries {
                   2982:     my ($record,$last_reset,$part) = @_;
                   2983:     my $timestamp = '';
                   2984:     my $num_tries = 0;
                   2985:     if ($$record{'version'}) {
                   2986:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2987:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2988:                 $timestamp = $$record{$version.':timestamp'};
                   2989:                 if ($timestamp > $last_reset) {
                   2990:                     $num_tries ++;
                   2991:                 } else {
                   2992:                     last;
                   2993:                 }
                   2994:             }
                   2995:         }
                   2996:     }
                   2997:     return $num_tries;
                   2998: }
                   2999: 
                   3000: # ----------- Determine decrements required in aggregate totals 
                   3001: sub decrement_aggs {
                   3002:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   3003:     my %decrement = (
                   3004:                         attempts => 0,
                   3005:                         users => 0,
                   3006:                         correct => 0
                   3007:                     );
                   3008:     $decrement{'attempts'} = $aggtries;
                   3009:     if ($solvedstatus =~ /^correct/) {
                   3010:         $decrement{'correct'} = 1;
                   3011:     }
                   3012:     if ($aggtries == $totaltries) {
                   3013:         $decrement{'users'} = 1;
                   3014:     }
1.524     raeburn  3015:     foreach my $type (keys(%decrement)) {
1.269     raeburn  3016:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   3017:     }
                   3018:     return;
                   3019: }
                   3020: 
                   3021: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   3022: sub get_last_resets {
1.270     albertel 3023:     my ($symb,$courseid,$partids) =@_;
                   3024:     my %last_resets;
1.269     raeburn  3025:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   3026:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 3027:     my @keys;
                   3028:     foreach my $part (@{$partids}) {
                   3029: 	push(@keys,"$symb\0$part\0resettime");
                   3030:     }
                   3031:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   3032: 				     $cdom,$cname);
                   3033:     foreach my $part (@{$partids}) {
                   3034: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  3035:     }
1.270     albertel 3036:     return %last_resets;
1.269     raeburn  3037: }
                   3038: 
1.251     banghart 3039: # ----------- Handles creating versions for portfolio files as answers
                   3040: sub version_portfiles {
1.343     banghart 3041:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 3042:     my $version_parts = join('|',@$v_flag);
1.343     banghart 3043:     my @returned_keys;
1.255     banghart 3044:     my $parts = join('|', @$parts_graded);
1.517     raeburn  3045:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 3046:     foreach my $key (keys(%$record)) {
1.259     banghart 3047:         my $new_portfiles;
1.263     banghart 3048:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 3049:             my @versioned_portfiles;
1.367     albertel 3050:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 3051:             foreach my $file (@portfiles) {
1.306     banghart 3052:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 3053:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   3054: 		my ($answer_name,$answer_ver,$answer_ext) =
                   3055: 		    &file_name_version_ext($answer_file);
1.517     raeburn  3056:                 my $getpropath = 1;    
                   3057:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 3058:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 3059:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   3060:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 3061:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 3062:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 3063:                         [$directory.$new_answer],
1.306     banghart 3064:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 3065:                 }
1.252     banghart 3066:             }
1.343     banghart 3067:             $$record{$key} = join(',',@versioned_portfiles);
                   3068:             push(@returned_keys,$key);
1.251     banghart 3069:         }
                   3070:     } 
1.343     banghart 3071:     return (@returned_keys);   
1.305     banghart 3072: }
                   3073: 
1.307     banghart 3074: sub get_next_version {
1.341     banghart 3075:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 3076:     my $version;
                   3077:     foreach my $row (@$dir_list) {
                   3078:         my ($file) = split(/\&/,$row,2);
                   3079:         my ($file_name,$file_version,$file_ext) =
                   3080: 	    &file_name_version_ext($file);
                   3081:         if (($file_name eq $answer_name) && 
                   3082: 	    ($file_ext eq $answer_ext)) {
                   3083:                 # gets here if filename and extension match, regardless of version
                   3084:                 if ($file_version ne '') {
                   3085:                 # a versioned file is found  so save it for later
                   3086:                 if ($file_version > $version) {
                   3087: 		    $version = $file_version;
                   3088: 	        }
                   3089:             }
                   3090:         }
                   3091:     } 
                   3092:     $version ++;
                   3093:     return($version);
                   3094: }
                   3095: 
1.305     banghart 3096: sub version_selected_portfile {
1.306     banghart 3097:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   3098:     my ($answer_name,$answer_ver,$answer_ext) =
                   3099:         &file_name_version_ext($file_name);
                   3100:     my $new_answer;
                   3101:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   3102:     if($env{'form.copy'} eq '-1') {
                   3103:         $new_answer = 'problem getting file';
                   3104:     } else {
                   3105:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   3106:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   3107:                             $stu_name,$domain,'copy',
                   3108: 		        '/portfolio'.$directory.$new_answer);
                   3109:     }    
                   3110:     return ($new_answer);
1.251     banghart 3111: }
                   3112: 
1.304     albertel 3113: sub file_name_version_ext {
                   3114:     my ($file)=@_;
                   3115:     my @file_parts = split(/\./, $file);
                   3116:     my ($name,$version,$ext);
                   3117:     if (@file_parts > 1) {
                   3118: 	$ext=pop(@file_parts);
                   3119: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3120: 	    $version=pop(@file_parts);
                   3121: 	}
                   3122: 	$name=join('.',@file_parts);
                   3123:     } else {
                   3124: 	$name=join('.',@file_parts);
                   3125:     }
                   3126:     return($name,$version,$ext);
                   3127: }
                   3128: 
1.44      ng       3129: #--------------------------------------------------------------------------------------
                   3130: #
                   3131: #-------------------------- Next few routines handles grading by section or whole class
                   3132: #
                   3133: #--- Javascript to handle grading by section or whole class
1.42      ng       3134: sub viewgrades_js {
                   3135:     my ($request) = shift;
                   3136: 
1.41      ng       3137:     $request->print(<<VIEWJAVASCRIPT);
                   3138: <script type="text/javascript" language="javascript">
1.45      ng       3139:    function writePoint(partid,weight,point) {
1.125     ng       3140: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3141: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3142: 	if (point == "textval") {
1.125     ng       3143: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3144: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3145: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3146: 		var resetbox = false;
                   3147: 		for (var i=0; i<radioButton.length; i++) {
                   3148: 		    if (radioButton[i].checked) {
                   3149: 			textbox.value = i;
                   3150: 			resetbox = true;
                   3151: 		    }
                   3152: 		}
                   3153: 		if (!resetbox) {
                   3154: 		    textbox.value = "";
                   3155: 		}
                   3156: 		return;
                   3157: 	    }
1.109     matthew  3158: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3159: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3160: 				   ") greater than the weight for the part. Accept?");
                   3161: 		if (resp == false) {
                   3162: 		    textbox.value = "";
                   3163: 		    return;
                   3164: 		}
                   3165: 	    }
1.42      ng       3166: 	    for (var i=0; i<radioButton.length; i++) {
                   3167: 		radioButton[i].checked=false;
1.109     matthew  3168: 		if (parseFloat(point) == i) {
1.42      ng       3169: 		    radioButton[i].checked=true;
                   3170: 		}
                   3171: 	    }
1.41      ng       3172: 
1.42      ng       3173: 	} else {
1.125     ng       3174: 	    textbox.value = parseFloat(point);
1.42      ng       3175: 	}
1.41      ng       3176: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3177: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3178: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3179: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3180: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3181: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3182: 	    if (saveval != "correct") {
                   3183: 		scorename.value = point;
1.43      ng       3184: 		if (selname[0].selected != true) {
                   3185: 		    selname[0].selected = true;
                   3186: 		}
1.42      ng       3187: 	    }
                   3188: 	}
1.125     ng       3189: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3190:     }
                   3191: 
                   3192:     function writeRadText(partid,weight) {
1.125     ng       3193: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3194: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3195:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3196: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3197: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3198: 	    for (var i=0; i<radioButton.length; i++) {
                   3199: 		radioButton[i].checked=false;
                   3200: 
                   3201: 	    }
                   3202: 	    textbox.value = "";
                   3203: 
                   3204: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3205: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3206: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3207: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3208: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3209: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3210: 		if ((saveval != "correct") || override) {
1.42      ng       3211: 		    scorename.value = "";
1.125     ng       3212: 		    if (selval[1].selected) {
                   3213: 			selname[1].selected = true;
                   3214: 		    } else {
                   3215: 			selname[2].selected = true;
                   3216: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3217: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3218: 		    }
1.42      ng       3219: 		}
                   3220: 	    }
1.43      ng       3221: 	} else {
                   3222: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3223: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3224: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3225: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3226: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3227: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3228: 		if ((saveval != "correct") || override) {
1.125     ng       3229: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3230: 		    selname[0].selected = true;
                   3231: 		}
                   3232: 	    }
                   3233: 	}	    
1.42      ng       3234:     }
                   3235: 
                   3236:     function changeSelect(partid,user) {
1.125     ng       3237: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3238: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3239: 	var point  = textbox.value;
1.125     ng       3240: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3241: 
1.109     matthew  3242: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3243: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3244: 	    textbox.value = "";
                   3245: 	    return;
                   3246: 	}
1.109     matthew  3247: 	if (parseFloat(point) > parseFloat(weight)) {
                   3248: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3249: 			       ") greater than the weight of the part. Accept?");
                   3250: 	    if (resp == false) {
                   3251: 		textbox.value = "";
                   3252: 		return;
                   3253: 	    }
                   3254: 	}
1.42      ng       3255: 	selval[0].selected = true;
                   3256:     }
                   3257: 
                   3258:     function changeOneScore(partid,user) {
1.125     ng       3259: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3260: 	if (selval[1].selected || selval[2].selected) {
                   3261: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3262: 	    if (selval[2].selected) {
                   3263: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3264: 	    }
1.269     raeburn  3265:         }
1.42      ng       3266:     }
                   3267: 
                   3268:     function resetEntry(numpart) {
                   3269: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3270: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3271: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3272: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3273: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3274: 	    for (var i=0; i<radioButton.length; i++) {
                   3275: 		radioButton[i].checked=false;
                   3276: 
                   3277: 	    }
                   3278: 	    textbox.value = "";
                   3279: 	    selval[0].selected = true;
                   3280: 
                   3281: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3282: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3283: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3284: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3285: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3286: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3287: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3288: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3289: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3290: 		if (saveselval == "excused") {
1.43      ng       3291: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3292: 		} else {
1.43      ng       3293: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3294: 		}
                   3295: 	    }
1.41      ng       3296: 	}
1.42      ng       3297:     }
                   3298: 
1.41      ng       3299: </script>
                   3300: VIEWJAVASCRIPT
1.42      ng       3301: }
                   3302: 
1.44      ng       3303: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3304: sub viewgrades {
                   3305:     my ($request) = shift;
                   3306:     &viewgrades_js($request);
1.41      ng       3307: 
1.324     albertel 3308:     my ($symb) = &get_symb($request);
1.168     albertel 3309:     #need to make sure we have the correct data for later EXT calls, 
                   3310:     #thus invalidate the cache
                   3311:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3312:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3313:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3314:     &Apache::lonnet::clear_EXT_cache_status();
                   3315: 
1.398     albertel 3316:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3317:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3318: 
                   3319:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3320:     $result.=&jscriptNform($symb);
1.41      ng       3321: 
1.44      ng       3322:     #beginning of class grading form
1.442     banghart 3323:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3324:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3325: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3326: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3327: 	&build_section_inputs().
1.257     albertel 3328: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3329: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3330: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3331: 
1.126     ng       3332:     my $sectionClass;
1.430     banghart 3333:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3334:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3335: 	$sectionClass='Class';
1.257     albertel 3336:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3337: 	$sectionClass='Students in no Section';
1.52      albertel 3338:     } else {
1.485     albertel 3339: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3340:     }
1.485     albertel 3341:     $result.=
                   3342: 	'<h3>'.
                   3343: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3344:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3345:     #radio buttons/text box for assigning points for a section or class.
                   3346:     #handles different parts of a problem
1.375     albertel 3347:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3348:     my %weight = ();
                   3349:     my $ctsparts = 0;
1.45      ng       3350:     my %seen = ();
1.375     albertel 3351:     my @part_response_id = &flatten_responseType($responseType);
                   3352:     foreach my $part_response_id (@part_response_id) {
                   3353:     	my ($partid,$respid) = @{ $part_response_id };
                   3354: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3355: 	next if $seen{$partid};
                   3356: 	$seen{$partid}++;
1.375     albertel 3357: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3358: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3359: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3360: 
1.324     albertel 3361: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3362: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3363: 	my $ctr = 0;
1.42      ng       3364: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3365: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3366: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3367: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3368: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3369: 	    $ctr++;
                   3370: 	}
1.485     albertel 3371: 	$radio.='</tr></table>';
                   3372: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3373: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3374: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3375: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3376: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3377: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3378: 		$weight{$partid}.')"> '.
1.401     albertel 3379: 	    '<option selected="selected"> </option>'.
1.485     albertel 3380: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3381: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3382: 	    '</select></td>'.
                   3383:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3384: 	$line.='<input type="hidden" name="partid_'.
                   3385: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3386: 	$line.='<input type="hidden" name="weight_'.
                   3387: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3388: 
                   3389: 	$result.=
                   3390: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3391: 	    &mt('<td><b>Part:</b></td><td>[_1]</td><td><b>Points:</b></td><td>[_2]</td><td>or</td><td>[_3]</td>',$display_part,$radio,$line).
                   3392: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3393: 	$ctsparts++;
1.41      ng       3394:     }
1.474     albertel 3395:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3396: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3397:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3398: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3399: 
1.44      ng       3400:     #table listing all the students in a section/class
                   3401:     #header of table
1.485     albertel 3402:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3403: 			 $section_display).'</h3>';
1.474     albertel 3404:     $result.= &Apache::loncommon::start_data_table().
                   3405: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3406: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3407: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3408:     my (@parts) = sort(&getpartlist($symb));
                   3409:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3410:     my @partids = ();
1.41      ng       3411:     foreach my $part (@parts) {
                   3412: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3413: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3414: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3415: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3416:         push(@partids,$partid);
1.324     albertel 3417: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3418: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3419: 	    $result.='<th>'.
                   3420: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3421: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3422: 	    next;
1.485     albertel 3423: 	    
1.207     albertel 3424: 	} else {
1.485     albertel 3425: 	    if ($display =~ /Problem Status/) {
                   3426: 		my $grade_status_mt = &mt('Grade Status');
                   3427: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3428: 	    }
                   3429: 	    my $part_mt = &mt('Part:');
                   3430: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3431: 	}
1.485     albertel 3432: 
1.474     albertel 3433: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3434:     }
1.474     albertel 3435:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3436: 
1.270     albertel 3437:     my %last_resets = 
                   3438: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3439: 
1.41      ng       3440:     #get info for each student
1.44      ng       3441:     #list all the students - with points and grade status
1.257     albertel 3442:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3443:     my $ctr = 0;
1.294     albertel 3444:     foreach (sort 
                   3445: 	     {
                   3446: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3447: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3448: 		 }
                   3449: 		 return $a cmp $b;
                   3450: 	     } (keys(%$fullname))) {
1.126     ng       3451: 	$ctr++;
1.324     albertel 3452: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3453: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3454:     }
1.474     albertel 3455:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3456:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3457:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3458: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3459:     if (scalar(%$fullname) eq 0) {
                   3460: 	my $colspan=3+scalar(@parts);
1.433     banghart 3461: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3462:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3463: 	$result='<span class="LC_warning">'.
1.485     albertel 3464: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3465: 	        $section_display, $stu_status).
1.433     banghart 3466: 	    '</span>';
1.96      albertel 3467:     }
1.324     albertel 3468:     $result.=&show_grading_menu_form($symb);
1.41      ng       3469:     return $result;
                   3470: }
                   3471: 
1.44      ng       3472: #--- call by previous routine to display each student
1.41      ng       3473: sub viewstudentgrade {
1.324     albertel 3474:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3475:     my ($uname,$udom) = split(/:/,$student);
                   3476:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3477:     my %aggregates = (); 
1.474     albertel 3478:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3479: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3480: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3481: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3482: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3483: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3484:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3485:     foreach my $apart (@$parts) {
                   3486: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3487: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3488:         $result.='<td align="center">';
1.269     raeburn  3489:         my ($aggtries,$totaltries);
                   3490:         unless (exists($aggregates{$part})) {
1.270     albertel 3491: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3492: 
                   3493: 	    $aggtries = $totaltries;
1.269     raeburn  3494:             if ($$last_resets{$part}) {  
1.270     albertel 3495:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3496: 					   $part);
                   3497:             }
1.269     raeburn  3498:             $result.='<input type="hidden" name="'.
                   3499:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3500:             $result.='<input type="hidden" name="'.
                   3501:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3502:             $aggregates{$part} = 1;
                   3503:         }
1.41      ng       3504: 	if ($type eq 'awarded') {
1.320     albertel 3505: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3506: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3507: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3508: 	    $result.='<input type="text" name="'.
1.89      albertel 3509: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3510: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3511: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3512: 	} elsif ($type eq 'solved') {
                   3513: 	    my ($status,$foo)=split(/_/,$score,2);
                   3514: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3515: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3516: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3517: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3518: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3519: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3520: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3521: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3522: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3523: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3524: 	} else {
                   3525: 	    $result.='<input type="hidden" name="'.
                   3526: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3527: 		    "\n";
1.233     albertel 3528: 	    $result.='<input type="text" name="'.
1.122     ng       3529: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3530: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3531: 	}
                   3532:     }
1.474     albertel 3533:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3534:     return $result;
1.38      ng       3535: }
                   3536: 
1.44      ng       3537: #--- change scores for all the students in a section/class
                   3538: #    record does not get update if unchanged
1.38      ng       3539: sub editgrades {
1.41      ng       3540:     my ($request) = @_;
                   3541: 
1.324     albertel 3542:     my $symb=&get_symb($request);
1.433     banghart 3543:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3544:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3545:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3546:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3547: 
1.477     albertel 3548:     my $result= &Apache::loncommon::start_data_table().
                   3549: 	&Apache::loncommon::start_data_table_header_row().
                   3550: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3551: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3552:     my %scoreptr = (
                   3553: 		    'correct'  =>'correct_by_override',
                   3554: 		    'incorrect'=>'incorrect_by_override',
                   3555: 		    'excused'  =>'excused',
                   3556: 		    'ungraded' =>'ungraded_attempted',
                   3557: 		    'nothing'  => '',
                   3558: 		    );
1.257     albertel 3559:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3560: 
1.44      ng       3561:     my (@partid);
                   3562:     my %weight = ();
1.54      albertel 3563:     my %columns = ();
1.44      ng       3564:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3565: 
1.324     albertel 3566:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3567:     my $header;
1.257     albertel 3568:     while ($ctr < $env{'form.totalparts'}) {
                   3569: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3570: 	push(@partid,$partid);
1.257     albertel 3571: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3572: 	$ctr++;
1.54      albertel 3573:     }
1.324     albertel 3574:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3575:     foreach my $partid (@partid) {
1.478     albertel 3576: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3577: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3578: 	$columns{$partid}=2;
                   3579: 	foreach my $stores (@parts) {
                   3580: 	    my ($part,$type) = &split_part_type($stores);
                   3581: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3582: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3583: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3584: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3585: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3586: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3587: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3588: 	    $columns{$partid}+=2;
                   3589: 	}
                   3590:     }
                   3591:     foreach my $partid (@partid) {
1.324     albertel 3592: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3593: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3594: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3595: 	    '</th>';
1.54      albertel 3596: 
1.44      ng       3597:     }
1.477     albertel 3598:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3599: 	&Apache::loncommon::start_data_table_header_row().
                   3600: 	$header.
                   3601: 	&Apache::loncommon::end_data_table_header_row();
                   3602:     my @noupdate;
1.126     ng       3603:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3604:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3605: 	my $line;
1.257     albertel 3606: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3607: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3608: 	my %newrecord;
                   3609: 	my $updateflag = 0;
1.281     albertel 3610: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3611: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3612: 	if (!&canmodify($usec)) {
1.126     ng       3613: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3614: 	    push(@noupdate,
1.478     albertel 3615: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3616: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3617: 	    next;
                   3618: 	}
1.269     raeburn  3619:         my %aggregate = ();
                   3620:         my $aggregateflag = 0;
1.281     albertel 3621: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3622: 	foreach (@partid) {
1.257     albertel 3623: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3624: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3625: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3626: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3627: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3628: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3629: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3630: 	    my $score;
                   3631: 	    if ($partial eq '') {
1.257     albertel 3632: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3633: 	    } elsif ($partial > 0) {
                   3634: 		$score = 'correct_by_override';
                   3635: 	    } elsif ($partial == 0) {
                   3636: 		$score = 'incorrect_by_override';
                   3637: 	    }
1.257     albertel 3638: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3639: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3640: 
1.292     albertel 3641: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3642: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3643: 	    if ($dropMenu eq 'reset status' &&
                   3644: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3645: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3646: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3647: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3648: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3649: 		$updateflag = 1;
1.269     raeburn  3650:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3651:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3652:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3653:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3654:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3655:                     $aggregateflag = 1;
                   3656:                 }
1.139     albertel 3657: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3658: 		$updateflag = 1;
                   3659: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3660: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3661: 		$rec_update++;
1.125     ng       3662: 	    }
                   3663: 
1.93      albertel 3664: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3665: 		'<td align="center">'.$awarded.
                   3666: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3667: 
1.54      albertel 3668: 
                   3669: 	    my $partid=$_;
                   3670: 	    foreach my $stores (@parts) {
                   3671: 		my ($part,$type) = &split_part_type($stores);
                   3672: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3673: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3674: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3675: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3676: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3677: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3678: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3679: 		    $updateflag=1;
                   3680: 		}
1.93      albertel 3681: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3682: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3683: 	    }
1.44      ng       3684: 	}
1.477     albertel 3685: 	$line.="\n";
1.301     albertel 3686: 
                   3687: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3688: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3689: 
1.44      ng       3690: 	if ($updateflag) {
                   3691: 	    $count++;
1.257     albertel 3692: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3693: 				    $udom,$uname);
1.301     albertel 3694: 
                   3695: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3696: 					      $cnum,$udom,$uname)) {
                   3697: 		# need to figure out if should be in queue.
                   3698: 		my %record =  
                   3699: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3700: 					     $udom,$uname);
                   3701: 		my $all_graded = 1;
                   3702: 		my $none_graded = 1;
                   3703: 		foreach my $part (@parts) {
                   3704: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3705: 			$all_graded = 0;
                   3706: 		    } else {
                   3707: 			$none_graded = 0;
                   3708: 		    }
                   3709: 		}
                   3710: 
                   3711: 		if ($all_graded || $none_graded) {
                   3712: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3713: 							   $symb,$cdom,$cnum,
                   3714: 							   $udom,$uname);
                   3715: 		}
                   3716: 	    }
                   3717: 
1.477     albertel 3718: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3719: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3720: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3721: 	    $updateCtr++;
1.93      albertel 3722: 	} else {
1.477     albertel 3723: 	    push(@noupdate,
                   3724: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3725: 	    $noupdateCtr++;
1.44      ng       3726: 	}
1.269     raeburn  3727:         if ($aggregateflag) {
                   3728:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3729: 				  $cdom,$cnum);
1.269     raeburn  3730:         }
1.93      albertel 3731:     }
1.477     albertel 3732:     if (@noupdate) {
1.126     ng       3733: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3734: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3735: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3736: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3737: 	    &mt('No Changes Occurred For the Students Below').
                   3738: 	    '</td>'.
1.477     albertel 3739: 	    &Apache::loncommon::end_data_table_row();
                   3740: 	foreach my $line (@noupdate) {
                   3741: 	    $result.=
                   3742: 		&Apache::loncommon::start_data_table_row().
                   3743: 		$line.
                   3744: 		&Apache::loncommon::end_data_table_row();
                   3745: 	}
1.44      ng       3746:     }
1.477     albertel 3747:     $result .= &Apache::loncommon::end_data_table().
                   3748: 	&show_grading_menu_form($symb);
1.478     albertel 3749:     my $msg = '<p><b>'.
                   3750: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3751: 	    $rec_update,$count).'</b><br />'.
                   3752: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3753: 	'</b></p>';
1.44      ng       3754:     return $title.$msg.$result;
1.5       albertel 3755: }
1.54      albertel 3756: 
                   3757: sub split_part_type {
                   3758:     my ($partstr) = @_;
                   3759:     my ($temp,@allparts)=split(/_/,$partstr);
                   3760:     my $type=pop(@allparts);
1.439     albertel 3761:     my $part=join('_',@allparts);
1.54      albertel 3762:     return ($part,$type);
                   3763: }
                   3764: 
1.44      ng       3765: #------------- end of section for handling grading by section/class ---------
                   3766: #
                   3767: #----------------------------------------------------------------------------
                   3768: 
1.5       albertel 3769: 
1.44      ng       3770: #----------------------------------------------------------------------------
                   3771: #
                   3772: #-------------------------- Next few routines handles grading by csv upload
                   3773: #
                   3774: #--- Javascript to handle csv upload
1.27      albertel 3775: sub csvupload_javascript_reverse_associate {
1.246     albertel 3776:     my $error1=&mt('You need to specify the username or ID');
                   3777:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3778:   return(<<ENDPICK);
                   3779:   function verify(vf) {
                   3780:     var foundsomething=0;
                   3781:     var founduname=0;
1.243     albertel 3782:     var foundID=0;
1.27      albertel 3783:     for (i=0;i<=vf.nfields.value;i++) {
                   3784:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3785:       if (i==0 && tw!=0) { foundID=1; }
                   3786:       if (i==1 && tw!=0) { founduname=1; }
                   3787:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3788:     }
1.246     albertel 3789:     if (founduname==0 && foundID==0) {
                   3790: 	alert('$error1');
                   3791: 	return;
1.27      albertel 3792:     }
                   3793:     if (foundsomething==0) {
1.246     albertel 3794: 	alert('$error2');
                   3795: 	return;
1.27      albertel 3796:     }
                   3797:     vf.submit();
                   3798:   }
                   3799:   function flip(vf,tf) {
                   3800:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3801:     var i;
                   3802:     for (i=0;i<=vf.nfields.value;i++) {
                   3803:       //can not pick the same destination field for both name and domain
                   3804:       if (((i ==0)||(i ==1)) && 
                   3805:           ((tf==0)||(tf==1)) && 
                   3806:           (i!=tf) &&
                   3807:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3808:         eval('vf.f'+i+'.selectedIndex=0;')
                   3809:       }
                   3810:     }
                   3811:   }
                   3812: ENDPICK
                   3813: }
                   3814: 
                   3815: sub csvupload_javascript_forward_associate {
1.246     albertel 3816:     my $error1=&mt('You need to specify the username or ID');
                   3817:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3818:   return(<<ENDPICK);
                   3819:   function verify(vf) {
                   3820:     var foundsomething=0;
                   3821:     var founduname=0;
1.243     albertel 3822:     var foundID=0;
1.27      albertel 3823:     for (i=0;i<=vf.nfields.value;i++) {
                   3824:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3825:       if (tw==1) { foundID=1; }
                   3826:       if (tw==2) { founduname=1; }
                   3827:       if (tw>3) { foundsomething=1; }
1.27      albertel 3828:     }
1.246     albertel 3829:     if (founduname==0 && foundID==0) {
                   3830: 	alert('$error1');
                   3831: 	return;
1.27      albertel 3832:     }
                   3833:     if (foundsomething==0) {
1.246     albertel 3834: 	alert('$error2');
                   3835: 	return;
1.27      albertel 3836:     }
                   3837:     vf.submit();
                   3838:   }
                   3839:   function flip(vf,tf) {
                   3840:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3841:     var i;
                   3842:     //can not pick the same destination field twice
                   3843:     for (i=0;i<=vf.nfields.value;i++) {
                   3844:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3845:         eval('vf.f'+i+'.selectedIndex=0;')
                   3846:       }
                   3847:     }
                   3848:   }
                   3849: ENDPICK
                   3850: }
                   3851: 
1.26      albertel 3852: sub csvuploadmap_header {
1.324     albertel 3853:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3854:     my $javascript;
1.257     albertel 3855:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3856: 	$javascript=&csvupload_javascript_reverse_associate();
                   3857:     } else {
                   3858: 	$javascript=&csvupload_javascript_forward_associate();
                   3859:     }
1.45      ng       3860: 
1.324     albertel 3861:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3862:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3863:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3864:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3865:     $request->print(<<ENDPICK);
1.26      albertel 3866: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3867: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3868: $result
1.326     albertel 3869: <hr />
1.26      albertel 3870: <h3>Identify fields</h3>
                   3871: Total number of records found in file: $distotal <hr />
                   3872: Enter as many fields as you can. The system will inform you and bring you back
                   3873: to this page if the data selected is insufficient to run your class.<hr />
                   3874: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3875: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3876: <input type="hidden" name="associate"  value="" />
                   3877: <input type="hidden" name="phase"      value="three" />
                   3878: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3879: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3880: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3881: <input type="hidden" name="upfile_associate" 
1.257     albertel 3882:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3883: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3884: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3885: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3886: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3887: <hr />
                   3888: <script type="text/javascript" language="Javascript">
                   3889: $javascript
                   3890: </script>
                   3891: ENDPICK
1.118     ng       3892:     return '';
1.26      albertel 3893: 
                   3894: }
                   3895: 
                   3896: sub csvupload_fields {
1.324     albertel 3897:     my ($symb) = @_;
                   3898:     my (@parts) = &getpartlist($symb);
1.243     albertel 3899:     my @fields=(['ID','Student ID'],
                   3900: 		['username','Student Username'],
                   3901: 		['domain','Student Domain']);
1.324     albertel 3902:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3903:     foreach my $part (sort(@parts)) {
                   3904: 	my @datum;
                   3905: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3906: 	my $name=$part;
                   3907: 	if  (!$display) { $display = $name; }
                   3908: 	@datum=($name,$display);
1.244     albertel 3909: 	if ($name=~/^stores_(.*)_awarded/) {
                   3910: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3911: 	}
1.41      ng       3912: 	push(@fields,\@datum);
                   3913:     }
                   3914:     return (@fields);
1.26      albertel 3915: }
                   3916: 
                   3917: sub csvuploadmap_footer {
1.41      ng       3918:     my ($request,$i,$keyfields) =@_;
                   3919:     $request->print(<<ENDPICK);
1.26      albertel 3920: </table>
                   3921: <input type="hidden" name="nfields" value="$i" />
                   3922: <input type="hidden" name="keyfields" value="$keyfields" />
                   3923: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3924: </form>
                   3925: ENDPICK
                   3926: }
                   3927: 
1.283     albertel 3928: sub checkforfile_js {
1.86      ng       3929:     my $result =<<CSVFORMJS;
                   3930: <script type="text/javascript" language="javascript">
                   3931:     function checkUpload(formname) {
                   3932: 	if (formname.upfile.value == "") {
                   3933: 	    alert("Please use the browse button to select a file from your local directory.");
                   3934: 	    return false;
                   3935: 	}
                   3936: 	formname.submit();
                   3937:     }
                   3938:     </script>
                   3939: CSVFORMJS
1.283     albertel 3940:     return $result;
                   3941: }
                   3942: 
                   3943: sub upcsvScores_form {
                   3944:     my ($request) = shift;
1.324     albertel 3945:     my ($symb)=&get_symb($request);
1.283     albertel 3946:     if (!$symb) {return '';}
                   3947:     my $result=&checkforfile_js();
1.257     albertel 3948:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3949:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3950:     $result.=$table;
1.326     albertel 3951:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3952:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3953:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3954: 	'.</b></td></tr>'."\n";
                   3955:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3956:     my $upload=&mt("Upload Scores");
1.86      ng       3957:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3958:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3959:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3960:     $result.=<<ENDUPFORM;
1.106     albertel 3961: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3962: <input type="hidden" name="symb" value="$symb" />
                   3963: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3964: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3965: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3966: $upfile_select
1.370     www      3967: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3968: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3969: </form>
                   3970: ENDUPFORM
1.370     www      3971:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3972:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3973:     .'</td></tr></table>'."\n";
1.86      ng       3974:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3975:     $result.=&show_grading_menu_form($symb);
1.86      ng       3976:     return $result;
                   3977: }
                   3978: 
                   3979: 
1.26      albertel 3980: sub csvuploadmap {
1.41      ng       3981:     my ($request)= @_;
1.324     albertel 3982:     my ($symb)=&get_symb($request);
1.41      ng       3983:     if (!$symb) {return '';}
1.72      ng       3984: 
1.41      ng       3985:     my $datatoken;
1.257     albertel 3986:     if (!$env{'form.datatoken'}) {
1.41      ng       3987: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3988:     } else {
1.257     albertel 3989: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3990: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3991:     }
1.41      ng       3992:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3993:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3994:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3995:     my ($i,$keyfields);
                   3996:     if (@records) {
1.324     albertel 3997: 	my @fields=&csvupload_fields($symb);
1.45      ng       3998: 
1.257     albertel 3999: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       4000: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   4001: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   4002: 							  \@fields);
                   4003: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   4004: 	    chop($keyfields);
                   4005: 	} else {
                   4006: 	    unshift(@fields,['none','']);
                   4007: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   4008: 							    \@fields);
1.311     banghart 4009:             foreach my $rec (@records) {
                   4010:                 my %temp = &Apache::loncommon::record_sep($rec);
                   4011:                 if (%temp) {
                   4012:                     $keyfields=join(',',sort(keys(%temp)));
                   4013:                     last;
                   4014:                 }
                   4015:             }
1.41      ng       4016: 	}
                   4017:     }
                   4018:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 4019:     $request->print(&show_grading_menu_form($symb));
1.72      ng       4020: 
1.41      ng       4021:     return '';
1.27      albertel 4022: }
                   4023: 
1.246     albertel 4024: sub csvuploadoptions {
1.41      ng       4025:     my ($request)= @_;
1.324     albertel 4026:     my ($symb)=&get_symb($request);
1.257     albertel 4027:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 4028:     my $ignore=&mt('Ignore First Line');
                   4029:     $request->print(<<ENDPICK);
                   4030: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 4031: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 4032: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 4033: <!--
1.246     albertel 4034: <p>
                   4035: <label>
                   4036:    <input type="checkbox" name="show_full_results" />
                   4037:    Show a table of all changes
                   4038: </label>
                   4039: </p>
1.302     albertel 4040: -->
1.246     albertel 4041: <p>
                   4042: <label>
                   4043:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   4044:    Overwrite any existing score
                   4045: </label>
                   4046: </p>
                   4047: ENDPICK
                   4048:     my %fields=&get_fields();
                   4049:     if (!defined($fields{'domain'})) {
1.257     albertel 4050: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 4051: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   4052:     }
1.257     albertel 4053:     foreach my $key (sort(keys(%env))) {
1.246     albertel 4054: 	if ($key !~ /^form\.(.*)$/) { next; }
                   4055: 	my $cleankey=$1;
                   4056: 	if ($cleankey eq 'command') { next; }
                   4057: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 4058: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 4059:     }
                   4060:     # FIXME do a check for any duplicated user ids...
                   4061:     # FIXME do a check for any invalid user ids?...
1.290     albertel 4062:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   4063: <hr /></form>'."\n");
1.324     albertel 4064:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 4065:     return '';
                   4066: }
                   4067: 
                   4068: sub get_fields {
                   4069:     my %fields;
1.257     albertel 4070:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4071:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4072: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   4073: 	    if ($env{'form.f'.$i} ne 'none') {
                   4074: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       4075: 	    }
                   4076: 	} else {
1.257     albertel 4077: 	    if ($env{'form.f'.$i} ne 'none') {
                   4078: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       4079: 	    }
                   4080: 	}
1.27      albertel 4081:     }
1.246     albertel 4082:     return %fields;
                   4083: }
                   4084: 
                   4085: sub csvuploadassign {
                   4086:     my ($request)= @_;
1.324     albertel 4087:     my ($symb)=&get_symb($request);
1.246     albertel 4088:     if (!$symb) {return '';}
1.345     bowersj2 4089:     my $error_msg = '';
1.246     albertel 4090:     &Apache::loncommon::load_tmp_file($request);
                   4091:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 4092:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 4093:     my %fields=&get_fields();
1.41      ng       4094:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 4095:     my $courseid=$env{'request.course.id'};
1.97      albertel 4096:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 4097:     my @notallowed;
1.41      ng       4098:     my @skipped;
                   4099:     my $countdone=0;
                   4100:     foreach my $grade (@gradedata) {
                   4101: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 4102: 	my $domain;
                   4103: 	if ($entries{$fields{'domain'}}) {
                   4104: 	    $domain=$entries{$fields{'domain'}};
                   4105: 	} else {
1.257     albertel 4106: 	    $domain=$env{'form.default_domain'};
1.246     albertel 4107: 	}
1.243     albertel 4108: 	$domain=~s/\s//g;
1.41      ng       4109: 	my $username=$entries{$fields{'username'}};
1.160     albertel 4110: 	$username=~s/\s//g;
1.243     albertel 4111: 	if (!$username) {
                   4112: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 4113: 	    $id=~s/\s//g;
1.243     albertel 4114: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   4115: 	    $username=$ids{$id};
                   4116: 	}
1.41      ng       4117: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4118: 	    my $id=$entries{$fields{'ID'}};
                   4119: 	    $id=~s/\s//g;
                   4120: 	    if ($id) {
                   4121: 		push(@skipped,"$id:$domain");
                   4122: 	    } else {
                   4123: 		push(@skipped,"$username:$domain");
                   4124: 	    }
1.41      ng       4125: 	    next;
                   4126: 	}
1.108     albertel 4127: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4128: 	if (!&canmodify($usec)) {
                   4129: 	    push(@notallowed,"$username:$domain");
                   4130: 	    next;
                   4131: 	}
1.244     albertel 4132: 	my %points;
1.41      ng       4133: 	my %grades;
                   4134: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4135: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4136: 		$dest eq 'domain') { next; }
                   4137: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4138: 	    if ($dest=~/stores_(.*)_points/) {
                   4139: 		my $part=$1;
                   4140: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4141: 					      $symb,$domain,$username);
1.345     bowersj2 4142:                 if ($wgt) {
                   4143:                     $entries{$fields{$dest}}=~s/\s//g;
                   4144:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4145:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4146:                                           : 'correct_by_override';
1.345     bowersj2 4147:                     $grades{"resource.$part.awarded"}=$pcr;
                   4148:                     $grades{"resource.$part.solved"}=$award;
                   4149:                     $points{$part}=1;
                   4150:                 } else {
                   4151:                     $error_msg = "<br />" .
                   4152:                         &mt("Some point values were assigned"
                   4153:                             ." for problems with a weight "
                   4154:                             ."of zero. These values were "
                   4155:                             ."ignored.");
                   4156:                 }
1.244     albertel 4157: 	    } else {
                   4158: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4159: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4160: 		my $store_key=$dest;
                   4161: 		$store_key=~s/^stores/resource/;
                   4162: 		$store_key=~s/_/\./g;
                   4163: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4164: 	    }
1.41      ng       4165: 	}
1.508     www      4166: 	if (! %grades) { 
                   4167:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4168:         } else {
                   4169: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4170: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4171: 					   $env{'request.course.id'},
                   4172: 					   $domain,$username);
1.508     www      4173: 	   if ($result eq 'ok') {
                   4174: 	      $request->print('.');
                   4175: 	   } else {
                   4176: 	      $request->print("<p><span class=\"LC_error\">".
                   4177:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4178:                                   "$username:$domain",$result)."</span></p>");
                   4179: 	   }
                   4180: 	   $request->rflush();
                   4181: 	   $countdone++;
                   4182:         }
1.41      ng       4183:     }
1.508     www      4184:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4185:     if (@skipped) {
1.508     www      4186: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4187: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4188:     }
                   4189:     if (@notallowed) {
1.508     www      4190: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4191: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4192:     }
1.106     albertel 4193:     $request->print("<br />\n");
1.324     albertel 4194:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4195:     return $error_msg;
1.26      albertel 4196: }
1.44      ng       4197: #------------- end of section for handling csv file upload ---------
                   4198: #
                   4199: #-------------------------------------------------------------------
                   4200: #
1.122     ng       4201: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4202: #
                   4203: #--- Select a page/sequence and a student to grade
1.68      ng       4204: sub pickStudentPage {
                   4205:     my ($request) = shift;
                   4206: 
                   4207:     $request->print(<<LISTJAVASCRIPT);
                   4208: <script type="text/javascript" language="javascript">
                   4209: 
                   4210: function checkPickOne(formname) {
1.76      ng       4211:     if (radioSelection(formname.student) == null) {
1.68      ng       4212: 	alert("Please select the student you wish to grade.");
                   4213: 	return;
                   4214:     }
1.125     ng       4215:     ptr = pullDownSelection(formname.selectpage);
                   4216:     formname.page.value = formname["page"+ptr].value;
                   4217:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4218:     formname.submit();
                   4219: }
                   4220: 
                   4221: </script>
                   4222: LISTJAVASCRIPT
1.118     ng       4223:     &commonJSfunctions($request);
1.324     albertel 4224:     my ($symb) = &get_symb($request);
1.257     albertel 4225:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4226:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4227:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4228: 
1.398     albertel 4229:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4230: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4231: 
1.80      ng       4232:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4233:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4234:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4235: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4236: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4237:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4238:     my $ctr=0;
1.68      ng       4239:     foreach (@$titles) {
                   4240: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4241: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4242: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4243: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4244: 	$ctr++;
1.68      ng       4245:     }
1.485     albertel 4246:     $select.= '</select>';
                   4247:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4248: 
1.70      ng       4249:     $ctr=0;
                   4250:     foreach (@$titles) {
                   4251: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4252: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4253: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4254: 	$ctr++;
                   4255:     }
1.72      ng       4256:     $result.='<input type="hidden" name="page" />'."\n".
                   4257: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4258: 
1.485     albertel 4259:     my $options =
                   4260: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4261: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4262:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4263: 
                   4264:     $options =
                   4265: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4266: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4267: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4268:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4269:     
                   4270:     $result.=&build_section_inputs();
1.442     banghart 4271:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4272:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4273: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4274: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4275: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4276: 
1.485     albertel 4277:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4278: 			  '<input type="text" name="CODE" value="" />').
                   4279: 			      '<br />'."\n";
1.382     albertel 4280: 
1.80      ng       4281:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4282: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4283: 
1.68      ng       4284:     $request->print($result);
                   4285: 
1.485     albertel 4286:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4287: 	&Apache::loncommon::start_data_table().
                   4288: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4289: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4290: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4291: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4292: 	'<th>'.&nameUserString('header').'</th>'.
                   4293: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4294:  
1.76      ng       4295:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4296:     my $ptr = 1;
1.294     albertel 4297:     foreach my $student (sort 
                   4298: 			 {
                   4299: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4300: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4301: 			     }
                   4302: 			     return $a cmp $b;
                   4303: 			 } (keys(%$fullname))) {
1.68      ng       4304: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4305: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4306:                                   : '</td>');
1.126     ng       4307: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4308: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4309: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4310: 	$studentTable.=
                   4311: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4312:                          : '');
1.68      ng       4313: 	$ptr++;
                   4314:     }
1.484     albertel 4315:     if ($ptr%2 == 0) {
                   4316: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4317: 	    &Apache::loncommon::end_data_table_row();
                   4318:     }
                   4319:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4320:     $studentTable.='<input type="button" '.
1.485     albertel 4321: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4322: 
1.324     albertel 4323:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4324:     $request->print($studentTable);
                   4325: 
                   4326:     return '';
                   4327: }
                   4328: 
                   4329: sub getSymbMap {
1.132     bowersj2 4330:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4331: 
                   4332:     my %symbx = ();
                   4333:     my @titles = ();
1.117     bowersj2 4334:     my $minder = 0;
                   4335: 
                   4336:     # Gather every sequence that has problems.
1.240     albertel 4337:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4338: 					       1,0,1);
1.117     bowersj2 4339:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4340: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4341: 	    my $title = $minder.'.'.
                   4342: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4343: 	    push(@titles, $title); # minder in case two titles are identical
                   4344: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4345: 	    $minder++;
1.241     albertel 4346: 	}
1.68      ng       4347:     }
                   4348:     return \@titles,\%symbx;
                   4349: }
                   4350: 
1.72      ng       4351: #
                   4352: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4353: sub displayPage {
                   4354:     my ($request) = shift;
                   4355: 
1.324     albertel 4356:     my ($symb) = &get_symb($request);
1.257     albertel 4357:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4358:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4359:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4360:     my $pageTitle = $env{'form.page'};
1.103     albertel 4361:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4362:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4363:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4364: 
                   4365:     #need to make sure we have the correct data for later EXT calls, 
                   4366:     #thus invalidate the cache
                   4367:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4368:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4369:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4370:     &Apache::lonnet::clear_EXT_cache_status();
                   4371: 
1.103     albertel 4372:     if (!&canview($usec)) {
1.485     albertel 4373: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4374: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4375: 	return;
                   4376:     }
1.398     albertel 4377:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4378:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4379: 	'</h3>'."\n";
1.500     albertel 4380:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4381:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4382: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4383:     } else {
                   4384: 	delete($env{'form.CODE'});
                   4385:     }
1.71      ng       4386:     &sub_page_js($request);
                   4387:     $request->print($result);
                   4388: 
1.132     bowersj2 4389:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4390:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4391:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4392:     if (!$map) {
1.485     albertel 4393: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4394: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4395: 	return; 
                   4396:     }
1.68      ng       4397:     my $iterator = $navmap->getIterator($map->map_start(),
                   4398: 					$map->map_finish());
                   4399: 
1.71      ng       4400:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4401: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4402: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4403: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4404: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4405: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4406: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4407: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4408: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4409: 
1.382     albertel 4410:     if (defined($env{'form.CODE'})) {
                   4411: 	$studentTable.=
                   4412: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4413:     }
1.381     albertel 4414:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4415: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4416: 
1.485     albertel 4417:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4418: 	&Apache::loncommon::start_data_table().
                   4419: 	&Apache::loncommon::start_data_table_header_row().
                   4420: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4421: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4422: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4423: 
1.329     albertel 4424:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4425:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4426:     $iterator->next(); # skip the first BEGIN_MAP
                   4427:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4428:     while ($depth > 0) {
1.68      ng       4429:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4430:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4431: 
1.385     albertel 4432:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4433: 	    my $parts = $curRes->parts();
1.68      ng       4434:             my $title = $curRes->compTitle();
1.71      ng       4435: 	    my $symbx = $curRes->symb();
1.484     albertel 4436: 	    $studentTable.=
                   4437: 		&Apache::loncommon::start_data_table_row().
                   4438: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4439: 		(scalar(@{$parts}) == 1 ? '' 
                   4440: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4441: 							scalar(@{$parts}))
                   4442: 		 ).
                   4443: 		 '</td>';
1.71      ng       4444: 	    $studentTable.='<td valign="top">';
1.382     albertel 4445: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4446: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4447: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4448: 					     undef,'both',\%form);
1.71      ng       4449: 	    } else {
1.382     albertel 4450: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4451: 		$companswer =~ s|<form(.*?)>||g;
                   4452: 		$companswer =~ s|</form>||g;
1.71      ng       4453: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4454: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4455: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4456: #		}
1.116     ng       4457: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4458: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4459: 	    }
                   4460: 
1.257     albertel 4461: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4462: 
1.257     albertel 4463: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4464: 		if ($record{'version'} eq '') {
1.485     albertel 4465: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4466: 		} else {
1.116     ng       4467: 		    my %responseType = ();
                   4468: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4469: 			my @responseIds =$curRes->responseIds($partid);
                   4470: 			my @responseType =$curRes->responseType($partid);
                   4471: 			my %responseIds;
                   4472: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4473: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4474: 			}
                   4475: 			$responseType{$partid} = \%responseIds;
1.116     ng       4476: 		    }
1.148     albertel 4477: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4478: 
1.71      ng       4479: 		}
1.257     albertel 4480: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4481: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4482: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4483: 									$env{'request.course.id'},
1.71      ng       4484: 									'','.submission');
                   4485:  
                   4486: 	    }
1.103     albertel 4487: 	    if (&canmodify($usec)) {
                   4488: 		foreach my $partid (@{$parts}) {
                   4489: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4490: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4491: 		    $question++;
                   4492: 		}
1.196     albertel 4493: 		$prob++;
1.71      ng       4494: 	    }
                   4495: 	    $studentTable.='</td></tr>';
1.68      ng       4496: 
1.103     albertel 4497: 	}
1.68      ng       4498:         $curRes = $iterator->next();
                   4499:     }
                   4500: 
1.485     albertel 4501:     $studentTable.='</table>'."\n".
                   4502: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4503: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4504: 	'</form>'."\n";
1.324     albertel 4505:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4506:     $request->print($studentTable);
                   4507: 
                   4508:     return '';
1.119     ng       4509: }
                   4510: 
                   4511: sub displaySubByDates {
1.148     albertel 4512:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4513:     my $isCODE=0;
1.335     albertel 4514:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4515:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4516:     my $studentTable=&Apache::loncommon::start_data_table().
                   4517: 	&Apache::loncommon::start_data_table_header_row().
                   4518: 	'<th>'.&mt('Date/Time').'</th>'.
                   4519: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4520: 	'<th>'.&mt('Submission').'</th>'.
                   4521: 	'<th>'.&mt('Status').'</th>'.
                   4522: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4523:     my ($version);
                   4524:     my %mark;
1.148     albertel 4525:     my %orders;
1.119     ng       4526:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4527:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4528: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4529:     }
1.335     albertel 4530: 
                   4531:     my $interaction;
1.525     raeburn  4532:     my $no_increment = 1;
1.119     ng       4533:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4534: 	my $timestamp = 
                   4535: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4536: 	if (exists($$record{$version.':resource.0.version'})) {
                   4537: 	    $interaction = $$record{$version.':resource.0.version'};
                   4538: 	}
                   4539: 
                   4540: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4541: 		             : "$version:resource");
1.467     albertel 4542: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4543: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4544: 	if ($isCODE) {
                   4545: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4546: 	}
1.119     ng       4547: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4548: 	my @displaySub = ();
                   4549: 	foreach my $partid (@{$parts}) {
1.335     albertel 4550: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4551: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4552: 	    
                   4553: 
1.122     ng       4554: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4555: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4556: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4557: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4558: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4559: 
                   4560: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4561: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4562: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4563: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4564: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4565: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4566: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4567: 		    } else {
1.467     albertel 4568: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4569: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4570: 		    }
1.335     albertel 4571: 		    my $responseType=($isTask ? 'Task'
                   4572:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4573: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4574: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4575: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4576: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4577:                                        $no_increment);
1.148     albertel 4578: 		    }
1.147     albertel 4579: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4580: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4581: 		}
                   4582: 	    }
1.335     albertel 4583: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4584: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4585: 				    $$record{"$where.$partid.checkedin"},
                   4586: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4587: 					'<br />';
1.335     albertel 4588: 	    }
                   4589: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4590: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4591: 		    lc($$record{"$where.$partid.award"}).' '.
                   4592: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4593: 		    '<br />';
                   4594: 	    }
1.335     albertel 4595: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4596: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4597: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4598: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4599: 		$displaySub[2].=
                   4600: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4601: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4602: 	    }
                   4603: 	}
                   4604: 	# needed because old essay regrader has not parts info
                   4605: 	if (exists $$record{"$version:resource.regrader"}) {
                   4606: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4607: 	}
                   4608: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4609: 	if ($displaySub[2]) {
1.467     albertel 4610: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4611: 	}
1.467     albertel 4612: 	$studentTable.='&nbsp;</td>'.
                   4613: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4614:     }
1.467     albertel 4615:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4616:     return $studentTable;
1.71      ng       4617: }
                   4618: 
                   4619: sub updateGradeByPage {
                   4620:     my ($request) = shift;
                   4621: 
1.257     albertel 4622:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4623:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4624:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4625:     my $pageTitle = $env{'form.page'};
1.103     albertel 4626:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4627:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4628:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4629:     if (!&canmodify($usec)) {
1.526     raeburn  4630: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4631: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4632: 	return;
                   4633:     }
1.398     albertel 4634:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4635:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4636: 	'</h3>'."\n";
1.70      ng       4637: 
1.68      ng       4638:     $request->print($result);
                   4639: 
1.132     bowersj2 4640:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4641:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4642:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4643:     if (!$map) {
1.527     raeburn  4644: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4645: 	my ($symb)=&get_symb($request);
                   4646: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4647: 	return; 
                   4648:     }
1.71      ng       4649:     my $iterator = $navmap->getIterator($map->map_start(),
                   4650: 					$map->map_finish());
1.70      ng       4651: 
1.484     albertel 4652:     my $studentTable=
                   4653: 	&Apache::loncommon::start_data_table().
                   4654: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4655: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4656: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4657: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4658: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4659: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4660: 
                   4661:     $iterator->next(); # skip the first BEGIN_MAP
                   4662:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4663:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4664:     while ($depth > 0) {
1.71      ng       4665:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4666:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4667: 
1.385     albertel 4668:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4669: 	    my $parts = $curRes->parts();
1.71      ng       4670:             my $title = $curRes->compTitle();
                   4671: 	    my $symbx = $curRes->symb();
1.484     albertel 4672: 	    $studentTable.=
                   4673: 		&Apache::loncommon::start_data_table_row().
                   4674: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4675: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4676:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4677: 		.')').'</td>';
1.71      ng       4678: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4679: 
                   4680: 	    my %newrecord=();
                   4681: 	    my @displayPts=();
1.269     raeburn  4682:             my %aggregate = ();
                   4683:             my $aggregateflag = 0;
1.71      ng       4684: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4685: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4686: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4687: 
1.257     albertel 4688: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4689: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4690: 		my $partial = $newpts/$wgt;
                   4691: 		my $score;
                   4692: 		if ($partial > 0) {
                   4693: 		    $score = 'correct_by_override';
1.125     ng       4694: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4695: 		    $score = 'incorrect_by_override';
                   4696: 		}
1.257     albertel 4697: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4698: 		if ($dropMenu eq 'excused') {
1.71      ng       4699: 		    $partial = '';
                   4700: 		    $score = 'excused';
1.125     ng       4701: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4702: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4703: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4704: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4705: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4706: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4707: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4708: 		    $changeflag++;
                   4709: 		    $newpts = '';
1.269     raeburn  4710:                     
                   4711:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4712:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4713:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4714:                     if ($aggtries > 0) {
                   4715:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4716:                         $aggregateflag = 1;
                   4717:                     }
1.71      ng       4718: 		}
1.324     albertel 4719: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4720: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4721: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4722: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4723: 		    '&nbsp;<br />';
1.526     raeburn  4724: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4725: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4726: 		    '&nbsp;<br />';
1.71      ng       4727: 		$question++;
1.380     albertel 4728: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4729: 
1.71      ng       4730: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4731: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4732: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4733: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4734: 
                   4735: 		$changeflag++;
                   4736: 	    }
                   4737: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4738: 		my %record = 
                   4739: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4740: 					     $udom,$uname);
                   4741: 
                   4742: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4743: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4744: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4745: 		    $newrecord{'resource.CODE'} = '';
                   4746: 		}
1.257     albertel 4747: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4748: 					$udom,$uname);
1.382     albertel 4749: 		%record = &Apache::lonnet::restore($symbx,
                   4750: 						   $env{'request.course.id'},
                   4751: 						   $udom,$uname);
1.380     albertel 4752: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4753: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4754: 	    }
1.380     albertel 4755: 	    
1.269     raeburn  4756:             if ($aggregateflag) {
                   4757:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4758:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4759:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4760:             }
1.125     ng       4761: 
1.71      ng       4762: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4763: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4764: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4765: 
1.196     albertel 4766: 	    $prob++;
1.68      ng       4767: 	}
1.71      ng       4768:         $curRes = $iterator->next();
1.68      ng       4769:     }
1.98      albertel 4770: 
1.484     albertel 4771:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4772:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4773:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4774: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4775: 		  $changeflag));
1.76      ng       4776:     $request->print($grademsg.$studentTable);
1.68      ng       4777: 
1.70      ng       4778:     return '';
                   4779: }
                   4780: 
1.72      ng       4781: #-------- end of section for handling grading by page/sequence ---------
                   4782: #
                   4783: #-------------------------------------------------------------------
                   4784: 
1.75      albertel 4785: #--------------------Scantron Grading-----------------------------------
                   4786: #
                   4787: #------ start of section for handling grading by page/sequence ---------
                   4788: 
1.423     albertel 4789: =pod
                   4790: 
                   4791: =head1 Bubble sheet grading routines
                   4792: 
1.424     albertel 4793:   For this documentation:
                   4794: 
                   4795:    'scanline' refers to the full line of characters
                   4796:    from the file that we are parsing that represents one entire sheet
                   4797: 
                   4798:    'bubble line' refers to the data
                   4799:    representing the line of bubbles that are on the physical bubble sheet
                   4800: 
                   4801: 
                   4802: The overall process is that a scanned in bubble sheet data is uploaded
                   4803: into a course. When a user wants to grade, they select a
                   4804: sequence/folder of resources, a file of bubble sheet info, and pick
                   4805: one of the predefined configurations for what each scanline looks
                   4806: like.
                   4807: 
                   4808: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4809: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4810: because too light bubbling), 'double bubble' (each bubble line should
                   4811: have no more that one letter picked), invalid or duplicated CODE,
                   4812: invalid student ID
                   4813: 
                   4814: If the CODE option is used that determines the randomization of the
                   4815: homework problems, either way the student ID is looked up into a
                   4816: username:domain.
                   4817: 
                   4818: During the validation phase the instructor can choose to skip scanlines. 
                   4819: 
1.435     foxr     4820: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4821: 
                   4822:   scantron_original_filename (unmodified original file)
                   4823:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4824:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4825: 
                   4826: Also there is a separate hash nohist_scantrondata that contains extra
                   4827: correction information that isn't representable in the bubble sheet
                   4828: file (see &scantron_getfile() for more information)
                   4829: 
                   4830: After all scanlines are either valid, marked as valid or skipped, then
                   4831: foreach line foreach problem in the picked sequence, an ssi request is
                   4832: made that simulates a user submitting their selected letter(s) against
                   4833: the homework problem.
1.423     albertel 4834: 
                   4835: =over 4
                   4836: 
                   4837: 
                   4838: 
                   4839: =item defaultFormData
                   4840: 
                   4841:   Returns html hidden inputs used to hold context/default values.
                   4842: 
                   4843:  Arguments:
                   4844:   $symb - $symb of the current resource 
                   4845: 
                   4846: =cut
1.422     foxr     4847: 
1.81      albertel 4848: sub defaultFormData {
1.324     albertel 4849:     my ($symb)=@_;
1.447     foxr     4850:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4851:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4852:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4853: }
                   4854: 
1.447     foxr     4855: 
1.423     albertel 4856: =pod 
                   4857: 
                   4858: =item getSequenceDropDown
                   4859: 
                   4860:    Return html dropdown of possible sequences to grade
                   4861:  
                   4862:  Arguments:
                   4863:    $symb - $symb of the current resource 
                   4864: 
                   4865: =cut
1.422     foxr     4866: 
1.75      albertel 4867: sub getSequenceDropDown {
1.423     albertel 4868:     my ($symb)=@_;
1.75      albertel 4869:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4870:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4871:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4872:     my $ctr=0;
                   4873:     foreach (@$titles) {
                   4874: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4875: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4876: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4877: 	    '>'.$showtitle.'</option>'."\n";
                   4878: 	$ctr++;
                   4879:     }
                   4880:     $result.= '</select>';
                   4881:     return $result;
                   4882: }
                   4883: 
1.495     albertel 4884: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4885:                                    # index is "symb.part_id"
                   4886: 
                   4887: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4888: 
1.509     raeburn  4889: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4890:                                    # matchresponse or rankresponse, where 
                   4891:                                    # an individual response can have multiple 
                   4892:                                    # lines
1.503     raeburn  4893: 
                   4894: my %responsetype_per_response;     # responsetype for each response
                   4895: 
1.495     albertel 4896: # Save and restore the bubble lines array to the form env.
                   4897: 
                   4898: 
                   4899: sub save_bubble_lines {
                   4900:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4901: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4902: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4903: 	    $first_bubble_line{$line};
1.503     raeburn  4904:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4905:             $subdivided_bubble_lines{$line};
                   4906:         $env{"form.scantron.responsetype.$line"} =
                   4907:             $responsetype_per_response{$line};
1.495     albertel 4908:     }
                   4909: }
                   4910: 
                   4911: 
                   4912: sub restore_bubble_lines {
                   4913:     my $line = 0;
                   4914:     %bubble_lines_per_response = ();
                   4915:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4916: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4917: 	$bubble_lines_per_response{$line} = $value;
                   4918: 	$first_bubble_line{$line}  =
                   4919: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4920:         $subdivided_bubble_lines{$line} =
                   4921:             $env{"form.scantron.sub_bubblelines.$line"};
                   4922:         $responsetype_per_response{$line} =
                   4923:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4924: 	$line++;
                   4925:     }
                   4926: 
                   4927: }
                   4928: 
                   4929: #  Given the parsed scanline, get the response for 
                   4930: #  'answer' number n:
                   4931: 
                   4932: sub get_response_bubbles {
                   4933:     my ($parsed_line, $response)  = @_;
                   4934: 
                   4935: 
                   4936:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4937:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4938:     
                   4939:     my $selected = "";
                   4940: 
                   4941:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4942: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4943: 	$bubble_line++;
                   4944:     }
                   4945:     return $selected;
                   4946: }
1.423     albertel 4947: 
                   4948: =pod 
                   4949: 
                   4950: =item scantron_filenames
                   4951: 
                   4952:    Returns a list of the scantron files in the current course 
                   4953: 
                   4954: =cut
1.422     foxr     4955: 
1.202     albertel 4956: sub scantron_filenames {
1.257     albertel 4957:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4959:     my $getpropath = 1;
1.157     albertel 4960:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4961:                                        $getpropath);
1.202     albertel 4962:     my @possiblenames;
1.201     albertel 4963:     foreach my $filename (sort(@files)) {
1.157     albertel 4964: 	($filename)=split(/&/,$filename);
                   4965: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4966: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4967: 	push(@possiblenames,$filename);
                   4968:     }
                   4969:     return @possiblenames;
                   4970: }
                   4971: 
1.423     albertel 4972: =pod 
                   4973: 
                   4974: =item scantron_uploads
                   4975: 
                   4976:    Returns  html drop-down list of scantron files in current course.
                   4977: 
                   4978:  Arguments:
                   4979:    $file2grade - filename to set as selected in the dropdown
                   4980: 
                   4981: =cut
1.422     foxr     4982: 
1.202     albertel 4983: sub scantron_uploads {
1.209     ng       4984:     my ($file2grade) = @_;
1.202     albertel 4985:     my $result=	'<select name="scantron_selectfile">';
                   4986:     $result.="<option></option>";
                   4987:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4988: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4989:     }
                   4990:     $result.="</select>";
                   4991:     return $result;
                   4992: }
                   4993: 
1.423     albertel 4994: =pod 
                   4995: 
                   4996: =item scantron_scantab
                   4997: 
                   4998:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4999:   file.
                   5000: 
                   5001: =cut
1.422     foxr     5002: 
1.82      albertel 5003: sub scantron_scantab {
                   5004:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 5005:     $result.='<option></option>'."\n";
1.518     raeburn  5006:     my @lines = &get_scantronformat_file();
                   5007:     if (@lines > 0) {
                   5008:         foreach my $line (@lines) {
                   5009:             next if (($line =~ /^\#/) || ($line eq ''));
                   5010: 	    my ($name,$descrip)=split(/:/,$line);
                   5011: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   5012:         }
1.82      albertel 5013:     }
                   5014:     $result.='</select>'."\n";
1.518     raeburn  5015:     return $result;
                   5016: }
                   5017: 
                   5018: =pod
                   5019: 
                   5020: =item get_scantronformat_file
                   5021: 
                   5022:   Returns an array containing lines from the scantron format file for
                   5023:   the domain of the course.
                   5024: 
                   5025:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   5026:   lines are from this file.
                   5027: 
                   5028:   Otherwise, if a default.tab has been published in RES space by the 
                   5029:   domainconfig user, lines are from this file.
                   5030: 
                   5031:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  5032:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 5033: 
1.518     raeburn  5034: =cut
                   5035: 
                   5036: sub get_scantronformat_file {
                   5037:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5038:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   5039:     my $gottab = 0;
                   5040:     my @lines;
                   5041:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   5042:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   5043:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   5044:             if ($formatfile ne '-1') {
                   5045:                 @lines = split("\n",$formatfile,-1);
                   5046:                 $gottab = 1;
                   5047:             }
                   5048:         }
                   5049:     }
                   5050:     if (!$gottab) {
                   5051:         my $confname = $cdom.'-domainconfig';
                   5052:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   5053:         my $formatfile =  &Apache::lonnet::getfile($default);
                   5054:         if ($formatfile ne '-1') {
                   5055:             @lines = split("\n",$formatfile,-1);
                   5056:             $gottab = 1;
                   5057:         }
                   5058:     }
                   5059:     if (!$gottab) {
1.519     raeburn  5060:         my @domains = &Apache::lonnet::current_machine_domains();
                   5061:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   5062:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5063:             @lines = <$fh>;
                   5064:             close($fh);
                   5065:         } else {
                   5066:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   5067:             @lines = <$fh>;
                   5068:             close($fh);
                   5069:         }
1.518     raeburn  5070:     }
                   5071:     return @lines;
1.82      albertel 5072: }
                   5073: 
1.423     albertel 5074: =pod 
                   5075: 
                   5076: =item scantron_CODElist
                   5077: 
                   5078:   Returns html drop down of the saved CODE lists from current course,
                   5079:   generated from earlier printings.
                   5080: 
                   5081: =cut
1.422     foxr     5082: 
1.186     albertel 5083: sub scantron_CODElist {
1.257     albertel 5084:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5085:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 5086:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   5087:     my $namechoice='<option></option>';
1.225     albertel 5088:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 5089: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 5090: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 5091: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   5092:     }
                   5093:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   5094:     return $namechoice;
                   5095: }
                   5096: 
1.423     albertel 5097: =pod 
                   5098: 
                   5099: =item scantron_CODEunique
                   5100: 
                   5101:   Returns the html for "Each CODE to be used once" radio.
                   5102: 
                   5103: =cut
1.422     foxr     5104: 
1.186     albertel 5105: sub scantron_CODEunique {
1.381     albertel 5106:     my $result='<span style="white-space: nowrap;">
1.272     albertel 5107:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5108:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 5109:                 </span>
                   5110:                 <span style="white-space: nowrap;">
1.272     albertel 5111:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 5112:                         value="no" />'.&mt('No').' </label>
1.381     albertel 5113:                 </span>';
1.186     albertel 5114:     return $result;
                   5115: }
1.423     albertel 5116: 
                   5117: =pod 
                   5118: 
                   5119: =item scantron_selectphase
                   5120: 
                   5121:   Generates the initial screen to start the bubble sheet process.
                   5122:   Allows for - starting a grading run.
1.424     albertel 5123:              - downloading existing scan data (original, corrected
1.423     albertel 5124:                                                 or skipped info)
                   5125: 
                   5126:              - uploading new scan data
                   5127: 
                   5128:  Arguments:
                   5129:   $r          - The Apache request object
                   5130:   $file2grade - name of the file that contain the scanned data to score
                   5131: 
                   5132: =cut
1.186     albertel 5133: 
1.75      albertel 5134: sub scantron_selectphase {
1.209     ng       5135:     my ($r,$file2grade) = @_;
1.324     albertel 5136:     my ($symb)=&get_symb($r);
1.75      albertel 5137:     if (!$symb) {return '';}
1.423     albertel 5138:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5139:     my $default_form_data=&defaultFormData($symb);
                   5140:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5141:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5142:     my $format_selector=&scantron_scantab();
1.186     albertel 5143:     my $CODE_selector=&scantron_CODElist();
                   5144:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5145:     my $result;
1.422     foxr     5146: 
1.513     foxr     5147:     $ssi_error = 0;
                   5148: 
1.422     foxr     5149:     # Chunk of form to prompt for a file to grade and how:
                   5150: 
1.489     albertel 5151:     $result.= '
                   5152:     <br />
                   5153:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5154:     <input type="hidden" name="command" value="scantron_warning" />
                   5155:     '.$default_form_data.'
                   5156:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5157:        '.&Apache::loncommon::start_data_table_header_row().'
                   5158:             <th colspan="2">
1.492     albertel 5159:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5160:             </th>
                   5161:        '.&Apache::loncommon::end_data_table_header_row().'
                   5162:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5163:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5164:        '.&Apache::loncommon::end_data_table_row().'
                   5165:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5166:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5167:        '.&Apache::loncommon::end_data_table_row().'
                   5168:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5169:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5170:        '.&Apache::loncommon::end_data_table_row().'
                   5171:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5172:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5173:        '.&Apache::loncommon::end_data_table_row().'
                   5174:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5175:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5176:        '.&Apache::loncommon::end_data_table_row().'
                   5177:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5178: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5179:             <td>
1.492     albertel 5180: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5181:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5182:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5183: 	    </td>
1.489     albertel 5184:        '.&Apache::loncommon::end_data_table_row().'
                   5185:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5186:             <td colspan="2">
1.492     albertel 5187:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5188:             </td>
1.489     albertel 5189:        '.&Apache::loncommon::end_data_table_row().'
                   5190:     '.&Apache::loncommon::end_data_table().'
                   5191:     </form>
                   5192: ';
1.162     albertel 5193:    
                   5194:     $r->print($result);
                   5195: 
1.257     albertel 5196:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5197:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5198: 
1.422     foxr     5199: 	# Chunk of form to prompt for a scantron file upload.
                   5200: 
1.489     albertel 5201:         $r->print('
                   5202:     <br />
                   5203:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5204:        '.&Apache::loncommon::start_data_table_header_row().'
                   5205:             <th>
1.492     albertel 5206:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5207:             </th>
                   5208:        '.&Apache::loncommon::end_data_table_header_row().'
                   5209:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5210:             <td>
1.489     albertel 5211: ');
1.324     albertel 5212:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5213:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5214:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5215:     $r->print('
1.174     albertel 5216:               <script type="text/javascript" language="javascript">
                   5217:     function checkUpload(formname) {
                   5218: 	if (formname.upfile.value == "") {
1.492     albertel 5219: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5220: 	    return false;
                   5221: 	}
                   5222: 	formname.submit();
                   5223:     }
                   5224:               </script>
                   5225: 
1.492     albertel 5226:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5227:                 '.$default_form_data.'
                   5228:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5229:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5230:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5231:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5232:                 <br />
1.492     albertel 5233:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5234:               </form>
1.492     albertel 5235: ');
1.162     albertel 5236: 
1.489     albertel 5237:         $r->print('
1.162     albertel 5238:             </td>
1.489     albertel 5239:        '.&Apache::loncommon::end_data_table_row().'
                   5240:        '.&Apache::loncommon::end_data_table().'
                   5241: ');
1.162     albertel 5242:     }
1.422     foxr     5243: 
                   5244:     # Chunk of the form that prompts to view a scoring office file,
                   5245:     # corrected file, skipped records in a file.
                   5246: 
1.489     albertel 5247:     $r->print('
                   5248:    <br />
                   5249:    <form action="/adm/grades" name="scantron_download">
                   5250:      '.$default_form_data.'
                   5251:      <input type="hidden" name="command" value="scantron_download" />
                   5252:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5253:        '.&Apache::loncommon::start_data_table_header_row().'
                   5254:               <th>
1.492     albertel 5255:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5256:               </th>
                   5257:        '.&Apache::loncommon::end_data_table_header_row().'
                   5258:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5259:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5260:                 <br />
1.492     albertel 5261:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5262:        '.&Apache::loncommon::end_data_table_row().'
                   5263:      '.&Apache::loncommon::end_data_table().'
                   5264:    </form>
                   5265:    <br />
                   5266: ');
1.162     albertel 5267: 
1.457     banghart 5268:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5269: 
1.528     raeburn  5270:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5271:              $default_form_data."\n".
                   5272:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5273:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5274:              '<th colspan="2">
                   5275:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5276:              '</th>'."\n".
                   5277:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5278:               &Apache::loncommon::start_data_table_row()."\n".
                   5279:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5280:               '<td> '.$sequence_selector.' </td>'.
                   5281:               &Apache::loncommon::end_data_table_row()."\n".
                   5282:               &Apache::loncommon::start_data_table_row()."\n".
                   5283:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5284:               '<td> '.$file_selector.' </td>'."\n".
                   5285:               &Apache::loncommon::end_data_table_row()."\n".
                   5286:               &Apache::loncommon::start_data_table_row()."\n".
                   5287:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5288:               '<td> '.$format_selector.' </td>'."\n".
                   5289:               &Apache::loncommon::end_data_table_row()."\n".
                   5290:               &Apache::loncommon::start_data_table_row()."\n".
                   5291:               '<td colspan="2">'."\n".
                   5292:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5293:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5294:               '</td>'."\n".
                   5295:               &Apache::loncommon::end_data_table_row()."\n".
                   5296:               &Apache::loncommon::end_data_table()."\n".
                   5297:               '</form><br />');
1.457     banghart 5298:     $r->print($grading_menu_button);
1.523     raeburn  5299:     return;
1.75      albertel 5300: }
                   5301: 
1.423     albertel 5302: =pod
                   5303: 
                   5304: =item get_scantron_config
                   5305: 
                   5306:    Parse and return the scantron configuration line selected as a
                   5307:    hash of configuration file fields.
                   5308: 
                   5309:  Arguments:
                   5310:     which - the name of the configuration to parse from the file.
                   5311: 
                   5312: 
                   5313:  Returns:
                   5314:             If the named configuration is not in the file, an empty
                   5315:             hash is returned.
                   5316:     a hash with the fields
                   5317:       name         - internal name for the this configuration setup
                   5318:       description  - text to display to operator that describes this config
                   5319:       CODElocation - if 0 or the string 'none'
                   5320:                           - no CODE exists for this config
                   5321:                      if -1 || the string 'letter'
                   5322:                           - a CODE exists for this config and is
                   5323:                             a string of letters
                   5324:                      Unsupported value (but planned for future support)
                   5325:                           if a positive integer
                   5326:                                - The CODE exists as the first n items from
                   5327:                                  the question section of the form
                   5328:                           if the string 'number'
                   5329:                                - The CODE exists for this config and is
                   5330:                                  a string of numbers
                   5331:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5332:                      the CODE starts
                   5333:       CODElength  - length of the CODE
                   5334:       IDstart     - column where the student ID number starts
                   5335:       IDlength    - length of the student ID info
                   5336:       Qstart      - column where the information from the bubbled
                   5337:                     'questions' start
                   5338:       Qlength     - number of columns comprising a single bubble line from
                   5339:                     the sheet. (usually either 1 or 10)
1.424     albertel 5340:       Qon         - either a single character representing the character used
1.423     albertel 5341:                     to signal a bubble was chosen in the positional setup, or
                   5342:                     the string 'letter' if the letter of the chosen bubble is
                   5343:                     in the final, or 'number' if a number representing the
                   5344:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5345:       Qoff        - the character used to represent that a bubble was
                   5346:                     left blank
1.423     albertel 5347:       PaperID     - if the scanning process generates a unique number for each
                   5348:                     sheet scanned the column that this ID number starts in
                   5349:       PaperIDlength - number of columns that comprise the unique ID number
                   5350:                       for the sheet of paper
1.424     albertel 5351:       FirstName   - column that the first name starts in
1.423     albertel 5352:       FirstNameLength - number of columns that the first name spans
                   5353:  
                   5354:       LastName    - column that the last name starts in
                   5355:       LastNameLength - number of columns that the last name spans
                   5356: 
                   5357: =cut
1.422     foxr     5358: 
1.82      albertel 5359: sub get_scantron_config {
                   5360:     my ($which) = @_;
1.518     raeburn  5361:     my @lines = &get_scantronformat_file();
1.82      albertel 5362:     my %config;
1.157     albertel 5363:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5364:     foreach my $line (@lines) {
1.82      albertel 5365: 	my ($name,$descrip)=split(/:/,$line);
                   5366: 	if ($name ne $which ) { next; }
                   5367: 	chomp($line);
                   5368: 	my @config=split(/:/,$line);
                   5369: 	$config{'name'}=$config[0];
                   5370: 	$config{'description'}=$config[1];
                   5371: 	$config{'CODElocation'}=$config[2];
                   5372: 	$config{'CODEstart'}=$config[3];
                   5373: 	$config{'CODElength'}=$config[4];
                   5374: 	$config{'IDstart'}=$config[5];
                   5375: 	$config{'IDlength'}=$config[6];
                   5376: 	$config{'Qstart'}=$config[7];
1.497     foxr     5377:  	$config{'Qlength'}=$config[8];
1.82      albertel 5378: 	$config{'Qoff'}=$config[9];
                   5379: 	$config{'Qon'}=$config[10];
1.157     albertel 5380: 	$config{'PaperID'}=$config[11];
                   5381: 	$config{'PaperIDlength'}=$config[12];
                   5382: 	$config{'FirstName'}=$config[13];
                   5383: 	$config{'FirstNamelength'}=$config[14];
                   5384: 	$config{'LastName'}=$config[15];
                   5385: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5386: 	last;
                   5387:     }
                   5388:     return %config;
                   5389: }
                   5390: 
1.423     albertel 5391: =pod 
                   5392: 
                   5393: =item username_to_idmap
                   5394: 
                   5395:     creates a hash keyed by student id with values of the corresponding
                   5396:     student username:domain.
                   5397: 
                   5398:   Arguments:
                   5399: 
                   5400:     $classlist - reference to the class list hash. This is a hash
                   5401:                  keyed by student name:domain  whose elements are references
1.424     albertel 5402:                  to arrays containing various chunks of information
1.423     albertel 5403:                  about the student. (See loncoursedata for more info).
                   5404: 
                   5405:   Returns
                   5406:     %idmap - the constructed hash
                   5407: 
                   5408: =cut
                   5409: 
1.82      albertel 5410: sub username_to_idmap {
                   5411:     my ($classlist)= @_;
                   5412:     my %idmap;
                   5413:     foreach my $student (keys(%$classlist)) {
                   5414: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5415: 	    $student;
                   5416:     }
                   5417:     return %idmap;
                   5418: }
1.423     albertel 5419: 
                   5420: =pod
                   5421: 
1.424     albertel 5422: =item scantron_fixup_scanline
1.423     albertel 5423: 
                   5424:    Process a requested correction to a scanline.
                   5425: 
                   5426:   Arguments:
                   5427:     $scantron_config   - hash from &get_scantron_config()
                   5428:     $scan_data         - hash of correction information 
                   5429:                           (see &scantron_getfile())
                   5430:     $line              - existing scanline
                   5431:     $whichline         - line number of the passed in scanline
                   5432:     $field             - type of change to process 
                   5433:                          (either 
                   5434:                           'ID'     -> correct the student ID number
                   5435:                           'CODE'   -> correct the CODE
                   5436:                           'answer' -> fixup the submitted answers)
                   5437:     
                   5438:    $args               - hash of additional info,
                   5439:                           - 'ID' 
                   5440:                                'newid' -> studentID to use in replacement
1.424     albertel 5441:                                           of existing one
1.423     albertel 5442:                           - 'CODE' 
                   5443:                                'CODE_ignore_dup' - set to true if duplicates
                   5444:                                                    should be ignored.
                   5445: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5446:                                         if the existing unfound code should
1.423     albertel 5447:                                         be used as is
                   5448:                           - 'answer'
                   5449:                                'response' - new answer or 'none' if blank
                   5450:                                'question' - the bubble line to change
1.503     raeburn  5451:                                'questionnum' - the question identifier,
                   5452:                                                may include subquestion. 
1.423     albertel 5453: 
                   5454:   Returns:
                   5455:     $line - the modified scanline
                   5456: 
                   5457:   Side effects: 
                   5458:     $scan_data - may be updated
                   5459: 
                   5460: =cut
                   5461: 
1.82      albertel 5462: 
1.157     albertel 5463: sub scantron_fixup_scanline {
                   5464:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5465:     if ($field eq 'ID') {
                   5466: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5467: 	    return ($line,1,'New value too large');
1.157     albertel 5468: 	}
                   5469: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5470: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5471: 				     $args->{'newid'});
                   5472: 	}
                   5473: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5474: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5475: 	if ($args->{'newid'}=~/^\s*$/) {
                   5476: 	    &scan_data($scan_data,"$whichline.user",
                   5477: 		       $args->{'username'}.':'.$args->{'domain'});
                   5478: 	}
1.186     albertel 5479:     } elsif ($field eq 'CODE') {
1.192     albertel 5480: 	if ($args->{'CODE_ignore_dup'}) {
                   5481: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5482: 	}
                   5483: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5484: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5485: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5486: 		return ($line,1,'New CODE value too large');
                   5487: 	    }
                   5488: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5489: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5490: 	    }
                   5491: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5492: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5493: 	}
1.157     albertel 5494:     } elsif ($field eq 'answer') {
1.497     foxr     5495: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5496: 	my $off=$scantron_config->{'Qoff'};
                   5497: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5498: 	my $answer=${off}x$length;
                   5499: 	if ($args->{'response'} eq 'none') {
                   5500: 	    &scan_data($scan_data,
1.503     raeburn  5501: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5502: 	} else {
                   5503: 	    if ($on eq 'letter') {
                   5504: 		my @alphabet=('A'..'Z');
                   5505: 		$answer=$alphabet[$args->{'response'}];
                   5506: 	    } elsif ($on eq 'number') {
                   5507: 		$answer=$args->{'response'}+1;
                   5508: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5509: 	    } else {
1.497     foxr     5510: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5511: 	    }
1.497     foxr     5512: 	    &scan_data($scan_data,
1.503     raeburn  5513: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5514: 	}
1.497     foxr     5515: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5516: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5517:     }
                   5518:     return $line;
                   5519: }
1.423     albertel 5520: 
                   5521: =pod
                   5522: 
                   5523: =item scan_data
                   5524: 
                   5525:     Edit or look up  an item in the scan_data hash.
                   5526: 
                   5527:   Arguments:
                   5528:     $scan_data  - The hash (see scantron_getfile)
                   5529:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5530:                   scantronfilename_key).
1.423     albertel 5531:     $data        - New value of the hash entry.
                   5532:     $delete      - If true, the entry is removed from the hash.
                   5533: 
                   5534:   Returns:
                   5535:     The new value of the hash table field (undefined if deleted).
                   5536: 
                   5537: =cut
                   5538: 
                   5539: 
1.157     albertel 5540: sub scan_data {
                   5541:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5542:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5543:     if (defined($value)) {
                   5544: 	$scan_data->{$filename.'_'.$key} = $value;
                   5545:     }
                   5546:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5547:     return $scan_data->{$filename.'_'.$key};
                   5548: }
1.423     albertel 5549: 
1.495     albertel 5550: # ----- These first few routines are general use routines.----
                   5551: 
                   5552: # Return the number of occurences of a pattern in a string.
                   5553: 
                   5554: sub occurence_count {
                   5555:     my ($string, $pattern) = @_;
                   5556: 
                   5557:     my @matches = ($string =~ /$pattern/g);
                   5558: 
                   5559:     return scalar(@matches);
                   5560: }
                   5561: 
                   5562: 
                   5563: # Take a string known to have digits and convert all the
                   5564: # digits into letters in the range J,A..I.
                   5565: 
                   5566: sub digits_to_letters {
                   5567:     my ($input) = @_;
                   5568: 
                   5569:     my @alphabet = ('J', 'A'..'I');
                   5570: 
                   5571:     my @input    = split(//, $input);
                   5572:     my $output ='';
                   5573:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5574: 	if ($input[$i] =~ /\d/) {
                   5575: 	    $output .= $alphabet[$input[$i]];
                   5576: 	} else {
                   5577: 	    $output .= $input[$i];
                   5578: 	}
                   5579:     }
                   5580:     return $output;
                   5581: }
                   5582: 
1.423     albertel 5583: =pod 
                   5584: 
                   5585: =item scantron_parse_scanline
                   5586: 
                   5587:   Decodes a scanline from the selected scantron file
                   5588: 
                   5589:  Arguments:
                   5590:     line             - The text of the scantron file line to process
                   5591:     whichline        - Line number
                   5592:     scantron_config  - Hash describing the format of the scantron lines.
                   5593:     scan_data        - Hash of extra information about the scanline
                   5594:                        (see scantron_getfile for more information)
                   5595:     just_header      - True if should not process question answers but only
                   5596:                        the stuff to the left of the answers.
                   5597:  Returns:
                   5598:    Hash containing the result of parsing the scanline
                   5599: 
                   5600:    Keys are all proceeded by the string 'scantron.'
                   5601: 
                   5602:        CODE    - the CODE in use for this scanline
                   5603:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5604:                  by the operator
                   5605:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5606:                             CODEs were selected, but the usage has been
                   5607:                             forced by the operator
                   5608:        ID  - student ID
                   5609:        PaperID - if used, the ID number printed on the sheet when the 
                   5610:                  paper was scanned
                   5611:        FirstName - first name from the sheet
                   5612:        LastName  - last name from the sheet
                   5613: 
                   5614:      if just_header was not true these key may also exist
                   5615: 
1.447     foxr     5616:        missingerror - a list of bubble ranges that are considered to be answers
                   5617:                       to a single question that don't have any bubbles filled in.
                   5618:                       Of the form questionnumber:firstbubblenumber:count.
                   5619:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5620:                       to a single question that have more than one bubble filled in.
                   5621:                       Of the form questionnumber::firstbubblenumber:count
                   5622:    
                   5623:                 In the above, count is the number of bubble responses in the
                   5624:                 input line needed to represent the possible answers to the question.
                   5625:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5626:                 per line would have count = 2.
                   5627: 
1.423     albertel 5628:        maxquest     - the number of the last bubble line that was parsed
                   5629: 
                   5630:        (<number> starts at 1)
                   5631:        <number>.answer - zero or more letters representing the selected
                   5632:                          letters from the scanline for the bubble line 
                   5633:                          <number>.
                   5634:                          if blank there was either no bubble or there where
                   5635:                          multiple bubbles, (consult the keys missingerror and
                   5636:                          doubleerror if this is an error condition)
                   5637: 
                   5638: =cut
                   5639: 
1.82      albertel 5640: sub scantron_parse_scanline {
1.423     albertel 5641:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5642: 
1.82      albertel 5643:     my %record;
1.422     foxr     5644:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5645:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5646:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5647: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5648: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5649: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5650: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5651: 	    $record{'scantron.CODE'}=substr($data,
                   5652: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5653: 					    $$scantron_config{'CODElength'});
1.191     albertel 5654: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5655: 		$record{'scantron.useCODE'}=1;
                   5656: 	    }
1.192     albertel 5657: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5658: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5659: 	    }
1.82      albertel 5660: 	} else {
                   5661: 	    #FIXME interpret first N questions
                   5662: 	}
                   5663:     }
1.83      albertel 5664:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5665: 				  $$scantron_config{'IDlength'});
1.157     albertel 5666:     $record{'scantron.PaperID'}=
                   5667: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5668: 	       $$scantron_config{'PaperIDlength'});
                   5669:     $record{'scantron.FirstName'}=
                   5670: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5671: 	       $$scantron_config{'FirstNamelength'});
                   5672:     $record{'scantron.LastName'}=
                   5673: 	substr($data,$$scantron_config{'LastName'}-1,
                   5674: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5675:     if ($just_header) { return \%record; }
1.194     albertel 5676: 
1.82      albertel 5677:     my @alphabet=('A'..'Z');
                   5678:     my $questnum=0;
1.447     foxr     5679:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5680: 
1.470     foxr     5681:     chomp($questions);		# Get rid of any trailing \n.
                   5682:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5683:     while (length($questions)) {
1.447     foxr     5684: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5685:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5686:                              || 1;
                   5687:         $questnum++;
                   5688:         my $quest_id = $questnum;
                   5689:         my $currentquest = substr($questions,0,$answer_length);
                   5690:         $questions       = substr($questions,$answer_length);
                   5691:         if (length($currentquest) < $answer_length) { next; }
                   5692: 
                   5693:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5694:             my $subquestnum = 1;
                   5695:             my $subquestions = $currentquest;
                   5696:             my @subanswers_needed = 
                   5697:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5698:             foreach my $subans (@subanswers_needed) {
                   5699:                 my $subans_length =
                   5700:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5701:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5702:                 $subquestions   = substr($subquestions,$subans_length);
                   5703:                 $quest_id = "$questnum.$subquestnum";
                   5704:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5705:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5706:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5707:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5708:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5709:                 } else {
                   5710:                     $ansnum = &scantron_validator_positional($ansnum,
                   5711:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5712:                 }
                   5713:                 $subquestnum ++;
                   5714:             }
                   5715:         } else {
                   5716:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5717:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5718:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5719:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5720:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5721:             } else {
                   5722:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5723:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5724:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5725:             }
                   5726:         }
                   5727:     }
                   5728:     $record{'scantron.maxquest'}=$questnum;
                   5729:     return \%record;
                   5730: }
1.447     foxr     5731: 
1.503     raeburn  5732: sub scantron_validator_lettnum {
                   5733:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5734:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5735: 
                   5736:     # Qon 'letter' implies for each slot in currquest we have:
                   5737:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5738:     #    about anything else (esp. a value of Qoff) for missing
                   5739:     #    bubbles.
                   5740:     #
                   5741:     # Qon 'number' implies each slot gives a digit that indexes the
                   5742:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5743:     #    and * or ? for double bubbles on a single line.
                   5744:     #
1.447     foxr     5745: 
1.503     raeburn  5746:     my $matchon;
                   5747:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5748:         $matchon = '[A-Z]';
                   5749:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5750:         $matchon = '\d';
                   5751:     }
                   5752:     my $occurrences = 0;
                   5753:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5754:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5755:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5756:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5757:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5758:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5759:         my @singlelines = split('',$currquest);
                   5760:         foreach my $entry (@singlelines) {
                   5761:             $occurrences = &occurence_count($entry,$matchon);
                   5762:             if ($occurrences > 1) {
                   5763:                 last;
                   5764:             }
                   5765:         } 
                   5766:     } else {
                   5767:         $occurrences = &occurence_count($currquest,$matchon); 
                   5768:     }
                   5769:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5770:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5771:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5772:             my $bubble = substr($currquest,$ans,1);
                   5773:             if ($bubble =~ /$matchon/ ) {
                   5774:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5775:                     if ($bubble == 0) {
                   5776:                         $bubble = 10; 
                   5777:                     }
                   5778:                     $record->{"scantron.$ansnum.answer"} = 
                   5779:                         $alphabet->[$bubble-1];
                   5780:                 } else {
                   5781:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5782:                 }
                   5783:             } else {
                   5784:                 $record->{"scantron.$ansnum.answer"}='';
                   5785:             }
                   5786:             $ansnum++;
                   5787:         }
                   5788:     } elsif (!defined($currquest)
                   5789:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5790:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5791:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5792:             $record->{"scantron.$ansnum.answer"}='';
                   5793:             $ansnum++;
                   5794:         }
                   5795:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5796:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5797:         }
                   5798:     } else {
                   5799:         if ($$scantron_config{'Qon'} eq 'number') {
                   5800:             $currquest = &digits_to_letters($currquest);            
                   5801:         }
                   5802:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5803:             my $bubble = substr($currquest,$ans,1);
                   5804:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5805:             $ansnum++;
                   5806:         }
                   5807:     }
                   5808:     return $ansnum;
                   5809: }
1.447     foxr     5810: 
1.503     raeburn  5811: sub scantron_validator_positional {
                   5812:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5813:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5814: 
1.503     raeburn  5815:     # Otherwise there's a positional notation;
                   5816:     # each bubble line requires Qlength items, and there are filled in
                   5817:     # bubbles for each case where there 'Qon' characters.
                   5818:     #
1.447     foxr     5819: 
1.503     raeburn  5820:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5821: 
1.503     raeburn  5822:     # If the split only gives us one element.. the full length of the
                   5823:     # answer string, no bubbles are filled in:
1.447     foxr     5824: 
1.507     raeburn  5825:     if ($answers_needed eq '') {
                   5826:         return;
                   5827:     }
                   5828: 
1.503     raeburn  5829:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5830:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5831:             $record->{"scantron.$ansnum.answer"}='';
                   5832:             $ansnum++;
                   5833:         }
                   5834:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5835:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5836:         }
                   5837:     } elsif (scalar(@array) == 2) {
                   5838:         my $location = length($array[0]);
                   5839:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5840:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5841:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5842:             if ($ans eq $line_num) {
                   5843:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5844:             } else {
                   5845:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5846:             }
                   5847:             $ansnum++;
                   5848:          }
                   5849:     } else {
                   5850:         #  If there's more than one instance of a bubble character
                   5851:         #  That's a double bubble; with positional notation we can
                   5852:         #  record all the bubbles filled in as well as the
                   5853:         #  fact this response consists of multiple bubbles.
                   5854:         #
                   5855:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5856:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5857:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5858:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5859:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5860:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5861:             my $doubleerror = 0;
                   5862:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5863:                    (!$doubleerror)) {
                   5864:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5865:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5866:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5867:                if (length(@currarray) > 2) {
                   5868:                    $doubleerror = 1;
                   5869:                } 
                   5870:             }
                   5871:             if ($doubleerror) {
                   5872:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5873:             }
                   5874:         } else {
                   5875:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5876:         }
                   5877:         my $item = $ansnum;
                   5878:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5879:             $record->{"scantron.$item.answer"} = '';
                   5880:             $item ++;
                   5881:         }
1.447     foxr     5882: 
1.503     raeburn  5883:         my @ans=@array;
                   5884:         my $i=0;
                   5885:         my $increment = 0;
                   5886:         while ($#ans) {
                   5887:             $i+=length($ans[0]) + $increment;
                   5888:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5889:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5890:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5891:             shift(@ans);
                   5892:             $increment = 1;
                   5893:         }
                   5894:         $ansnum += $answers_needed;
1.82      albertel 5895:     }
1.503     raeburn  5896:     return $ansnum;
1.82      albertel 5897: }
                   5898: 
1.423     albertel 5899: =pod
                   5900: 
                   5901: =item scantron_add_delay
                   5902: 
                   5903:    Adds an error message that occurred during the grading phase to a
                   5904:    queue of messages to be shown after grading pass is complete
                   5905: 
                   5906:  Arguments:
1.424     albertel 5907:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5908:    $scanline    - the scanline that caused the error
                   5909:    $errormesage - the error message
                   5910:    $errorcode   - a numeric code for the error
                   5911: 
                   5912:  Side Effects:
1.424     albertel 5913:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5914: 
                   5915: =cut
                   5916: 
1.82      albertel 5917: sub scantron_add_delay {
1.140     albertel 5918:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5919:     push(@$delayqueue,
                   5920: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5921: 	  'ecode' => $errorcode }
                   5922: 	 );
1.82      albertel 5923: }
                   5924: 
1.423     albertel 5925: =pod
                   5926: 
                   5927: =item scantron_find_student
                   5928: 
1.424     albertel 5929:    Finds the username for the current scanline
                   5930: 
                   5931:   Arguments:
                   5932:    $scantron_record - hash result from scantron_parse_scanline
                   5933:    $scan_data       - hash of correction information 
                   5934:                       (see &scantron_getfile() form more information)
                   5935:    $idmap           - hash from &username_to_idmap()
                   5936:    $line            - number of current scanline
                   5937:  
                   5938:   Returns:
                   5939:    Either 'username:domain' or undef if unknown
                   5940: 
1.423     albertel 5941: =cut
                   5942: 
1.82      albertel 5943: sub scantron_find_student {
1.157     albertel 5944:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5945:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5946:     if ($scanID =~ /^\s*$/) {
                   5947:  	return &scan_data($scan_data,"$line.user");
                   5948:     }
1.83      albertel 5949:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5950:  	if (lc($id) eq lc($scanID)) {
                   5951:  	    return $$idmap{$id};
                   5952:  	}
1.83      albertel 5953:     }
                   5954:     return undef;
                   5955: }
                   5956: 
1.423     albertel 5957: =pod
                   5958: 
                   5959: =item scantron_filter
                   5960: 
1.424     albertel 5961:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5962:    hidden resources was selected
                   5963: 
1.423     albertel 5964: =cut
                   5965: 
1.83      albertel 5966: sub scantron_filter {
                   5967:     my ($curres)=@_;
1.331     albertel 5968: 
                   5969:     if (ref($curres) && $curres->is_problem()) {
                   5970: 	# if the user has asked to not have either hidden
                   5971: 	# or 'randomout' controlled resources to be graded
                   5972: 	# don't include them
                   5973: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5974: 	    && $curres->randomout) {
                   5975: 	    return 0;
                   5976: 	}
1.83      albertel 5977: 	return 1;
                   5978:     }
                   5979:     return 0;
1.82      albertel 5980: }
                   5981: 
1.423     albertel 5982: =pod
                   5983: 
                   5984: =item scantron_process_corrections
                   5985: 
1.424     albertel 5986:    Gets correction information out of submitted form data and corrects
                   5987:    the scanline
                   5988: 
1.423     albertel 5989: =cut
                   5990: 
1.157     albertel 5991: sub scantron_process_corrections {
                   5992:     my ($r) = @_;
1.257     albertel 5993:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5994:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5995:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5996:     my $which=$env{'form.scantron_line'};
1.200     albertel 5997:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5998:     my ($skip,$err,$errmsg);
1.257     albertel 5999:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 6000: 	$skip=1;
1.257     albertel 6001:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   6002: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   6003: 	    $env{'form.scantron_domain'};
1.157     albertel 6004: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   6005: 	($line,$err,$errmsg)=
                   6006: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   6007: 				     'ID',{'newid'=>$newid,
1.257     albertel 6008: 				    'username'=>$env{'form.scantron_username'},
                   6009: 				    'domain'=>$env{'form.scantron_domain'}});
                   6010:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   6011: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 6012: 	my $newCODE;
1.192     albertel 6013: 	my %args;
1.190     albertel 6014: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 6015: 	    $newCODE='use_unfound';
1.190     albertel 6016: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 6017: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 6018: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 6019: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 6020: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 6021: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 6022: 	}
1.257     albertel 6023: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 6024: 	    $args{'CODE_ignore_dup'}=1;
                   6025: 	}
                   6026: 	$args{'CODE'}=$newCODE;
1.186     albertel 6027: 	($line,$err,$errmsg)=
                   6028: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 6029: 				     'CODE',\%args);
1.257     albertel 6030:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   6031: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 6032: 	    ($line,$err,$errmsg)=
                   6033: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   6034: 					 $which,'answer',
                   6035: 					 { 'question'=>$question,
1.503     raeburn  6036: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   6037:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 6038: 	    if ($err) { last; }
                   6039: 	}
                   6040:     }
                   6041:     if ($err) {
1.398     albertel 6042: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 6043:     } else {
1.200     albertel 6044: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 6045: 	&scantron_putfile($scanlines,$scan_data);
                   6046:     }
                   6047: }
                   6048: 
1.423     albertel 6049: =pod
                   6050: 
                   6051: =item reset_skipping_status
                   6052: 
1.424     albertel 6053:    Forgets the current set of remember skipped scanlines (and thus
                   6054:    reverts back to considering all lines in the
                   6055:    scantron_skipped_<filename> file)
                   6056: 
1.423     albertel 6057: =cut
                   6058: 
1.200     albertel 6059: sub reset_skipping_status {
                   6060:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6061:     &scan_data($scan_data,'remember_skipping',undef,1);
                   6062:     &scantron_putfile(undef,$scan_data);
                   6063: }
                   6064: 
1.423     albertel 6065: =pod
                   6066: 
                   6067: =item start_skipping
                   6068: 
1.424     albertel 6069:    Marks a scanline to be skipped. 
                   6070: 
1.423     albertel 6071: =cut
                   6072: 
1.376     albertel 6073: sub start_skipping {
1.200     albertel 6074:     my ($scan_data,$i)=@_;
                   6075:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6076:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   6077: 	$remembered{$i}=2;
                   6078:     } else {
                   6079: 	$remembered{$i}=1;
                   6080:     }
1.200     albertel 6081:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   6082: }
                   6083: 
1.423     albertel 6084: =pod
                   6085: 
                   6086: =item should_be_skipped
                   6087: 
1.424     albertel 6088:    Checks whether a scanline should be skipped.
                   6089: 
1.423     albertel 6090: =cut
                   6091: 
1.200     albertel 6092: sub should_be_skipped {
1.376     albertel 6093:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 6094:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 6095: 	# not redoing old skips
1.376     albertel 6096: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 6097: 	return 0;
                   6098:     }
                   6099:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 6100: 
                   6101:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   6102: 	return 0;
                   6103:     }
1.200     albertel 6104:     return 1;
                   6105: }
                   6106: 
1.423     albertel 6107: =pod
                   6108: 
                   6109: =item remember_current_skipped
                   6110: 
1.424     albertel 6111:    Discovers what scanlines are in the scantron_skipped_<filename>
                   6112:    file and remembers them into scan_data for later use.
                   6113: 
1.423     albertel 6114: =cut
                   6115: 
1.200     albertel 6116: sub remember_current_skipped {
                   6117:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6118:     my %to_remember;
                   6119:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6120: 	if ($scanlines->{'skipped'}[$i]) {
                   6121: 	    $to_remember{$i}=1;
                   6122: 	}
                   6123:     }
1.376     albertel 6124: 
1.200     albertel 6125:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6126:     &scantron_putfile(undef,$scan_data);
                   6127: }
                   6128: 
1.423     albertel 6129: =pod
                   6130: 
                   6131: =item check_for_error
                   6132: 
1.424     albertel 6133:     Checks if there was an error when attempting to remove a specific
                   6134:     scantron_.. bubble sheet data file. Prints out an error if
                   6135:     something went wrong.
                   6136: 
1.423     albertel 6137: =cut
                   6138: 
1.200     albertel 6139: sub check_for_error {
                   6140:     my ($r,$result)=@_;
                   6141:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6142: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6143:     }
                   6144: }
1.157     albertel 6145: 
1.423     albertel 6146: =pod
                   6147: 
                   6148: =item scantron_warning_screen
                   6149: 
1.424     albertel 6150:    Interstitial screen to make sure the operator has selected the
                   6151:    correct options before we start the validation phase.
                   6152: 
1.423     albertel 6153: =cut
                   6154: 
1.203     albertel 6155: sub scantron_warning_screen {
                   6156:     my ($button_text)=@_;
1.257     albertel 6157:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6158:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6159:     my $CODElist;
1.284     albertel 6160:     if ($scantron_config{'CODElocation'} &&
                   6161: 	$scantron_config{'CODEstart'} &&
                   6162: 	$scantron_config{'CODElength'}) {
                   6163: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6164: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6165: 	$CODElist=
1.492     albertel 6166: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6167: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6168:     }
1.492     albertel 6169:     return ('
1.203     albertel 6170: <p>
1.492     albertel 6171: <span class="LC_warning">
                   6172: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6173: </p>
                   6174: <table>
1.492     albertel 6175: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6176: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6177: '.$CODElist.'
1.203     albertel 6178: </table>
                   6179: <br />
1.492     albertel 6180: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6181: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6182: 
                   6183: <br />
1.492     albertel 6184: ');
1.203     albertel 6185: }
                   6186: 
1.423     albertel 6187: =pod
                   6188: 
                   6189: =item scantron_do_warning
                   6190: 
1.424     albertel 6191:    Check if the operator has picked something for all required
                   6192:    fields. Error out if something is missing.
                   6193: 
1.423     albertel 6194: =cut
                   6195: 
1.203     albertel 6196: sub scantron_do_warning {
                   6197:     my ($r)=@_;
1.324     albertel 6198:     my ($symb)=&get_symb($r);
1.203     albertel 6199:     if (!$symb) {return '';}
1.324     albertel 6200:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6201:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6202:     if ( $env{'form.selectpage'} eq '' ||
                   6203: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6204: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6205: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6206: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6207: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6208: 	} 
1.257     albertel 6209: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6210: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a file that contains the student\'s response data.').'</span></p>');
1.237     albertel 6211: 	} 
1.257     albertel 6212: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6213: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a the format of the student\'s response data.').'</span></p>');
1.237     albertel 6214: 	} 
                   6215:     } else {
1.265     www      6216: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6217: 	$r->print('
                   6218: '.$warning.'
                   6219: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6220: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6221: ');
1.237     albertel 6222:     }
1.352     albertel 6223:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6224:     return '';
                   6225: }
                   6226: 
1.423     albertel 6227: =pod
                   6228: 
                   6229: =item scantron_form_start
                   6230: 
1.424     albertel 6231:     html hidden input for remembering all selected grading options
                   6232: 
1.423     albertel 6233: =cut
                   6234: 
1.203     albertel 6235: sub scantron_form_start {
                   6236:     my ($max_bubble)=@_;
                   6237:     my $result= <<SCANTRONFORM;
                   6238: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6239:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6240:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6241:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6242:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6243:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6244:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6245:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6246:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6247:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6248: SCANTRONFORM
1.447     foxr     6249: 
                   6250:   my $line = 0;
                   6251:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6252:        my $chunk =
                   6253: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6254:        $chunk .=
                   6255: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6256:        $chunk .= 
                   6257:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6258:        $chunk .=
                   6259:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6260:        $result .= $chunk;
                   6261:        $line++;
                   6262:    }
1.203     albertel 6263:     return $result;
                   6264: }
                   6265: 
1.423     albertel 6266: =pod
                   6267: 
                   6268: =item scantron_validate_file
                   6269: 
1.424     albertel 6270:     Dispatch routine for doing validation of a bubble sheet data file.
                   6271: 
                   6272:     Also processes any necessary information resets that need to
                   6273:     occur before validation begins (ignore previous corrections,
                   6274:     restarting the skipped records processing)
                   6275: 
1.423     albertel 6276: =cut
                   6277: 
1.157     albertel 6278: sub scantron_validate_file {
                   6279:     my ($r) = @_;
1.324     albertel 6280:     my ($symb)=&get_symb($r);
1.157     albertel 6281:     if (!$symb) {return '';}
1.324     albertel 6282:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6283:     
                   6284:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6285:     # them when doing the corrections reset
1.257     albertel 6286:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6287: 	&reset_skipping_status();
                   6288:     }
1.257     albertel 6289:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6290: 	&remember_current_skipped();
1.257     albertel 6291: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6292:     }
                   6293: 
1.257     albertel 6294:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6295: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6296: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6297: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6298: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6299:     }
1.200     albertel 6300: 
1.257     albertel 6301:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6302: 	&scantron_process_corrections($r);
                   6303:     }
1.503     raeburn  6304:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6305:     #get the student pick code ready
                   6306:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6307:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6308:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6309:     $r->print($result);
                   6310:     
1.334     albertel 6311:     my @validate_phases=( 'sequence',
                   6312: 			  'ID',
1.157     albertel 6313: 			  'CODE',
                   6314: 			  'doublebubble',
                   6315: 			  'missingbubbles');
1.257     albertel 6316:     if (!$env{'form.validatepass'}) {
                   6317: 	$env{'form.validatepass'} = 0;
1.157     albertel 6318:     }
1.257     albertel 6319:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6320: 
1.448     foxr     6321: 
1.157     albertel 6322:     my $stop=0;
                   6323:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6324: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6325: 	$r->rflush();
                   6326: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6327: 	{
                   6328: 	    no strict 'refs';
                   6329: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6330: 	}
                   6331:     }
                   6332:     if (!$stop) {
1.203     albertel 6333: 	my $warning=&scantron_warning_screen('Start Grading');
1.512     www      6334: 	$r->print(&mt('Validation process complete.').'<br />
1.492     albertel 6335: '.$warning.'
                   6336: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6337: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6338: ');
1.203     albertel 6339: 
1.157     albertel 6340:     } else {
                   6341: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6342: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6343:     }
                   6344:     if ($stop) {
1.334     albertel 6345: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6346: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6347: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6348: 
1.492     albertel 6349: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6350: 	} else {
1.503     raeburn  6351:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
                   6352: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
                   6353:             } else {
                   6354:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6355:             }
1.492     albertel 6356: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6357: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6358: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6359: 	}
1.157     albertel 6360:     }
1.352     albertel 6361:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6362:     return '';
                   6363: }
                   6364: 
1.423     albertel 6365: 
                   6366: =pod
                   6367: 
                   6368: =item scantron_remove_file
                   6369: 
1.424     albertel 6370:    Removes the requested bubble sheet data file, makes sure that
                   6371:    scantron_original_<filename> is never removed
                   6372: 
                   6373: 
1.423     albertel 6374: =cut
                   6375: 
1.200     albertel 6376: sub scantron_remove_file {
1.192     albertel 6377:     my ($which)=@_;
1.257     albertel 6378:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6379:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6380:     my $file='scantron_';
1.200     albertel 6381:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6382: 	$file.=$which.'_';
1.192     albertel 6383:     } else {
                   6384: 	return 'refused';
                   6385:     }
1.257     albertel 6386:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6387:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6388: }
                   6389: 
1.423     albertel 6390: 
                   6391: =pod
                   6392: 
                   6393: =item scantron_remove_scan_data
                   6394: 
1.424     albertel 6395:    Removes all scan_data correction for the requested bubble sheet
                   6396:    data file.  (In the case that both the are doing skipped records we need
                   6397:    to remember the old skipped lines for the time being so that element
                   6398:    persists for a while.)
                   6399: 
1.423     albertel 6400: =cut
                   6401: 
1.200     albertel 6402: sub scantron_remove_scan_data {
1.257     albertel 6403:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6404:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6405:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6406:     my @todelete;
1.257     albertel 6407:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6408:     foreach my $key (@keys) {
                   6409: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6410: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6411: 		$key=~/remember_skipping/) {
                   6412: 		next;
                   6413: 	    }
1.192     albertel 6414: 	    push(@todelete,$key);
                   6415: 	}
                   6416:     }
1.200     albertel 6417:     my $result;
1.192     albertel 6418:     if (@todelete) {
1.491     albertel 6419: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6420: 				       \@todelete,$cdom,$cname);
                   6421:     } else {
                   6422: 	$result = 'ok';
1.192     albertel 6423:     }
                   6424:     return $result;
                   6425: }
                   6426: 
1.423     albertel 6427: 
                   6428: =pod
                   6429: 
                   6430: =item scantron_getfile
                   6431: 
1.424     albertel 6432:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6433:     the scan_data hash
                   6434:   
                   6435:   Arguments:
                   6436:     None
                   6437: 
                   6438:   Returns:
                   6439:     2 hash references
                   6440: 
                   6441:      - first one has 
                   6442:          orig      -
                   6443:          corrected -
                   6444:          skipped   -  each of which points to an array ref of the specified
                   6445:                       file broken up into individual lines
                   6446:          count     - number of scanlines
                   6447:  
                   6448:      - second is the scan_data hash possible keys are
1.425     albertel 6449:        ($number refers to scanline numbered $number and thus the key affects
                   6450:         only that scanline
                   6451:         $bubline refers to the specific bubble line element and the aspects
                   6452:         refers to that specific bubble line element)
                   6453: 
                   6454:        $number.user - username:domain to use
                   6455:        $number.CODE_ignore_dup 
                   6456:                     - ignore the duplicate CODE error 
                   6457:        $number.useCODE
                   6458:                     - use the CODE in the scanline as is
                   6459:        $number.no_bubble.$bubline
                   6460:                     - it is valid that there is no bubbled in bubble
                   6461:                       at $number $bubline
                   6462:        remember_skipping
                   6463:                     - a frozen hash containing keys of $number and values
                   6464:                       of either 
                   6465:                         1 - we are on a 'do skipped records pass' and plan
                   6466:                             on processing this line
                   6467:                         2 - we are on a 'do skipped records pass' and this
                   6468:                             scanline has been marked to skip yet again
1.424     albertel 6469: 
1.423     albertel 6470: =cut
                   6471: 
1.157     albertel 6472: sub scantron_getfile {
1.200     albertel 6473:     #FIXME really would prefer a scantron directory
1.257     albertel 6474:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6475:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6476:     my $lines;
                   6477:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6478: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6479:     my %scanlines;
                   6480:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6481:     my $temp=$scanlines{'orig'};
                   6482:     $scanlines{'count'}=$#$temp;
                   6483: 
                   6484:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6485: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6486:     if ($lines eq '-1') {
                   6487: 	$scanlines{'corrected'}=[];
                   6488:     } else {
                   6489: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6490:     }
                   6491:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6492: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6493:     if ($lines eq '-1') {
                   6494: 	$scanlines{'skipped'}=[];
                   6495:     } else {
                   6496: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6497:     }
1.175     albertel 6498:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6499:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6500:     my %scan_data = @tmp;
                   6501:     return (\%scanlines,\%scan_data);
                   6502: }
                   6503: 
1.423     albertel 6504: =pod
                   6505: 
                   6506: =item lonnet_putfile
                   6507: 
1.424     albertel 6508:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6509: 
                   6510:  Arguments:
                   6511:    $contents - data to store
                   6512:    $filename - filename to store $contents into
                   6513: 
                   6514:  Returns:
                   6515:    result value from &Apache::lonnet::finishuserfileupload
                   6516: 
1.423     albertel 6517: =cut
                   6518: 
1.157     albertel 6519: sub lonnet_putfile {
                   6520:     my ($contents,$filename)=@_;
1.257     albertel 6521:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6522:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6523:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6524:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6525: 
                   6526: }
                   6527: 
1.423     albertel 6528: =pod
                   6529: 
                   6530: =item scantron_putfile
                   6531: 
1.424     albertel 6532:     Stores the current version of the bubble sheet data files, and the
                   6533:     scan_data hash. (Does not modify the original version only the
                   6534:     corrected and skipped versions.
                   6535: 
                   6536:  Arguments:
                   6537:     $scanlines - hash ref that looks like the first return value from
                   6538:                  &scantron_getfile()
                   6539:     $scan_data - hash ref that looks like the second return value from
                   6540:                  &scantron_getfile()
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.157     albertel 6544: sub scantron_putfile {
                   6545:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6546:     #FIXME really would prefer a scantron directory
1.257     albertel 6547:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6548:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6549:     if ($scanlines) {
                   6550: 	my $prefix='scantron_';
1.157     albertel 6551: # no need to update orig, shouldn't change
                   6552: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6553: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6554: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6555: 			$prefix.'corrected_'.
1.257     albertel 6556: 			$env{'form.scantron_selectfile'});
1.200     albertel 6557: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6558: 			$prefix.'skipped_'.
1.257     albertel 6559: 			$env{'form.scantron_selectfile'});
1.200     albertel 6560:     }
1.175     albertel 6561:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6562: }
                   6563: 
1.423     albertel 6564: =pod
                   6565: 
                   6566: =item scantron_get_line
                   6567: 
1.424     albertel 6568:    Returns the correct version of the scanline
                   6569: 
                   6570:  Arguments:
                   6571:     $scanlines - hash ref that looks like the first return value from
                   6572:                  &scantron_getfile()
                   6573:     $scan_data - hash ref that looks like the second return value from
                   6574:                  &scantron_getfile()
                   6575:     $i         - number of the requested line (starts at 0)
                   6576: 
                   6577:  Returns:
                   6578:    A scanline, (either the original or the corrected one if it
                   6579:    exists), or undef if the requested scanline should be
                   6580:    skipped. (Either because it's an skipped scanline, or it's an
                   6581:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6582:    pass.
                   6583: 
1.423     albertel 6584: =cut
                   6585: 
1.157     albertel 6586: sub scantron_get_line {
1.200     albertel 6587:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6588:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6589:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6590:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6591:     return $scanlines->{'orig'}[$i]; 
                   6592: }
                   6593: 
1.423     albertel 6594: =pod
                   6595: 
                   6596: =item scantron_todo_count
                   6597: 
1.424     albertel 6598:     Counts the number of scanlines that need processing.
                   6599: 
                   6600:  Arguments:
                   6601:     $scanlines - hash ref that looks like the first return value from
                   6602:                  &scantron_getfile()
                   6603:     $scan_data - hash ref that looks like the second return value from
                   6604:                  &scantron_getfile()
                   6605: 
                   6606:  Returns:
                   6607:     $count - number of scanlines to process
                   6608: 
1.423     albertel 6609: =cut
                   6610: 
1.200     albertel 6611: sub get_todo_count {
                   6612:     my ($scanlines,$scan_data)=@_;
                   6613:     my $count=0;
                   6614:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6615: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6616: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6617: 	$count++;
                   6618:     }
                   6619:     return $count;
                   6620: }
                   6621: 
1.423     albertel 6622: =pod
                   6623: 
                   6624: =item scantron_put_line
                   6625: 
1.424     albertel 6626:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6627:     data file.
                   6628: 
                   6629:  Arguments:
                   6630:     $scanlines - hash ref that looks like the first return value from
                   6631:                  &scantron_getfile()
                   6632:     $scan_data - hash ref that looks like the second return value from
                   6633:                  &scantron_getfile()
                   6634:     $i         - line number to update
                   6635:     $newline   - contents of the updated scanline
                   6636:     $skip      - if true make the line for skipping and update the
                   6637:                  'skipped' file
                   6638: 
1.423     albertel 6639: =cut
                   6640: 
1.157     albertel 6641: sub scantron_put_line {
1.200     albertel 6642:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6643:     if ($skip) {
                   6644: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6645: 	&start_skipping($scan_data,$i);
1.157     albertel 6646: 	return;
                   6647:     }
                   6648:     $scanlines->{'corrected'}[$i]=$newline;
                   6649: }
                   6650: 
1.423     albertel 6651: =pod
                   6652: 
                   6653: =item scantron_clear_skip
                   6654: 
1.424     albertel 6655:    Remove a line from the 'skipped' file
                   6656: 
                   6657:  Arguments:
                   6658:     $scanlines - hash ref that looks like the first return value from
                   6659:                  &scantron_getfile()
                   6660:     $scan_data - hash ref that looks like the second return value from
                   6661:                  &scantron_getfile()
                   6662:     $i         - line number to update
                   6663: 
1.423     albertel 6664: =cut
                   6665: 
1.376     albertel 6666: sub scantron_clear_skip {
                   6667:     my ($scanlines,$scan_data,$i)=@_;
                   6668:     if (exists($scanlines->{'skipped'}[$i])) {
                   6669: 	undef($scanlines->{'skipped'}[$i]);
                   6670: 	return 1;
                   6671:     }
                   6672:     return 0;
                   6673: }
                   6674: 
1.423     albertel 6675: =pod
                   6676: 
                   6677: =item scantron_filter_not_exam
                   6678: 
1.424     albertel 6679:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6680:    filter out resources that are not marked as 'exam' mode
                   6681: 
1.423     albertel 6682: =cut
                   6683: 
1.334     albertel 6684: sub scantron_filter_not_exam {
                   6685:     my ($curres)=@_;
                   6686:     
                   6687:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6688: 	# if the user has asked to not have either hidden
                   6689: 	# or 'randomout' controlled resources to be graded
                   6690: 	# don't include them
                   6691: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6692: 	    && $curres->randomout) {
                   6693: 	    return 0;
                   6694: 	}
                   6695: 	return 1;
                   6696:     }
                   6697:     return 0;
                   6698: }
                   6699: 
1.423     albertel 6700: =pod
                   6701: 
                   6702: =item scantron_validate_sequence
                   6703: 
1.424     albertel 6704:     Validates the selected sequence, checking for resource that are
                   6705:     not set to exam mode.
                   6706: 
1.423     albertel 6707: =cut
                   6708: 
1.334     albertel 6709: sub scantron_validate_sequence {
                   6710:     my ($r,$currentphase) = @_;
                   6711: 
                   6712:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6713:     my (undef,undef,$sequence)=
                   6714: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6715: 
                   6716:     my $map=$navmap->getResourceByUrl($sequence);
                   6717: 
                   6718:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6719:                                     value="ignore" />');
                   6720:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6721: 	my @resources=
                   6722: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6723: 	if (@resources) {
1.357     banghart 6724: 	    $r->print("<p>".&mt('Some resources in the sequence currently are not set to exam mode. Grading these resources currently may not work correctly.')."</p>");
1.334     albertel 6725: 	    return (1,$currentphase);
                   6726: 	}
                   6727:     }
                   6728: 
                   6729:     return (0,$currentphase+1);
                   6730: }
                   6731: 
1.423     albertel 6732: 
                   6733: 
1.157     albertel 6734: sub scantron_validate_ID {
                   6735:     my ($r,$currentphase) = @_;
                   6736:     
                   6737:     #get student info
                   6738:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6739:     my %idmap=&username_to_idmap($classlist);
                   6740: 
                   6741:     #get scantron line setup
1.257     albertel 6742:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6743:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6744:     
                   6745:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6746: 
                   6747:     my %found=('ids'=>{},'usernames'=>{});
                   6748:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6749: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6750: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6751: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6752: 						 $scan_data);
                   6753: 	my $id=$$scan_record{'scantron.ID'};
                   6754: 	my $found;
                   6755: 	foreach my $checkid (keys(%idmap)) {
                   6756: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6757: 	}
                   6758: 	if ($found) {
                   6759: 	    my $username=$idmap{$found};
                   6760: 	    if ($found{'ids'}{$found}) {
                   6761: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6762: 					 $line,'duplicateID',$found);
1.194     albertel 6763: 		return(1,$currentphase);
1.157     albertel 6764: 	    } elsif ($found{'usernames'}{$username}) {
                   6765: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6766: 					 $line,'duplicateID',$username);
1.194     albertel 6767: 		return(1,$currentphase);
1.157     albertel 6768: 	    }
1.186     albertel 6769: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6770: 	    $found{'ids'}{$found}++;
                   6771: 	    $found{'usernames'}{$username}++;
                   6772: 	} else {
                   6773: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6774: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6775: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6776: 		    &scantron_get_correction($r,$i,$scan_record,
                   6777: 					     \%scantron_config,
                   6778: 					     $line,'duplicateID',$username);
1.194     albertel 6779: 		    return(1,$currentphase);
1.157     albertel 6780: 		} elsif (!defined($username)) {
                   6781: 		    &scantron_get_correction($r,$i,$scan_record,
                   6782: 					     \%scantron_config,
                   6783: 					     $line,'incorrectID');
1.194     albertel 6784: 		    return(1,$currentphase);
1.157     albertel 6785: 		}
                   6786: 		$found{'usernames'}{$username}++;
                   6787: 	    } else {
                   6788: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6789: 					 $line,'incorrectID');
1.194     albertel 6790: 		return(1,$currentphase);
1.157     albertel 6791: 	    }
                   6792: 	}
                   6793:     }
                   6794: 
                   6795:     return (0,$currentphase+1);
                   6796: }
                   6797: 
1.423     albertel 6798: 
1.157     albertel 6799: sub scantron_get_correction {
                   6800:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6801: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6802: #to show both the current line and the previous one and allow skipping
                   6803: #the previous one or the current one
                   6804: 
1.333     albertel 6805:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6806: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6807: 			    " for PaperID <tt>[_1]</tt>",
                   6808: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6809:     } else {
1.492     albertel 6810: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6811: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6812: 			    $i,$line)."</p> \n");
                   6813:     }
                   6814:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6815: 			  "The name on the paper is [_2],[_3]",
                   6816: 			  $$scan_record{'scantron.ID'},
                   6817: 			  $$scan_record{'scantron.LastName'},
                   6818: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6819: 
1.157     albertel 6820:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6821:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6822:                            # Array populated for doublebubble or
                   6823:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6824:                            # to validate radio button checking   
                   6825: 
1.157     albertel 6826:     if ($error =~ /ID$/) {
1.186     albertel 6827: 	if ($error eq 'incorrectID') {
1.492     albertel 6828: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6829: 		      "</p>\n");
1.157     albertel 6830: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6831: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6832: 	}
1.242     albertel 6833: 	$r->print($message);
1.492     albertel 6834: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6835: 	$r->print("\n<ul><li> ");
                   6836: 	#FIXME it would be nice if this sent back the user ID and
                   6837: 	#could do partial userID matches
                   6838: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6839: 				       'scantron_username','scantron_domain'));
                   6840: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6841: 	$r->print("\n@".
1.257     albertel 6842: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6843: 
                   6844: 	$r->print('</li>');
1.186     albertel 6845:     } elsif ($error =~ /CODE$/) {
                   6846: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6847: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6848: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6849: 	    $r->print("<p>".&mt("The encoded CODE has also been used by a previous paper [_1], and CODEs are supposed to be unique.",join(', ',@{$arg}))."</p>\n");
1.186     albertel 6850: 	}
1.492     albertel 6851: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6852: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6853: 	$r->print($message);
1.492     albertel 6854: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6855: 	$r->print("\n<br /> ");
1.194     albertel 6856: 	my $i=0;
1.273     albertel 6857: 	if ($error eq 'incorrectCODE' 
                   6858: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6859: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6860: 	    if ($closest > 0) {
                   6861: 		foreach my $testcode (@{$closest}) {
                   6862: 		    my $checked='';
1.401     albertel 6863: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6864: 		    $r->print("
                   6865:    <label>
                   6866:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6867:        ".&mt("Use the similar CODE [_1] instead.",
                   6868: 	    "<b><tt>".$testcode."</tt></b>")."
                   6869:     </label>
                   6870:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6871: 		    $r->print("\n<br />");
                   6872: 		    $i++;
                   6873: 		}
1.194     albertel 6874: 	    }
                   6875: 	}
1.273     albertel 6876: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6877: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6878: 	    $r->print("
                   6879:     <label>
                   6880:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6881:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6882: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6883:     </label>");
1.273     albertel 6884: 	    $r->print("\n<br />");
                   6885: 	}
1.194     albertel 6886: 
1.188     albertel 6887: 	$r->print(<<ENDSCRIPT);
                   6888: <script type="text/javascript">
                   6889: function change_radio(field) {
1.190     albertel 6890:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6891:     var i;
                   6892:     for (i=0;i<slct.length;i++) {
                   6893:         if (slct[i].value==field) { slct[i].checked=true; }
                   6894:     }
                   6895: }
                   6896: </script>
                   6897: ENDSCRIPT
1.187     albertel 6898: 	my $href="/adm/pickcode?".
1.359     www      6899: 	   "form=".&escape("scantronupload").
                   6900: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6901: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6902: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6903: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6904: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6905: 	    $r->print("
                   6906:     <label>
                   6907:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6908:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6909: 	     "<a target='_blank' href='$href'>","</a>")."
                   6910:     </label> 
                   6911:     ".&mt("Selected CODE is [_1]","<input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />"));
1.332     albertel 6912: 	    $r->print("\n<br />");
                   6913: 	}
1.492     albertel 6914: 	$r->print("
                   6915:     <label>
                   6916:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6917:        ".&mt("Use [_1] as the CODE.",
                   6918: 	     "</label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" />"));
1.187     albertel 6919: 	$r->print("\n<br /><br />");
1.157     albertel 6920:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6921: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6922: 
                   6923: 	# The form field scantron_questions is acutally a list of line numbers.
                   6924: 	# represented by this form so:
                   6925: 
                   6926: 	my $line_list = &questions_to_line_list($arg);
                   6927: 
1.157     albertel 6928: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6929: 		  $line_list.'" />');
1.242     albertel 6930: 	$r->print($message);
1.492     albertel 6931: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6932: 	foreach my $question (@{$arg}) {
1.503     raeburn  6933: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6934:                                                    $scan_record, $error);
1.524     raeburn  6935:             push(@lines_to_correct,@linenums);
1.157     albertel 6936: 	}
1.503     raeburn  6937:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6938:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6939: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6940: 	$r->print($message);
1.492     albertel 6941: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6942: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6943: 
1.503     raeburn  6944: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6945: 	# a list of question numbers. Therefore:
                   6946: 	#
                   6947: 	
                   6948: 	my $line_list = &questions_to_line_list($arg);
                   6949: 
1.157     albertel 6950: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6951: 		  $line_list.'" />');
1.157     albertel 6952: 	foreach my $question (@{$arg}) {
1.503     raeburn  6953: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6954:                                                    $scan_record, $error);
1.524     raeburn  6955:             push(@lines_to_correct,@linenums);
1.157     albertel 6956: 	}
1.503     raeburn  6957:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6958:     } else {
                   6959: 	$r->print("\n<ul>");
                   6960:     }
                   6961:     $r->print("\n</li></ul>");
1.497     foxr     6962: }
                   6963: 
1.503     raeburn  6964: sub verify_bubbles_checked {
                   6965:     my (@ansnums) = @_;
                   6966:     my $ansnumstr = join('","',@ansnums);
                   6967:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6968:     my $output = (<<ENDSCRIPT);
                   6969: <script type="text/javascript">
                   6970: function verify_bubble_radio(form) {
                   6971:     var ansnumArray = new Array ("$ansnumstr");
                   6972:     var need_bubble_count = 0;
                   6973:     for (var i=0; i<ansnumArray.length; i++) {
                   6974:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6975:             var bubble_picked = 0; 
                   6976:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6977:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6978:                     bubble_picked = 1;
                   6979:                 }
                   6980:             }
                   6981:             if (bubble_picked == 0) {
                   6982:                 need_bubble_count ++;
                   6983:             }
                   6984:         }
                   6985:     }
                   6986:     if (need_bubble_count) {
                   6987:         alert("$warning");
                   6988:         return;
                   6989:     }
                   6990:     form.submit(); 
                   6991: }
                   6992: </script>
                   6993: ENDSCRIPT
                   6994:     return $output;
                   6995: }
                   6996: 
1.497     foxr     6997: =pod
                   6998: 
                   6999: =item  questions_to_line_list
1.157     albertel 7000: 
1.497     foxr     7001: Converts a list of questions into a string of comma separated
                   7002: line numbers in the answer sheet used by the questions.  This is
                   7003: used to fill in the scantron_questions form field.
                   7004: 
                   7005:   Arguments:
                   7006:      questions    - Reference to an array of questions.
                   7007: 
                   7008: =cut
                   7009: 
                   7010: 
                   7011: sub questions_to_line_list {
                   7012:     my ($questions) = @_;
                   7013:     my @lines;
                   7014: 
1.503     raeburn  7015:     foreach my $item (@{$questions}) {
                   7016:         my $question = $item;
                   7017:         my ($first,$count,$last);
                   7018:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   7019:             $question = $1;
                   7020:             my $subquestion = $2;
                   7021:             $first = $first_bubble_line{$question-1} + 1;
                   7022:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7023:             my $subcount = 1;
                   7024:             while ($subcount<$subquestion) {
                   7025:                 $first += $subans[$subcount-1];
                   7026:                 $subcount ++;
                   7027:             }
                   7028:             $count = $subans[$subquestion-1];
                   7029:         } else {
                   7030: 	    $first   = $first_bubble_line{$question-1} + 1;
                   7031: 	    $count   = $bubble_lines_per_response{$question-1};
                   7032:         }
1.506     raeburn  7033:         $last = $first+$count-1;
1.503     raeburn  7034:         push(@lines, ($first..$last));
1.497     foxr     7035:     }
                   7036:     return join(',', @lines);
                   7037: }
                   7038: 
                   7039: =pod 
                   7040: 
                   7041: =item prompt_for_corrections
                   7042: 
                   7043: Prompts for a potentially multiline correction to the
                   7044: user's bubbling (factors out common code from scantron_get_correction
                   7045: for multi and missing bubble cases).
                   7046: 
                   7047:  Arguments:
                   7048:    $r           - Apache request object.
                   7049:    $question    - The question number to prompt for.
                   7050:    $scan_config - The scantron file configuration hash.
                   7051:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  7052:    $error       - Type of error
1.497     foxr     7053: 
                   7054:  Implicit inputs:
                   7055:    %bubble_lines_per_response   - Starting line numbers for each question.
                   7056:                                   Numbered from 0 (but question numbers are from
                   7057:                                   1.
                   7058:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  7059:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   7060:                                   type problems render as separate sub-questions, 
1.503     raeburn  7061:                                   in exam mode. This hash contains a 
                   7062:                                   comma-separated list of the lines per 
                   7063:                                   sub-question.
1.510     raeburn  7064:    %responsetype_per_response   - essayresponse, formularesponse,
                   7065:                                   stringresponse, imageresponse, reactionresponse,
                   7066:                                   and organicresponse type problem parts can have
1.503     raeburn  7067:                                   multiple lines per response if the weight
                   7068:                                   assigned exceeds 10.  In this case, only
                   7069:                                   one bubble per line is permitted, but more 
                   7070:                                   than one line might contain bubbles, e.g.
                   7071:                                   bubbling of: line 1 - J, line 2 - J, 
                   7072:                                   line 3 - B would assign 22 points.  
1.497     foxr     7073: 
                   7074: =cut
                   7075: 
                   7076: sub prompt_for_corrections {
1.503     raeburn  7077:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   7078:     my ($current_line,$lines);
                   7079:     my @linenums;
                   7080:     my $questionnum = $question;
                   7081:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7082:         $question = $1;
                   7083:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7084:         my $subquestion = $2;
                   7085:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7086:         my $subcount = 1;
                   7087:         while ($subcount<$subquestion) {
                   7088:             $current_line += $subans[$subcount-1];
                   7089:             $subcount ++;
                   7090:         }
                   7091:         $lines = $subans[$subquestion-1];
                   7092:     } else {
                   7093:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7094:         $lines        = $bubble_lines_per_response{$question-1};
                   7095:     }
1.497     foxr     7096:     if ($lines > 1) {
1.503     raeburn  7097:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7098:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7099:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7100:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7101:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7102:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7103:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7104:             $r->print(&mt("Although this particular question type requires handgrading, the instructions for this question in the exam directed students to leave [quant,_1,line] blank on their scantron sheets.",$lines).'<br /><br />'.&mt('A non-zero score can be assigned to the student during scantron grading by selecting a bubble in at least one line.').'<br />'.&mt('The score for this question will be a sum of the numeric values for the selected bubbles from each line, where A=1 point, B=2 points etc.').'<br />'.&mt("To assign a score of zero for this question, mark all lines as 'No bubble'.").'<br /><br />');
                   7105:         } else {
                   7106:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7107:         }
1.497     foxr     7108:     }
                   7109:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7110:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7111: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7112: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7113:         push(@linenums,$current_line);
1.497     foxr     7114: 	$current_line++;
                   7115:     }
                   7116:     if ($lines > 1) {
                   7117: 	$r->print("<hr /><br />");
                   7118:     }
1.503     raeburn  7119:     return @linenums;
1.157     albertel 7120: }
1.423     albertel 7121: 
                   7122: =pod
                   7123: 
                   7124: =item scantron_bubble_selector
                   7125:   
                   7126:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7127:    possibly showing the existing the selected bubbles if known
1.423     albertel 7128: 
                   7129:  Arguments:
                   7130:     $r           - Apache request object
                   7131:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7132:     $line        - Number of the line being displayed.
1.503     raeburn  7133:     $questionnum - Question number (may include subquestion)
                   7134:     $error       - Type of error.
1.497     foxr     7135:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7136: 
                   7137: =cut
                   7138: 
1.157     albertel 7139: sub scantron_bubble_selector {
1.503     raeburn  7140:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7141:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7142: 
                   7143:     my $scmode=$$scan_config{'Qon'};
                   7144:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7145: 
1.157     albertel 7146:     my @alphabet=('A'..'Z');
1.503     raeburn  7147:     $r->print(&Apache::loncommon::start_data_table().
                   7148:               &Apache::loncommon::start_data_table_row());
                   7149:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7150:     for (my $i=0;$i<$max+1;$i++) {
                   7151: 	$r->print("\n".'<td align="center">');
                   7152: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7153: 	else { $r->print('&nbsp;'); }
                   7154: 	$r->print('</td>');
                   7155:     }
1.503     raeburn  7156:     $r->print(&Apache::loncommon::end_data_table_row().
                   7157:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7158:     for (my $i=0;$i<$max;$i++) {
                   7159: 	$r->print("\n".
                   7160: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7161: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7162:     }
1.503     raeburn  7163:     my $nobub_checked = ' ';
                   7164:     if ($error eq 'missingbubble') {
                   7165:         $nobub_checked = ' checked = "checked" ';
                   7166:     }
                   7167:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7168: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7169:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7170:               $line.'" value="'.$questionnum.'" /></td>');
                   7171:     $r->print(&Apache::loncommon::end_data_table_row().
                   7172:               &Apache::loncommon::end_data_table());
1.157     albertel 7173: }
                   7174: 
1.423     albertel 7175: =pod
                   7176: 
                   7177: =item num_matches
                   7178: 
1.424     albertel 7179:    Counts the number of characters that are the same between the two arguments.
                   7180: 
                   7181:  Arguments:
                   7182:    $orig - CODE from the scanline
                   7183:    $code - CODE to match against
                   7184: 
                   7185:  Returns:
                   7186:    $count - integer count of the number of same characters between the
                   7187:             two arguments
                   7188: 
1.423     albertel 7189: =cut
                   7190: 
1.194     albertel 7191: sub num_matches {
                   7192:     my ($orig,$code) = @_;
                   7193:     my @code=split(//,$code);
                   7194:     my @orig=split(//,$orig);
                   7195:     my $same=0;
                   7196:     for (my $i=0;$i<scalar(@code);$i++) {
                   7197: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7198:     }
                   7199:     return $same;
                   7200: }
                   7201: 
1.423     albertel 7202: =pod
                   7203: 
                   7204: =item scantron_get_closely_matching_CODEs
                   7205: 
1.424     albertel 7206:    Cycles through all CODEs and finds the set that has the greatest
                   7207:    number of same characters as the provided CODE
                   7208: 
                   7209:  Arguments:
                   7210:    $allcodes - hash ref returned by &get_codes()
                   7211:    $CODE     - CODE from the current scanline
                   7212: 
                   7213:  Returns:
                   7214:    2 element list
                   7215:     - first elements is number of how closely matching the best fit is 
                   7216:       (5 means best set has 5 matching characters)
                   7217:     - second element is an arrary ref containing the set of valid CODEs
                   7218:       that best fit the passed in CODE
                   7219: 
1.423     albertel 7220: =cut
                   7221: 
1.194     albertel 7222: sub scantron_get_closely_matching_CODEs {
                   7223:     my ($allcodes,$CODE)=@_;
                   7224:     my @CODEs;
                   7225:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7226: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7227:     }
                   7228: 
                   7229:     return ($#CODEs,$CODEs[-1]);
                   7230: }
                   7231: 
1.423     albertel 7232: =pod
                   7233: 
                   7234: =item get_codes
                   7235: 
1.424     albertel 7236:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7237:    set of remembered CODEs.
                   7238: 
                   7239:  Arguments:
                   7240:   $old_name - name of the set of remembered CODEs
                   7241:   $cdom     - domain of the course
                   7242:   $cnum     - internal course name
                   7243: 
                   7244:  Returns:
                   7245:   %allcodes - keys are the valid CODEs, values are all 1
                   7246: 
1.423     albertel 7247: =cut
                   7248: 
1.194     albertel 7249: sub get_codes {
1.280     foxr     7250:     my ($old_name, $cdom, $cnum) = @_;
                   7251:     if (!$old_name) {
                   7252: 	$old_name=$env{'form.scantron_CODElist'};
                   7253:     }
                   7254:     if (!$cdom) {
                   7255: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7256:     }
                   7257:     if (!$cnum) {
                   7258: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7259:     }
1.278     albertel 7260:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7261: 				    $cdom,$cnum);
                   7262:     my %allcodes;
                   7263:     if ($result{"type\0$old_name"} eq 'number') {
                   7264: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7265:     } else {
                   7266: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7267:     }
1.194     albertel 7268:     return %allcodes;
                   7269: }
                   7270: 
1.423     albertel 7271: =pod
                   7272: 
                   7273: =item scantron_validate_CODE
                   7274: 
1.424     albertel 7275:    Validates all scanlines in the selected file to not have any
                   7276:    invalid or underspecified CODEs and that none of the codes are
                   7277:    duplicated if this was requested.
                   7278: 
1.423     albertel 7279: =cut
                   7280: 
1.157     albertel 7281: sub scantron_validate_CODE {
                   7282:     my ($r,$currentphase) = @_;
1.257     albertel 7283:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7284:     if ($scantron_config{'CODElocation'} &&
                   7285: 	$scantron_config{'CODEstart'} &&
                   7286: 	$scantron_config{'CODElength'}) {
1.257     albertel 7287: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7288: 	    &FIXME_blow_up()
                   7289: 	}
                   7290:     } else {
                   7291: 	return (0,$currentphase+1);
                   7292:     }
                   7293:     
                   7294:     my %usedCODEs;
                   7295: 
1.194     albertel 7296:     my %allcodes=&get_codes();
1.186     albertel 7297: 
1.447     foxr     7298:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7299: 
1.186     albertel 7300:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7301:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7302: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7303: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7304: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7305: 						 $scan_data);
                   7306: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7307: 	my $error=0;
1.224     albertel 7308: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7309: 	    &scantron_get_correction($r,$i,$scan_record,
                   7310: 				     \%scantron_config,
                   7311: 				     $line,'incorrectCODE',\%allcodes);
                   7312: 	    return(1,$currentphase);
                   7313: 	}
1.221     albertel 7314: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7315: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7316: 	    &scantron_get_correction($r,$i,$scan_record,
                   7317: 				     \%scantron_config,
1.194     albertel 7318: 				     $line,'incorrectCODE',\%allcodes);
                   7319: 	    return(1,$currentphase);
1.186     albertel 7320: 	}
1.214     albertel 7321: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7322: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7323: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7324: 	    &scantron_get_correction($r,$i,$scan_record,
                   7325: 				     \%scantron_config,
1.194     albertel 7326: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7327: 	    return(1,$currentphase);
1.186     albertel 7328: 	}
1.524     raeburn  7329: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7330:     }
1.157     albertel 7331:     return (0,$currentphase+1);
                   7332: }
                   7333: 
1.423     albertel 7334: =pod
                   7335: 
                   7336: =item scantron_validate_doublebubble
                   7337: 
1.424     albertel 7338:    Validates all scanlines in the selected file to not have any
                   7339:    bubble lines with multiple bubbles marked.
                   7340: 
1.423     albertel 7341: =cut
                   7342: 
1.157     albertel 7343: sub scantron_validate_doublebubble {
                   7344:     my ($r,$currentphase) = @_;
                   7345:     #get student info
                   7346:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7347:     my %idmap=&username_to_idmap($classlist);
                   7348: 
                   7349:     #get scantron line setup
1.257     albertel 7350:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7351:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7352:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7353: 
1.157     albertel 7354:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7355: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7356: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7357: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7358: 						 $scan_data);
                   7359: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7360: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7361: 				 'doublebubble',
                   7362: 				 $$scan_record{'scantron.doubleerror'});
                   7363:     	return (1,$currentphase);
                   7364:     }
                   7365:     return (0,$currentphase+1);
                   7366: }
                   7367: 
1.423     albertel 7368: 
1.503     raeburn  7369: sub scantron_get_maxbubble {
1.257     albertel 7370:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7371: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7372: 	&restore_bubble_lines();
1.257     albertel 7373: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7374:     }
1.330     albertel 7375: 
1.447     foxr     7376:     my (undef, undef, $sequence) =
1.257     albertel 7377: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7378: 
1.447     foxr     7379:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7380:     my $map=$navmap->getResourceByUrl($sequence);
                   7381:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7382: 
                   7383:     &Apache::lonxml::clear_problem_counter();
                   7384: 
1.435     foxr     7385:     my $uname       = $env{'form.student'};
                   7386:     my $udom        = $env{'form.userdom'};
                   7387:     my $cid         = $env{'request.course.id'};
                   7388:     my $total_lines = 0;
                   7389:     %bubble_lines_per_response = ();
1.447     foxr     7390:     %first_bubble_line         = ();
1.503     raeburn  7391:     %subdivided_bubble_lines   = ();
                   7392:     %responsetype_per_response = ();
1.447     foxr     7393:   
                   7394:     my $response_number = 0;
                   7395:     my $bubble_line     = 0;
1.191     albertel 7396:     foreach my $resource (@resources) {
1.515     raeburn  7397:         my $symb = $resource->symb();
1.523     raeburn  7398: 
                   7399:         my (@parts,@allparts,@possible_parts);
                   7400: 
1.510     raeburn  7401:         # Need to retrieve part IDs and response IDs because essayresponse,
                   7402:         # reactionresponse and organicresponse items are not included in 
                   7403:         # $analysis{'parts'} from lonnet::ssi.  
1.523     raeburn  7404:         if (ref($resource->parts()) eq 'ARRAY') {
1.503     raeburn  7405:             foreach my $part (@{$resource->parts()}) {
1.515     raeburn  7406:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
                   7407:                     my @resp_ids = $resource->responseIds($part);
                   7408:                     foreach my $id (@resp_ids) {
1.523     raeburn  7409:                         my $part_id = $part.'.'.$id;
                   7410:                         push(@possible_parts,$part_id);
1.515     raeburn  7411:                     }
1.503     raeburn  7412:                 }
                   7413:             }
                   7414:         }
1.435     foxr     7415: 
1.523     raeburn  7416:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
                   7417:                                         ('symb' => $symb,
                   7418:                                          'grade_target' => 'analyze',
                   7419:                                          'grade_courseid' => $cid,
                   7420:                                          'grade_domain' => $udom,
                   7421:                                          'grade_username' => $uname));
                   7422:         my (undef, $an) =
                   7423:             split(/_HASH_REF__/,$result, 2);
1.503     raeburn  7424: 
1.435     foxr     7425: 	my %analysis = &Apache::lonnet::str2hash($an);
                   7426: 
1.503     raeburn  7427:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.515     raeburn  7428:             foreach my $part (@{$analysis{'parts'}}) {
                   7429:                 my ($id,$respid) = split(/\./,$part);
                   7430:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7431:                     push(@parts,$part);
                   7432:                 }
                   7433:             }
1.503     raeburn  7434:         }
1.523     raeburn  7435:         # Add part_ids for any essayresponse, reactionresponse or 
                   7436:         # organicresponse items. 
                   7437:         foreach my $part_id (@possible_parts) {
                   7438:             if (grep(/^\Q$part_id\E$/,@parts)) {
                   7439:                 push(@allparts,$part_id);
                   7440:             } else {
                   7441:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
                   7442:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
                   7443:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
1.524     raeburn  7444:                     push(@allparts,$part_id);
1.503     raeburn  7445:                 }
                   7446:             }
                   7447:         }
1.435     foxr     7448: 
1.523     raeburn  7449: 	foreach my $part_id (@allparts) {
                   7450:             my $lines;
1.447     foxr     7451: 
                   7452: 	    # TODO - make this a persistent hash not an array.
                   7453: 
1.509     raeburn  7454:             # optionresponse, matchresponse and rankresponse type items 
                   7455:             # render as separate sub-questions in exam mode.
1.503     raeburn  7456:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
1.509     raeburn  7457:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
                   7458:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
1.503     raeburn  7459:                 my ($numbub,$numshown);
                   7460:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
                   7461:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
                   7462:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
                   7463:                     }
                   7464:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
                   7465:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
                   7466:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
                   7467:                     }
1.509     raeburn  7468:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
                   7469:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
                   7470:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
                   7471:                     }
1.503     raeburn  7472:                 }
                   7473:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
                   7474:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
                   7475:                 }
                   7476:                 my $bubbles_per_line = 10;
1.523     raeburn  7477:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7478:                 if (($numbub % $bubbles_per_line) != 0) {
1.503     raeburn  7479:                     $inner_bubble_lines++;
                   7480:                 }
                   7481:                 for (my $i=0; $i<$numshown; $i++) {
                   7482:                     $subdivided_bubble_lines{$response_number} .= 
                   7483:                         $inner_bubble_lines.',';
                   7484:                 }
                   7485:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
1.523     raeburn  7486:                 $lines = $numshown * $inner_bubble_lines;
                   7487:             } else {
                   7488:                 $lines = $analysis{"$part_id.bubble_lines"};
1.503     raeburn  7489:             } 
1.447     foxr     7490: 
1.503     raeburn  7491:             $first_bubble_line{$response_number} = $bubble_line;
                   7492: 	    $bubble_lines_per_response{$response_number} = $lines;
                   7493:             $responsetype_per_response{$response_number} = 
                   7494:                 $analysis{$part_id.'.type'};
1.447     foxr     7495: 	    $response_number++;
                   7496: 
                   7497: 	    $bubble_line +=  $lines;
                   7498: 	    $total_lines +=  $lines;
1.435     foxr     7499: 	}
                   7500: 
1.191     albertel 7501:     }
                   7502:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     7503: 
                   7504:     &save_bubble_lines();
1.330     albertel 7505:     $env{'form.scantron_maxbubble'} =
1.435     foxr     7506: 	$total_lines;
1.257     albertel 7507:     return $env{'form.scantron_maxbubble'};
1.191     albertel 7508: }
                   7509: 
1.423     albertel 7510: 
1.157     albertel 7511: sub scantron_validate_missingbubbles {
                   7512:     my ($r,$currentphase) = @_;
                   7513:     #get student info
                   7514:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7515:     my %idmap=&username_to_idmap($classlist);
                   7516: 
                   7517:     #get scantron line setup
1.257     albertel 7518:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7519:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7520:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7521:     if (!$max_bubble) { $max_bubble=2**31; }
                   7522:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7523: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7524: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7525: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7526: 						 $scan_data);
                   7527: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7528: 	my @to_correct;
1.470     foxr     7529: 	
                   7530: 	# Probably here's where the error is...
                   7531: 
1.157     albertel 7532: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7533:             my $lastbubble;
                   7534:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7535:                my $question = $1;
                   7536:                my $subquestion = $2;
                   7537:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7538:                my $first = $first_bubble_line{$question-1};
                   7539:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7540:                my $subcount = 1;
                   7541:                while ($subcount<$subquestion) {
                   7542:                    $first += $subans[$subcount-1];
                   7543:                    $subcount ++;
                   7544:                }
                   7545:                my $count = $subans[$subquestion-1];
                   7546:                $lastbubble = $first + $count;
                   7547:             } else {
                   7548:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7549:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7550:             }
                   7551:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7552: 	    push(@to_correct,$missing);
                   7553: 	}
                   7554: 	if (@to_correct) {
                   7555: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7556: 				     $line,'missingbubble',\@to_correct);
                   7557: 	    return (1,$currentphase);
                   7558: 	}
                   7559: 
                   7560:     }
                   7561:     return (0,$currentphase+1);
                   7562: }
                   7563: 
1.423     albertel 7564: 
1.82      albertel 7565: sub scantron_process_students {
1.75      albertel 7566:     my ($r) = @_;
1.513     foxr     7567: 
1.257     albertel 7568:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7569:     my ($symb)=&get_symb($r);
1.513     foxr     7570:     if (!$symb) {
                   7571: 	return '';
                   7572:     }
1.324     albertel 7573:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7574: 
1.257     albertel 7575:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7576:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7577:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7578:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7579:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7580:     my $map=$navmap->getResourceByUrl($sequence);
                   7581:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7582: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7583:     my $result= <<SCANTRONFORM;
1.81      albertel 7584: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7585:   <input type="hidden" name="command" value="scantron_configphase" />
                   7586:   $default_form_data
                   7587: SCANTRONFORM
1.82      albertel 7588:     $r->print($result);
                   7589: 
                   7590:     my @delayqueue;
1.140     albertel 7591:     my %completedstudents;
                   7592:     
1.520     www      7593:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7594:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7595:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7596:  				    'Scantron Progress',$count,
1.195     albertel 7597: 				    'inline',undef,'scantronupload');
1.140     albertel 7598:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7599: 					  'Processing first student');
                   7600:     my $start=&Time::HiRes::time();
1.158     albertel 7601:     my $i=-1;
1.200     albertel 7602:     my ($uname,$udom,$started);
1.447     foxr     7603: 
                   7604:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7605:     
                   7606: 
                   7607:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7608:     # the user and return.
                   7609: 
                   7610:     if ($ssi_error) {
                   7611: 	$r->print("</form>");
                   7612: 	&ssi_print_error($r);
                   7613: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7614:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7615: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7616:     }
1.447     foxr     7617: 
1.157     albertel 7618:     while ($i<$scanlines->{'count'}) {
                   7619:  	($uname,$udom)=('','');
                   7620:  	$i++;
1.200     albertel 7621:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7622:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7623: 	if ($started) {
                   7624: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7625: 						     'last student');
                   7626: 	}
                   7627: 	$started=1;
1.157     albertel 7628:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7629:  						 $scan_data);
                   7630:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7631:  					      \%idmap,$i)) {
                   7632:   	    &scantron_add_delay(\@delayqueue,$line,
                   7633:  				'Unable to find a student that matches',1);
                   7634:  	    next;
                   7635:   	}
                   7636:  	if (exists $completedstudents{$uname}) {
                   7637:  	    &scantron_add_delay(\@delayqueue,$line,
                   7638:  				'Student '.$uname.' has multiple sheets',2);
                   7639:  	    next;
                   7640:  	}
                   7641:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7642: 
                   7643: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7644:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7645: 
                   7646: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7647: 	    &scantron_putfile($scanlines,$scan_data);
                   7648: 	}
1.161     albertel 7649: 	
                   7650: 	my $i=0;
1.83      albertel 7651: 	foreach my $resource (@resources) {
1.85      albertel 7652: 	    $i++;
1.193     albertel 7653: 	    my %form=('submitted'     =>'scantron',
                   7654: 		      'grade_target'  =>'grade',
                   7655: 		      'grade_username'=>$uname,
                   7656: 		      'grade_domain'  =>$udom,
1.257     albertel 7657: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7658: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7659: 	    if (exists($scan_record->{'scantron.CODE'})
                   7660: 		&& 
                   7661: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7662: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7663: 	    } else {
                   7664: 		$form{'CODE'}='';
1.513     foxr     7665: 	    } 
                   7666: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
                   7667: 	    if ($ssi_error) {
                   7668: 		$ssi_error = 0;	# So end of handler error message does not trigger.
                   7669: 		$r->print("</form>");
                   7670: 		&ssi_print_error($r);
                   7671: 		$r->print(&show_grading_menu_form($symb));
1.520     www      7672:                 &Apache::lonnet::remove_lock($lock);
1.513     foxr     7673: 		return '';	# Why return ''?  Beats me.
1.193     albertel 7674: 	    }
1.513     foxr     7675: 
1.213     albertel 7676: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7677: 	}
1.140     albertel 7678: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7679: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7680:     } continue {
1.330     albertel 7681: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7682: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7683:     }
1.140     albertel 7684:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7685:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7686: #    my $lasttime = &Time::HiRes::time()-$start;
                   7687: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7688: 
1.200     albertel 7689:     $r->print("</form>");
1.324     albertel 7690:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7691:     return '';
1.75      albertel 7692: }
1.157     albertel 7693: 
                   7694: sub scantron_upload_scantron_data {
                   7695:     my ($r)=@_;
1.257     albertel 7696:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7697:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7698: 							  'domainid',
                   7699: 							  'coursename');
1.257     albertel 7700:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7701: 						   'domainid');
1.324     albertel 7702:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7703:     $r->print('
1.157     albertel 7704: <script type="text/javascript" language="javascript">
                   7705:     function checkUpload(formname) {
                   7706: 	if (formname.upfile.value == "") {
                   7707: 	    alert("Please use the browse button to select a file from your local directory.");
                   7708: 	    return false;
                   7709: 	}
                   7710: 	formname.submit();
                   7711:     }
                   7712: </script>
                   7713: 
1.492     albertel 7714: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7715: '.$default_form_data.'
1.181     albertel 7716: <table>
1.492     albertel 7717: <tr><td>'.$select_link.'                             </td></tr>
                   7718: <tr><td>'.&mt('Course ID:').'     </td>
                   7719:     <td><input name="courseid"   type="text" />      </td></tr>
                   7720: <tr><td>'.&mt('Course Name:').'   </td>
                   7721:     <td><input name="coursename" type="text" />      </td></tr>
                   7722: <tr><td>'.&mt('Domain:').'        </td>
                   7723:     <td>'.$domsel.'                                  </td></tr>
                   7724: <tr><td>'.&mt('File to upload:').'</td>
                   7725:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7726: </table>
1.492     albertel 7727: <input name="command" value="scantronupload_save" type="hidden" />
                   7728: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7729: </form>
1.492     albertel 7730: ');
1.157     albertel 7731:     return '';
                   7732: }
                   7733: 
1.423     albertel 7734: 
1.157     albertel 7735: sub scantron_upload_scantron_data_save {
                   7736:     my($r)=@_;
1.324     albertel 7737:     my ($symb)=&get_symb($r,1);
1.182     albertel 7738:     my $doanotherupload=
                   7739: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7740: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7741: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7742: 	'</form>'."\n";
1.257     albertel 7743:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7744: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7745: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7746: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7747: 	if ($symb) {
1.324     albertel 7748: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7749: 	} else {
                   7750: 	    $r->print($doanotherupload);
                   7751: 	}
1.162     albertel 7752: 	return '';
                   7753:     }
1.257     albertel 7754:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7755:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7756:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7757:     #FIXME
                   7758:     #copied from lonnet::userfileupload()
                   7759:     #make that function able to target a specified course
                   7760:     # Replace Windows backslashes by forward slashes
                   7761:     $fname=~s/\\/\//g;
                   7762:     # Get rid of everything but the actual filename
                   7763:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7764:     # Replace spaces by underscores
                   7765:     $fname=~s/\s+/\_/g;
                   7766:     # Replace all other weird characters by nothing
                   7767:     $fname=~s/[^\w\.\-]//g;
                   7768:     # See if there is anything left
                   7769:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7770:     my $uploadedfile=$fname;
1.157     albertel 7771:     $fname='scantron_orig_'.$fname;
1.257     albertel 7772:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7773: 	$r->print(&mt("<span class=\"LC_error\">Error:</span> The file you attempted to upload, [_1]  contained no information. Please check that you entered the correct filename.",'<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
1.183     albertel 7774:     } else {
1.275     albertel 7775: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7776: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7777: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7778: 			  (length($env{'form.upfile'})-1),
                   7779: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7780: 	} else {
1.492     albertel 7781: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7782: 			  $result,
                   7783: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7784: 
1.183     albertel 7785: 	}
                   7786:     }
1.174     albertel 7787:     if ($symb) {
1.209     ng       7788: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7789:     } else {
1.182     albertel 7790: 	$r->print($doanotherupload);
1.174     albertel 7791:     }
1.157     albertel 7792:     return '';
                   7793: }
                   7794: 
1.202     albertel 7795: sub valid_file {
                   7796:     my ($requested_file)=@_;
                   7797:     foreach my $filename (sort(&scantron_filenames())) {
                   7798: 	if ($requested_file eq $filename) { return 1; }
                   7799:     }
                   7800:     return 0;
                   7801: }
                   7802: 
                   7803: sub scantron_download_scantron_data {
                   7804:     my ($r)=@_;
1.324     albertel 7805:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7806:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7807:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7808:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7809:     if (! &valid_file($file)) {
1.492     albertel 7810: 	$r->print('
1.202     albertel 7811: 	<p>
1.492     albertel 7812: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7813:         </p>
1.492     albertel 7814: ');
1.324     albertel 7815: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7816: 	return;
                   7817:     }
                   7818:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7819:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7820:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7821:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7822:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7823:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7824:     $r->print('
1.202     albertel 7825:     <p>
1.492     albertel 7826: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7827: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7828:     </p>
                   7829:     <p>
1.492     albertel 7830: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7831: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7832:     </p>
                   7833:     <p>
1.492     albertel 7834: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7835: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7836:     </p>
1.492     albertel 7837: ');
1.324     albertel 7838:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7839:     return '';
                   7840: }
1.157     albertel 7841: 
1.523     raeburn  7842: sub checkscantron_results {
                   7843:     my ($r) = @_;
                   7844:     my ($symb)=&get_symb($r);
                   7845:     if (!$symb) {return '';}
                   7846:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7847:     my $cid = $env{'request.course.id'};
                   7848:     my %lettdig = (
                   7849:                     A => 1,
                   7850:                     B => 2,
                   7851:                     C => 3,
                   7852:                     D => 4,
                   7853:                     E => 5,
                   7854:                     F => 6,
                   7855:                     G => 7,
                   7856:                     H => 8,
                   7857:                     I => 9,
                   7858:                     J => 0,
                   7859:                   );
                   7860:     my $numletts = scalar(keys(%lettdig));
                   7861:     my $cnum = $env{'course.'.$cid.'.num'};
                   7862:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7863:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7864:     my %record;
                   7865:     my %scantron_config =
                   7866:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7867:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7868:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7869:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7870:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7871:     my $map=$navmap->getResourceByUrl($sequence);
                   7872:     my @resources=$navmap->retrieveResources($map,undef,1,0);
                   7873:     my (%scandata,%lastname,%bylast);
                   7874:     $r->print('
                   7875: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7876: 
                   7877:     my @delayqueue;
                   7878:     my %completedstudents;
                   7879: 
                   7880:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7881:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7882:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7883:                                     'inline',undef,'checkscantron');
                   7884:     my ($username,$domain,$uname,$started);
                   7885: 
                   7886:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
                   7887: 
                   7888:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7889:                                           'Processing first student');
                   7890:     my $start=&Time::HiRes::time();
                   7891:     my $i=-1;
                   7892: 
                   7893:     while ($i<$scanlines->{'count'}) {
                   7894:         ($username,$domain,$uname)=('','','');
                   7895:         $i++;
                   7896:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7897:         if ($line=~/^[\s\cz]*$/) { next; }
                   7898:         if ($started) {
                   7899:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7900:                                                      'last student');
                   7901:         }
                   7902:         $started=1;
                   7903:         my $scan_record=
                   7904:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7905:                                                      $scan_data);
                   7906:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7907:                                                               \%idmap,$i)) {
                   7908:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7909:                                 'Unable to find a student that matches',1);
                   7910:             next;
                   7911:         }
                   7912:         if (exists $completedstudents{$uname}) {
                   7913:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7914:                                 'Student '.$uname.' has multiple sheets',2);
                   7915:             next;
                   7916:         }
                   7917:         my $pid = $scan_record->{'scantron.ID'};
                   7918:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7919:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7920:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7921:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7922:         chomp($scandata{$pid});
                   7923:         $scandata{$pid} =~ s/\r$//;
                   7924:         ($username,$domain)=split(/:/,$uname);
                   7925:         my $counter = -1;
                   7926:         my (%expected,%startpos);
                   7927:         foreach my $resource (@resources) {
                   7928:             next if (!$resource->is_problem());
                   7929:             my $symb = $resource->symb();
                   7930:             my $partsref = $resource->parts();
                   7931:             my @parts;
                   7932:             my @part_ids = ();
                   7933:             if (ref($partsref) eq 'ARRAY') {
                   7934:                @parts = @{$partsref};
                   7935:                foreach my $part (@parts) {
                   7936:                    my @resp_ids = $resource->responseIds($part);
                   7937:                    foreach my $resp (@resp_ids) {
                   7938:                        $counter ++;
                   7939:                        my $part_id = $part.'.'.$resp;
                   7940:                        $expected{$part_id} = 0;
                   7941:                        push(@part_ids,$part_id);
                   7942:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   7943:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   7944:                            foreach my $item (@sub_lines) {
                   7945:                                $expected{$part_id} += $item;
                   7946:                            }
                   7947:                        } else {
                   7948:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   7949:                        }
                   7950:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   7951:                    }
                   7952:                 }
                   7953:             }
                   7954:             if ($symb) {
                   7955:                 my %recorded;
                   7956:                 my (%returnhash) =
                   7957:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   7958:                 if ($returnhash{'version'}) {
                   7959:                     my %lasthash=();
                   7960:                     my $version;
                   7961:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
                   7962:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   7963:                             $lasthash{$key}=$returnhash{$version.':'.$key};
                   7964:                         }
                   7965:                     }
                   7966:                     foreach my $key (keys(%lasthash)) {
                   7967:                         if ($key =~ /\.scantron$/) {
                   7968:                             my $value = &unescape($lasthash{$key});
                   7969:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   7970:                             if ($value eq '') {
                   7971:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   7972:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
                   7973:                                         $recorded{$part_id} .= $;
                   7974:                                     }
                   7975:                                 }
                   7976:                             } else {
                   7977:                                 my @tocheck;
                   7978:                                 my @items = split(//,$value);
                   7979:                                 if (($scantron_config{'Qon'} eq 'letter') ||
                   7980:                                     ($scantron_config{'Qon'} eq 'number')) {
                   7981:                                     if (@items < $expected{$part_id}) {
                   7982:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
                   7983:                                         my @singles = split(//,$fragment);
                   7984:                                         foreach my $pos (@singles) {
                   7985:                                             if ($pos eq ' ') {
                   7986:                                                 push(@tocheck,$pos);
                   7987:                                             } else {
                   7988:                                                 my $next = shift(@items);
                   7989:                                                 push(@tocheck,$next);
                   7990:                                             }
                   7991:                                         }
                   7992:                                     } else {
                   7993:                                         @tocheck = @items;
                   7994:                                     }
                   7995:                                     foreach my $letter (@tocheck) {
                   7996:                                         if ($scantron_config{'Qon'} eq 'letter') {
                   7997:                                             if ($letter !~ /^[A-J]$/) {
                   7998:                                                 $letter = $scantron_config{'Qoff'};
                   7999:                                             }
                   8000:                                             $recorded{$part_id} .= $letter;
                   8001:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
                   8002:                                             my $digit;
                   8003:                                             if ($letter !~ /^[A-J]$/) {
                   8004:                                                 $digit = $scantron_config{'Qoff'};
                   8005:                                             } else {
                   8006:                                                 $digit = $lettdig{$letter};
                   8007:                                             }
                   8008:                                             $recorded{$part_id} .= $digit;
                   8009:                                         }
                   8010:                                     }
                   8011:                                 } else {
                   8012:                                     @tocheck = @items;
                   8013:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8014:                                         my $curr_sub = shift(@tocheck);
                   8015:                                         my $digit;
                   8016:                                         if ($curr_sub =~ /^[A-J]$/) {
                   8017:                                             $digit = $lettdig{$curr_sub}-1;
                   8018:                                         }
                   8019:                                         if ($curr_sub eq 'J') {
                   8020:                                             $digit += scalar($numletts);
                   8021:                                         }
                   8022:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8023:                                             if ($j == $digit) {
                   8024:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
                   8025:                                             } else {
                   8026:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8027:                                             }
                   8028:                                         }
                   8029:                                     }
                   8030:                                 }
                   8031:                             }
                   8032:                         }
                   8033:                     }
                   8034:                 }
                   8035:                 foreach my $part_id (@part_ids) {
                   8036:                     if ($recorded{$part_id} eq '') {
                   8037:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8038:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8039:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8040:                             }
                   8041:                         }
                   8042:                     }
                   8043:                     $record{$pid} .= $recorded{$part_id};
                   8044:                 }
                   8045:             }
                   8046:         }
                   8047:     }
                   8048:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8049:     $r->print('<br />');
                   8050:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8051:     $passed = 0;
                   8052:     $failed = 0;
                   8053:     $numstudents = 0;
                   8054:     foreach my $last (sort(keys(%bylast))) {
                   8055:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8056:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8057:                 my $showscandata = $scandata{$pid};
                   8058:                 my $showrecord = $record{$pid};
                   8059:                 $showscandata =~ s/\s/&nbsp;/g;
                   8060:                 $showrecord =~ s/\s/&nbsp;/g;
                   8061:                 if ($scandata{$pid} eq $record{$pid}) {
                   8062:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8063:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8064: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8065: '</tr>'."\n".
                   8066: '<tr class="'.$css_class.'">'."\n".
                   8067: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8068:                     $passed ++;
                   8069:                 } else {
                   8070:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8071:                     $badstudents .= '<tr class="'.$css_class.'"><td>'.&mt('Scantron').'</td><td><span class="LC_nobreak">'.$scandata{$pid}.'</span></td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8072: '</tr>'."\n".
                   8073: '<tr class="'.$css_class.'">'."\n".
                   8074: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8075: '</tr>'."\n";
                   8076:                     $failed ++;
                   8077:                 }
                   8078:                 $numstudents ++;
                   8079:             }
                   8080:         }
                   8081:     }
                   8082:     $r->print('<p>'.&mt('Comparison of scantron data (including corrections) with corresponding submission records (most recent submission) for <b>[quant,_1,student]</b>  ([_2] scantron lines/student).',$numstudents,$env{'form.scantron_maxbubble'}).'</p>');
                   8083:     $r->print('<p>'.&mt('Exact matches for <b>[quant,_1,student]</b>.',$passed).'<br />'.&mt('Discrepancies detected for <b>[quant,_1,student]</b>.',$failed).'</p>');
                   8084:     if ($passed) {
                   8085:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8086:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8087:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8088:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8089:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8090:                  $okstudents."\n".
                   8091:                  &Apache::loncommon::end_data_table().'<br />');
                   8092:     }
                   8093:     if ($failed) {
                   8094:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8095:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8096:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8097:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8098:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8099:                  $badstudents."\n".
                   8100:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8101:                  &mt('Differences can occur if submissions were modified using manual grading after a scantron grading pass.').'<br />'.&mt('If unexpected discrepancies were detected, it is recommended that you inspect the original scantron sheets.');  
                   8102:     }
                   8103:     $r->print('</form><br />'.$grading_menu_button);
                   8104:     return;
                   8105: }
                   8106: 
1.423     albertel 8107: 
1.75      albertel 8108: #-------- end of section for handling grading scantron forms -------
                   8109: #
                   8110: #-------------------------------------------------------------------
                   8111: 
1.72      ng       8112: #-------------------------- Menu interface -------------------------
                   8113: #
                   8114: #--- Show a Grading Menu button - Calls the next routine ---
                   8115: sub show_grading_menu_form {
1.324     albertel 8116:     my ($symb)=@_;
1.125     ng       8117:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8118: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8119: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8120: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8121: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8122: 	'</form>'."\n";
                   8123:     return $result;
                   8124: }
                   8125: 
1.77      ng       8126: # -- Retrieve choices for grading form
                   8127: sub savedState {
                   8128:     my %savedState = ();
1.257     albertel 8129:     if ($env{'form.saveState'}) {
                   8130: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8131: 	    my ($key,$value) = split(/=/,$_,2);
                   8132: 	    $savedState{$key} = $value;
                   8133: 	}
                   8134:     }
                   8135:     return \%savedState;
                   8136: }
1.76      ng       8137: 
1.443     banghart 8138: sub grading_menu {
                   8139:     my ($request) = @_;
                   8140:     my ($symb)=&get_symb($request);
                   8141:     if (!$symb) {return '';}
                   8142:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8143:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8144: 
1.444     banghart 8145:     $request->print($table);
1.443     banghart 8146:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8147:                   'handgrade'=>$hdgrade,
                   8148:                   'probTitle'=>$probTitle,
                   8149:                   'command'=>'submit_options',
                   8150:                   'saveState'=>"",
                   8151:                   'gradingMenu'=>1,
                   8152:                   'showgrading'=>"yes");
                   8153:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8154:     my @menu = ({ url => $url,
                   8155:                      name => &mt('Manual Grading/View Submissions'),
                   8156:                      short_description => 
                   8157:     &mt('Start the process of hand grading submissions.'),
                   8158:                  });
                   8159:     $fields{'command'} = 'csvform';
                   8160:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8161:     push(@menu, { url => $url,
1.443     banghart 8162:                    name => &mt('Upload Scores'),
                   8163:                    short_description => 
                   8164:             &mt('Specify a file containing the class scores for current resource.')});
                   8165:     $fields{'command'} = 'processclicker';
                   8166:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8167:     push(@menu, { url => $url,
1.443     banghart 8168:                    name => &mt('Process Clicker'),
                   8169:                    short_description => 
                   8170:             &mt('Specify a file containing the clicker information for this resource.')});
                   8171:     $fields{'command'} = 'scantron_selectphase';
                   8172:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8173:     push(@menu, { url => $url,
1.523     raeburn  8174:                    name => &mt('Grade/Manage/Review Scantron Forms'),
1.454     banghart 8175:                    short_description => 
1.523     raeburn  8176:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
1.443     banghart 8177:     $fields{'command'} = 'verify';
                   8178:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8179:     push(@menu, { url => "",
1.443     banghart 8180:                    name => &mt('Verify Receipt'),
                   8181:                    short_description => 
                   8182:             &mt('')});
                   8183:     #
                   8184:     # Create the menu
                   8185:     my $Str;
1.444     banghart 8186:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8187:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8188:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8189:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8190: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8191: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8192: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8193: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8194: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8195: 
1.443     banghart 8196:     foreach my $menudata (@menu) {
1.445     banghart 8197:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   8198:             $Str .='    <h3><a '.
                   8199:                 $menudata->{'jscript'}.
                   8200:                 ' href="'.
                   8201:                 $menudata->{'url'}.'" >'.
                   8202:                 $menudata->{'name'}."</a></h3>\n";
                   8203:         } else {
1.511     www      8204:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 8205:                 $menudata->{'jscript'}.
1.458     banghart 8206:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      8207:                 ' /> '.
                   8208: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   8209:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 8210:         }
1.443     banghart 8211:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8212:             "\n";
                   8213:     }
1.444     banghart 8214:     $Str .="</form>\n";
1.443     banghart 8215:     $request->print(<<GRADINGMENUJS);
                   8216: <script type="text/javascript" language="javascript">
                   8217:     function checkChoice(formname,val,cmdx) {
                   8218: 	if (val <= 2) {
                   8219: 	    var cmd = radioSelection(formname.radioChoice);
                   8220: 	    var cmdsave = cmd;
                   8221: 	} else {
                   8222: 	    cmd = cmdx;
                   8223: 	    cmdsave = 'submission';
                   8224: 	}
                   8225: 	formname.command.value = cmd;
                   8226: 	if (val < 5) formname.submit();
                   8227: 	if (val == 5) {
1.458     banghart 8228: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8229: 	        return false;
                   8230: 	    } else {
                   8231: 	        formname.submit();
                   8232: 	    }
1.445     banghart 8233: 	}
                   8234:     }
1.443     banghart 8235: 
                   8236:     function checkReceiptNo(formname,nospace) {
                   8237: 	var receiptNo = formname.receipt.value;
                   8238: 	var checkOpt = false;
                   8239: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8240: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8241: 	if (checkOpt) {
                   8242: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8243: 	    formname.receipt.value = "";
                   8244: 	    formname.receipt.focus();
                   8245: 	    return false;
                   8246: 	}
                   8247: 	return true;
                   8248:     }
                   8249: </script>
                   8250: GRADINGMENUJS
                   8251:     &commonJSfunctions($request);
                   8252:     return $Str;    
                   8253: }
                   8254: 
                   8255: 
                   8256: #--- Displays the submissions first page -------
                   8257: sub submit_options {
1.72      ng       8258:     my ($request) = @_;
1.324     albertel 8259:     my ($symb)=&get_symb($request);
1.72      ng       8260:     if (!$symb) {return '';}
1.76      ng       8261:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8262: 
                   8263:     $request->print(<<GRADINGMENUJS);
                   8264: <script type="text/javascript" language="javascript">
1.116     ng       8265:     function checkChoice(formname,val,cmdx) {
                   8266: 	if (val <= 2) {
                   8267: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8268: 	    var cmdsave = cmd;
1.116     ng       8269: 	} else {
                   8270: 	    cmd = cmdx;
1.118     ng       8271: 	    cmdsave = 'submission';
1.116     ng       8272: 	}
                   8273: 	formname.command.value = cmd;
1.118     ng       8274: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8275: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8276: 	if (val < 5) formname.submit();
                   8277: 	if (val == 5) {
1.72      ng       8278: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8279: 	    formname.submit();
                   8280: 	}
1.238     albertel 8281: 	if (val < 7) formname.submit();
1.72      ng       8282:     }
                   8283: 
                   8284:     function checkReceiptNo(formname,nospace) {
                   8285: 	var receiptNo = formname.receipt.value;
                   8286: 	var checkOpt = false;
                   8287: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8288: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8289: 	if (checkOpt) {
                   8290: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8291: 	    formname.receipt.value = "";
                   8292: 	    formname.receipt.focus();
                   8293: 	    return false;
                   8294: 	}
                   8295: 	return true;
                   8296:     }
                   8297: </script>
                   8298: GRADINGMENUJS
1.118     ng       8299:     &commonJSfunctions($request);
1.324     albertel 8300:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8301:     my $result;
1.76      ng       8302:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8303:     my $savedState = &savedState();
1.118     ng       8304:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8305:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8306:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8307:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8308: 
                   8309:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8310: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8311: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8312: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8313: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8314: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8315: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8316: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8317: 
1.472     albertel 8318:     $result.='
                   8319:     <div class="LC_grade_select_mode">
1.473     albertel 8320:       <div class="LC_grade_select_mode_current">
                   8321:         <h2>
                   8322:           '.&mt('Grade Current Resource').'
                   8323:         </h2>
                   8324:         <div class="LC_grade_select_mode_body">
                   8325:           <div class="LC_grades_resource_info">
                   8326:            '.$table.'
                   8327:           </div>
                   8328:           <div class="LC_grade_select_mode_selector">
                   8329:              <div class="LC_grade_select_mode_selector_header">
                   8330:                 '.&mt('Sections').'
                   8331:              </div>
                   8332:              <div class="LC_grade_select_mode_selector_body">
                   8333: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       8334:     if (ref($sections)) {
1.524     raeburn  8335: 	foreach my $section (sort(@$sections)) {
1.472     albertel 8336: 	    $result.='<option value="'.$section.'" '.
                   8337: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 8338: 	}
1.116     ng       8339:     }
1.401     albertel 8340:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8341:     $result.='
1.473     albertel 8342:              </div>
                   8343:           </div>
                   8344:           <div class="LC_grade_select_mode_selector">
                   8345:              <div class="LC_grade_select_mode_selector_header">
                   8346:                 '.&mt('Groups').'
                   8347:              </div>
                   8348:              <div class="LC_grade_select_mode_selector_body">
                   8349:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8350:              </div>
1.472     albertel 8351:           </div>
1.473     albertel 8352:           <div class="LC_grade_select_mode_selector">
                   8353:              <div class="LC_grade_select_mode_selector_header">
                   8354:                 '.&mt('Access Status').'
                   8355:              </div>
                   8356:              <div class="LC_grade_select_mode_selector_body">
                   8357:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8358:              </div>
1.472     albertel 8359:           </div>
1.473     albertel 8360:           <div class="LC_grade_select_mode_selector">
                   8361:              <div class="LC_grade_select_mode_selector_header">
                   8362:                 '.&mt('Submission Status').'
                   8363:              </div>
                   8364:              <div class="LC_grade_select_mode_selector_body">
                   8365:                <select name="submitonly" size="5">
                   8366: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8367: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8368: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8369: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8370:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8371:                </select>
                   8372:              </div>
1.472     albertel 8373:           </div>
1.473     albertel 8374:           <div class="LC_grade_select_mode_type_body">
                   8375:             <div class="LC_grade_select_mode_type">
                   8376:               <label>
                   8377:                 <input type="radio" name="radioChoice" value="submission" '.
                   8378:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8379:              &mt('Select individual students to grade and view submissions.').'
                   8380: 	      </label> 
                   8381:             </div>
                   8382:             <div class="LC_grade_select_mode_type">
                   8383: 	      <label>
                   8384:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8385:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8386:                     &mt('Grade all selected students in a grading table.').'
                   8387:               </label>
                   8388:             </div>
                   8389:             <div class="LC_grade_select_mode_type">
                   8390: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8391:             </div>
1.472     albertel 8392:           </div>
1.473     albertel 8393:         </div>
                   8394:       </div>
                   8395:       <div class="LC_grade_select_mode_page">
                   8396:         <h2>
                   8397:          '.&mt('Grade Complete Folder for One Student').'
                   8398:         </h2>
                   8399:         <div class="LC_grades_select_mode_body">
                   8400:           <div class="LC_grade_select_mode_type_body">
                   8401:             <div class="LC_grade_select_mode_type">
                   8402:               <label>
                   8403:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8404: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8405:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8406:               </label>
                   8407:             </div>
                   8408:             <div class="LC_grade_select_mode_type">
                   8409: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8410:             </div>
1.472     albertel 8411:           </div>
                   8412:         </div>
                   8413:       </div>
                   8414:     </div>
                   8415:   </form>';
1.499     albertel 8416:     $result .= &show_grading_menu_form($symb);
1.44      ng       8417:     return $result;
1.2       albertel 8418: }
                   8419: 
1.285     albertel 8420: sub reset_perm {
                   8421:     undef(%perm);
                   8422: }
                   8423: 
                   8424: sub init_perm {
                   8425:     &reset_perm();
1.300     albertel 8426:     foreach my $test_perm ('vgr','mgr','opa') {
                   8427: 
                   8428: 	my $scope = $env{'request.course.id'};
                   8429: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8430: 
                   8431: 	    $scope .= '/'.$env{'request.course.sec'};
                   8432: 	    if ( $perm{$test_perm}=
                   8433: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8434: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8435: 	    } else {
                   8436: 		delete($perm{$test_perm});
                   8437: 	    }
1.285     albertel 8438: 	}
                   8439:     }
                   8440: }
                   8441: 
1.400     www      8442: sub gather_clicker_ids {
1.408     albertel 8443:     my %clicker_ids;
1.400     www      8444: 
                   8445:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8446: 
                   8447:     # Set up a couple variables.
1.407     albertel 8448:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8449:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8450:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8451: 
1.407     albertel 8452:     foreach my $student (keys(%$classlist)) {
1.438     www      8453:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8454:         my $username = $classlist->{$student}->[$username_idx];
                   8455:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8456:         my $clickers =
1.408     albertel 8457: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8458:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8459:             $id=~s/^[\#0]+//;
1.421     www      8460:             $id=~s/[\-\:]//g;
1.407     albertel 8461:             if (exists($clicker_ids{$id})) {
1.408     albertel 8462: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8463:             } else {
1.408     albertel 8464: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8465:             }
                   8466:         }
                   8467:     }
1.407     albertel 8468:     return %clicker_ids;
1.400     www      8469: }
                   8470: 
1.402     www      8471: sub gather_adv_clicker_ids {
1.408     albertel 8472:     my %clicker_ids;
1.402     www      8473:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8474:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8475:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8476:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8477:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8478:             my ($puname,$pudom)=split(/\:/,$person);
                   8479:             my $clickers =
1.408     albertel 8480: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8481:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8482: 		$id=~s/^[\#0]+//;
1.421     www      8483:                 $id=~s/[\-\:]//g;
1.408     albertel 8484: 		if (exists($clicker_ids{$id})) {
                   8485: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8486: 		} else {
                   8487: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8488: 		}
1.405     www      8489:             }
1.402     www      8490:         }
                   8491:     }
1.407     albertel 8492:     return %clicker_ids;
1.402     www      8493: }
                   8494: 
1.413     www      8495: sub clicker_grading_parameters {
                   8496:     return ('gradingmechanism' => 'scalar',
                   8497:             'upfiletype' => 'scalar',
                   8498:             'specificid' => 'scalar',
                   8499:             'pcorrect' => 'scalar',
                   8500:             'pincorrect' => 'scalar');
                   8501: }
                   8502: 
1.400     www      8503: sub process_clicker {
                   8504:     my ($r)=@_;
                   8505:     my ($symb)=&get_symb($r);
                   8506:     if (!$symb) {return '';}
                   8507:     my $result=&checkforfile_js();
                   8508:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8509:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8510:     $result.=$table;
                   8511:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8512:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   8513:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   8514:         '.</b></td></tr>'."\n";
                   8515:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8516: # Attempt to restore parameters from last session, set defaults if not present
                   8517:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8518:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8519:                                                  \%Saveable_Parameters);
                   8520:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8521:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8522:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8523:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8524: 
                   8525:     my %checked;
1.521     www      8526:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8527:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8528:           $checked{$gradingmechanism}="checked='checked'";
                   8529:        }
                   8530:     }
                   8531: 
1.400     www      8532:     my $upload=&mt("Upload File");
                   8533:     my $type=&mt("Type");
1.402     www      8534:     my $attendance=&mt("Award points just for participation");
                   8535:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8536:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8537:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8538:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8539:     my $pcorrect=&mt("Percentage points for correct solution");
                   8540:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8541:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8542: 						   ('iclicker' => 'i>clicker',
                   8543:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8544:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8545:     $result.=<<ENDUPFORM;
1.402     www      8546: <script type="text/javascript">
                   8547: function sanitycheck() {
                   8548: // Accept only integer percentages
                   8549:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8550:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8551: // Find out grading choice
                   8552:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8553:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8554:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8555:       }
                   8556:    }
                   8557: // By default, new choice equals user selection
                   8558:    newgradingchoice=gradingchoice;
                   8559: // Not good to give more points for false answers than correct ones
                   8560:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8561:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8562:    }
                   8563: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8564:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8565:       document.forms.gradesupload.pcorrect.value=100;
                   8566:       document.forms.gradesupload.pincorrect.value=100;
                   8567:    }
                   8568: // If the values are different, cannot be attendance only
                   8569:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8570:        (gradingchoice=='attendance')) {
                   8571:        newgradingchoice='personnel';
                   8572:    }
                   8573: // Change grading choice to new one
                   8574:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8575:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8576:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8577:       } else {
                   8578:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8579:       }
                   8580:    }
                   8581: // Remember the old state
                   8582:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8583: }
                   8584: </script>
1.400     www      8585: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8586: <input type="hidden" name="symb" value="$symb" />
                   8587: <input type="hidden" name="command" value="processclickerfile" />
                   8588: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8589: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8590: <input type="file" name="upfile" size="50" />
                   8591: <br /><label>$type: $selectform</label>
1.451     albertel 8592: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8593: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8594: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8595: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8596: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8597: <br />&nbsp;&nbsp;&nbsp;
                   8598: <input type="text" name="givenanswer" size="50" />
1.413     www      8599: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8600: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8601: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8602: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8603: </form>
                   8604: ENDUPFORM
                   8605:     $result.='</td></tr></table>'."\n".
                   8606:              '</td></tr></table><br /><br />'."\n";
                   8607:     $result.=&show_grading_menu_form($symb);
                   8608:     return $result;
                   8609: }
                   8610: 
                   8611: sub process_clicker_file {
                   8612:     my ($r)=@_;
                   8613:     my ($symb)=&get_symb($r);
                   8614:     if (!$symb) {return '';}
1.413     www      8615: 
                   8616:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8617:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8618:                                               \%Saveable_Parameters);
                   8619: 
1.400     www      8620:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8621:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8622: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8623: 	return $result.&show_grading_menu_form($symb);
1.404     www      8624:     }
1.522     www      8625:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8626:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8627:         return $result.&show_grading_menu_form($symb);
                   8628:     }
1.522     www      8629:     my $foundgiven=0;
1.521     www      8630:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8631:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8632:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8633:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8634:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8635:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8636:         $foundgiven=$#answers+1;
1.521     www      8637:     }
1.407     albertel 8638:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8639:     my %correct_ids;
1.404     www      8640:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8641: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8642:     }
                   8643:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8644: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8645: 	   $correct_id=~tr/a-z/A-Z/;
                   8646: 	   $correct_id=~s/\s//gs;
                   8647: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8648:            $correct_id=~s/[\-\:]//g;
1.414     www      8649:            if ($correct_id) {
                   8650: 	      $correct_ids{$correct_id}='specified';
                   8651:            }
                   8652:         }
1.400     www      8653:     }
1.404     www      8654:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8655: 	$result.=&mt('Score based on attendance only');
1.521     www      8656:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8657:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8658:     } else {
1.408     albertel 8659: 	my $number=0;
1.411     www      8660: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8661: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8662: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8663: 	    if ($correct_ids{$id} eq 'specified') {
                   8664: 		$result.=&mt('specified');
                   8665: 	    } else {
                   8666: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8667: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8668: 	    }
                   8669: 	    $number++;
                   8670: 	}
1.411     www      8671:         $result.="</p>\n";
1.408     albertel 8672: 	if ($number==0) {
                   8673: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8674: 	    return $result.&show_grading_menu_form($symb);
                   8675: 	}
1.404     www      8676:     }
1.405     www      8677:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8678:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8679: 		     '<span class="LC_error">',
                   8680: 		     '</span>',
                   8681: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8682:         return $result.&show_grading_menu_form($symb);
                   8683:     }
1.410     www      8684: 
                   8685: # Were able to get all the info needed, now analyze the file
                   8686: 
1.411     www      8687:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8688:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8689:     my $heading=&mt('Scanning clicker file');
                   8690:     $result.=(<<ENDHEADER);
                   8691: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8692: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8693: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8694: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8695: <input type="hidden" name="symb" value="$symb" />
                   8696: <input type="hidden" name="command" value="assignclickergrades" />
                   8697: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8698: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8699: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8700: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8701: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8702: ENDHEADER
1.522     www      8703:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8704:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8705:     } 
1.408     albertel 8706:     my %responses;
                   8707:     my @questiontitles;
1.405     www      8708:     my $errormsg='';
                   8709:     my $number=0;
                   8710:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8711: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8712:     }
1.419     www      8713:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8714:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8715:     }
1.411     www      8716:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8717:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8718:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8719:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8720:              '<br />';
1.522     www      8721:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8722:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8723:        return $result.&show_grading_menu_form($symb);
                   8724:     } 
1.414     www      8725: # Remember Question Titles
                   8726: # FIXME: Possibly need delimiter other than ":"
                   8727:     for (my $i=0;$i<$number;$i++) {
                   8728:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8729:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8730:     }
1.411     www      8731:     my $correct_count=0;
                   8732:     my $student_count=0;
                   8733:     my $unknown_count=0;
1.414     www      8734: # Match answers with usernames
                   8735: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8736:     foreach my $id (keys(%responses)) {
1.410     www      8737:        if ($correct_ids{$id}) {
1.414     www      8738:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8739:           $correct_count++;
1.410     www      8740:        } elsif ($clicker_ids{$id}) {
1.437     www      8741:           if ($clicker_ids{$id}=~/\,/) {
                   8742: # More than one user with the same clicker!
                   8743:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8744:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8745:                            "<select name='multi".$id."'>";
                   8746:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8747:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8748:              }
                   8749:              $result.='</select>';
                   8750:              $unknown_count++;
                   8751:           } else {
                   8752: # Good: found one and only one user with the right clicker
                   8753:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8754:              $student_count++;
                   8755:           }
1.410     www      8756:        } else {
1.411     www      8757:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8758:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8759:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8760:                    "\n".&mt("Domain").": ".
                   8761:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8762:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8763:           $unknown_count++;
1.410     www      8764:        }
1.405     www      8765:     }
1.412     www      8766:     $result.='<hr />'.
                   8767:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8768:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8769:        if ($correct_count==0) {
                   8770:           $errormsg.="Found no correct answers answers for grading!";
                   8771:        } elsif ($correct_count>1) {
1.414     www      8772:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8773:        }
                   8774:     }
1.428     www      8775:     if ($number<1) {
                   8776:        $errormsg.="Found no questions.";
                   8777:     }
1.412     www      8778:     if ($errormsg) {
                   8779:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8780:     } else {
                   8781:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8782:     }
                   8783:     $result.='</form></td></tr></table>'."\n".
1.410     www      8784:              '</td></tr></table><br /><br />'."\n";
1.404     www      8785:     return $result.&show_grading_menu_form($symb);
1.400     www      8786: }
                   8787: 
1.405     www      8788: sub iclicker_eval {
1.406     www      8789:     my ($questiontitles,$responses)=@_;
1.405     www      8790:     my $number=0;
                   8791:     my $errormsg='';
                   8792:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8793:         my %components=&Apache::loncommon::record_sep($line);
                   8794:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8795: 	if ($entries[0] eq 'Question') {
                   8796: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8797: 		$$questiontitles[$number]=$entries[$i];
                   8798: 		$number++;
                   8799: 	    }
                   8800: 	}
                   8801: 	if ($entries[0]=~/^\#/) {
                   8802: 	    my $id=$entries[0];
                   8803: 	    my @idresponses;
                   8804: 	    $id=~s/^[\#0]+//;
                   8805: 	    for (my $i=0;$i<$number;$i++) {
                   8806: 		my $idx=3+$i*6;
                   8807: 		push(@idresponses,$entries[$idx]);
                   8808: 	    }
                   8809: 	    $$responses{$id}=join(',',@idresponses);
                   8810: 	}
1.405     www      8811:     }
                   8812:     return ($errormsg,$number);
                   8813: }
                   8814: 
1.419     www      8815: sub interwrite_eval {
                   8816:     my ($questiontitles,$responses)=@_;
                   8817:     my $number=0;
                   8818:     my $errormsg='';
1.420     www      8819:     my $skipline=1;
                   8820:     my $questionnumber=0;
                   8821:     my %idresponses=();
1.419     www      8822:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8823:         my %components=&Apache::loncommon::record_sep($line);
                   8824:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8825:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8826:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8827:         next if $skipline;
                   8828:         if ($entries[0]!=$questionnumber) {
                   8829:            $questionnumber=$entries[0];
                   8830:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8831:            $number++;
1.419     www      8832:         }
1.420     www      8833:         my $id=$entries[4];
                   8834:         $id=~s/^[\#0]+//;
1.421     www      8835:         $id=~s/^v\d*\://i;
                   8836:         $id=~s/[\-\:]//g;
1.420     www      8837:         $idresponses{$id}[$number]=$entries[6];
                   8838:     }
1.524     raeburn  8839:     foreach my $id (keys(%idresponses)) {
1.420     www      8840:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8841:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8842:     }
                   8843:     return ($errormsg,$number);
                   8844: }
                   8845: 
1.414     www      8846: sub assign_clicker_grades {
                   8847:     my ($r)=@_;
                   8848:     my ($symb)=&get_symb($r);
                   8849:     if (!$symb) {return '';}
1.416     www      8850: # See which part we are saving to
                   8851:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8852: # FIXME: This should probably look for the first handgradeable part
                   8853:     my $part=$$partlist[0];
                   8854: # Start screen output
1.414     www      8855:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8856: 
1.414     www      8857:     my $heading=&mt('Assigning grades based on clicker file');
                   8858:     $result.=(<<ENDHEADER);
                   8859: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8860: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8861: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8862: ENDHEADER
                   8863: # Get correct result
                   8864: # FIXME: Possibly need delimiter other than ":"
                   8865:     my @correct=();
1.415     www      8866:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8867:     my $number=$env{'form.number'};
                   8868:     if ($gradingmechanism ne 'attendance') {
1.414     www      8869:        foreach my $key (keys(%env)) {
                   8870:           if ($key=~/^form\.correct\:/) {
                   8871:              my @input=split(/\,/,$env{$key});
                   8872:              for (my $i=0;$i<=$#input;$i++) {
                   8873:                  if (($correct[$i]) && ($input[$i]) &&
                   8874:                      ($correct[$i] ne $input[$i])) {
                   8875:                     $result.='<br /><span class="LC_warning">'.
                   8876:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8877:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8878:                  } elsif ($input[$i]) {
                   8879:                     $correct[$i]=$input[$i];
                   8880:                  }
                   8881:              }
                   8882:           }
                   8883:        }
1.415     www      8884:        for (my $i=0;$i<$number;$i++) {
1.414     www      8885:           if (!$correct[$i]) {
                   8886:              $result.='<br /><span class="LC_error">'.
                   8887:                       &mt('No correct result given for question "[_1]"!',
                   8888:                           $env{'form.question:'.$i}).'</span>';
                   8889:           }
                   8890:        }
                   8891:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8892:     }
                   8893: # Start grading
1.415     www      8894:     my $pcorrect=$env{'form.pcorrect'};
                   8895:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8896:     my $storecount=0;
1.415     www      8897:     foreach my $key (keys(%env)) {
1.420     www      8898:        my $user='';
1.415     www      8899:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8900:           $user=$1;
                   8901:        }
                   8902:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8903:           my $id=$1;
                   8904:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8905:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8906:           } elsif ($env{'form.multi'.$id}) {
                   8907:              $user=$env{'form.multi'.$id};
1.420     www      8908:           }
                   8909:        }
                   8910:        if ($user) { 
1.415     www      8911:           my @answer=split(/\,/,$env{$key});
                   8912:           my $sum=0;
1.522     www      8913:           my $realnumber=$number;
1.415     www      8914:           for (my $i=0;$i<$number;$i++) {
                   8915:              if ($answer[$i]) {
                   8916:                 if ($gradingmechanism eq 'attendance') {
                   8917:                    $sum+=$pcorrect;
1.522     www      8918:                 } elsif ($answer[$i] eq '*') {
                   8919:                    $sum+=$pcorrect;
                   8920:                 } elsif ($answer[$i] eq '-') {
                   8921:                    $realnumber--;
1.415     www      8922:                 } else {
                   8923:                    if ($answer[$i] eq $correct[$i]) {
                   8924:                       $sum+=$pcorrect;
                   8925:                    } else {
                   8926:                       $sum+=$pincorrect;
                   8927:                    }
                   8928:                 }
                   8929:              }
                   8930:           }
1.522     www      8931:           my $ave=$sum/(100*$realnumber);
1.416     www      8932: # Store
                   8933:           my ($username,$domain)=split(/\:/,$user);
                   8934:           my %grades=();
                   8935:           $grades{"resource.$part.solved"}='correct_by_override';
                   8936:           $grades{"resource.$part.awarded"}=$ave;
                   8937:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8938:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8939:                                                  $env{'request.course.id'},
                   8940:                                                  $domain,$username);
                   8941:           if ($returncode ne 'ok') {
                   8942:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8943:           } else {
                   8944:              $storecount++;
                   8945:           }
1.415     www      8946:        }
                   8947:     }
                   8948: # We are done
1.416     www      8949:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8950:              '</td></tr></table>'."\n".
1.414     www      8951:              '</td></tr></table><br /><br />'."\n";
                   8952:     return $result.&show_grading_menu_form($symb);
                   8953: }
                   8954: 
1.1       albertel 8955: sub handler {
1.41      ng       8956:     my $request=$_[0];
1.434     albertel 8957:     &reset_caches();
1.257     albertel 8958:     if ($env{'browser.mathml'}) {
1.141     www      8959: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8960:     } else {
1.141     www      8961: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8962:     }
                   8963:     $request->send_http_header;
1.44      ng       8964:     return '' if $request->header_only;
1.41      ng       8965:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8966:     my $symb=&get_symb($request,1);
1.160     albertel 8967:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8968:     my $command=$commands[0];
1.447     foxr     8969: 
1.160     albertel 8970:     if ($#commands > 0) {
                   8971: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8972:     }
1.447     foxr     8973: 
1.513     foxr     8974:     $ssi_error = 0;
1.353     albertel 8975:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8976:     if ($symb eq '' && $command eq '') {
1.257     albertel 8977: 	if ($env{'user.adv'}) {
                   8978: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8979: 		($env{'form.codethree'})) {
                   8980: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8981: 		    $env{'form.codethree'};
1.41      ng       8982: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8983: 		    &Apache::lonnet::checkin($token);
                   8984: 		if ($tsymb) {
1.137     albertel 8985: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8986: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     8987: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 8988: 					  ('grade_username' => $tuname,
                   8989: 					   'grade_domain' => $tudom,
                   8990: 					   'grade_courseid' => $tcrsid,
                   8991: 					   'grade_symb' => $tsymb)));
1.41      ng       8992: 		    } else {
1.45      ng       8993: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8994: 		    }
1.41      ng       8995: 		} else {
1.45      ng       8996: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8997: 		}
1.14      www      8998: 	    } else {
1.41      ng       8999: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9000: 	    }
                   9001: 	}
                   9002:     } else {
1.285     albertel 9003: 	&init_perm();
1.104     albertel 9004: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9005: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9006: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9007: 	    &pickStudentPage($request);
1.103     albertel 9008: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9009: 	    &displayPage($request);
1.104     albertel 9010: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9011: 	    &updateGradeByPage($request);
1.104     albertel 9012: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9013: 	    &processGroup($request);
1.104     albertel 9014: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9015: 	    $request->print(&grading_menu($request));
                   9016: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9017: 	    $request->print(&submit_options($request));
1.104     albertel 9018: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9019: 	    $request->print(&viewgrades($request));
1.104     albertel 9020: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9021: 	    $request->print(&processHandGrade($request));
1.106     albertel 9022: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9023: 	    $request->print(&editgrades($request));
1.106     albertel 9024: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9025: 	    $request->print(&verifyreceipt($request));
1.400     www      9026:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9027:             $request->print(&process_clicker($request));
                   9028:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9029:             $request->print(&process_clicker_file($request));
1.414     www      9030:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9031:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9032: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9033: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9034: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9035: 	    $request->print(&csvupload($request));
1.106     albertel 9036: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9037: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9038: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9039: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9040: 		$request->print(&csvuploadoptions($request));
1.41      ng       9041: 	    } else {
1.257     albertel 9042: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9043: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9044: 		} else {
1.257     albertel 9045: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9046: 		}
                   9047: 		$request->print(&csvuploadmap($request));
                   9048: 	    }
1.246     albertel 9049: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9050: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9051: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9052: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9053:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9054:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9055: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9056: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9057: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9058: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9059:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9060:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9061: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9062:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9063:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9064:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9065: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9066:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9067:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9068: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9069:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9070:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9071:             $request->print(&checkscantron_results($request));     
1.106     albertel 9072: 	} elsif ($command) {
1.157     albertel 9073: 	    $request->print("Access Denied ($command)");
1.26      albertel 9074: 	}
1.2       albertel 9075:     }
1.513     foxr     9076:     if ($ssi_error) {
                   9077: 	&ssi_print_error($request);
                   9078:     }
1.353     albertel 9079:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9080:     &reset_caches();
1.44      ng       9081:     return '';
                   9082: }
                   9083: 
1.1       albertel 9084: 1;
                   9085: 
1.13      albertel 9086: __END__;

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