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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.528   ! raeburn     4: # $Id: grades.pm,v 1.527 2008/07/08 08:08:44 raeburn 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: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.456     banghart   38: use Apache::lonpickcode;
1.55      matthew    39: use Apache::loncoursedata;
1.362     albertel   40: use Apache::lonmsg();
1.1       albertel   41: use Apache::Constants qw(:common);
1.167     sakharuk   42: use Apache::lonlocal;
1.386     raeburn    43: use Apache::lonenc;
1.170     albertel   44: use String::Similarity;
1.359     www        45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
1.435     foxr       49: 
1.513     foxr       50: 
1.435     foxr       51: my %perm=();
1.447     foxr       52: 
1.513     foxr       53: #  These variables are used to recover from ssi errors
                     54: 
                     55: my $ssi_retries = 5;
                     56: my $ssi_error;
                     57: my $ssi_error_resource;
                     58: my $ssi_error_message;
                     59: 
                     60: 
                     61: #  Do an ssi with retries:
                     62: #  While I'd love to factor out this with the vesrion in lonprintout,
                     63: #  that would either require a data coupling between modules, which I refuse to perpetuate
                     64: #  (there's quite enough of that already), or would require the invention of another infrastructure
                     65: #  I'm not quite ready to invent (e.g. an ssi_with_retry object).
                     66: #
                     67: # At least the logic that drives this has been pulled out into loncommon.
                     68: 
                     69: 
                     70: #
                     71: #   ssi_with_retries - Does the server side include of a resource.
                     72: #                      if the ssi call returns an error we'll retry it up to
                     73: #                      the number of times requested by the caller.
                     74: #                      If we still have a proble, no text is appended to the
                     75: #                      output and we set some global variables.
1.516     raeburn    76: #                      to indicate to the caller an SSI error occurred.  
1.513     foxr       77: #                      All of this is supposed to deal with the issues described
                     78: #                      in LonCAPA BZ 5631 see:
                     79: #                      http://bugs.lon-capa.org/show_bug.cgi?id=5631
                     80: #                      by informing the user that this happened.
                     81: #
                     82: # Parameters:
                     83: #   resource   - The resource to include.  This is passed directly, without
                     84: #                interpretation to lonnet::ssi.
                     85: #   form       - The form hash parameters that guide the interpretation of the resource
                     86: #                
                     87: #   retries    - Number of retries allowed before giving up completely.
                     88: # Returns:
                     89: #   On success, returns the rendered resource identified by the resource parameter.
                     90: # Side Effects:
                     91: #   The following global variables can be set:
1.516     raeburn    92: #    ssi_error                - If an unrecoverable error occurred this becomes true.
1.513     foxr       93: #                               It is up to the caller to initialize this to false
                     94: #                               if desired.
1.516     raeburn    95: #    ssi_error_resource  - If an unrecoverable error occurred, this is the value
1.513     foxr       96: #                               of the resource that could not be rendered by the ssi
                     97: #                               call.
1.516     raeburn    98: #    ssi_error_message   - The error string fetched from the ssi response
1.513     foxr       99: #                               in the event of an error.
                    100: #
                    101: sub ssi_with_retries {
                    102:     my ($resource, $retries, %form) = @_;
                    103:     my ($content, $response) = &Apache::loncommon::ssi_with_retries($resource, $retries, %form);
                    104:     if ($response->is_error) {
                    105: 	$ssi_error          = 1;
                    106: 	$ssi_error_resource = $resource;
                    107: 	$ssi_error_message  = $response->code . " " . $response->message;
                    108:     }
                    109: 
                    110:     return $content;
                    111: 
                    112: }
                    113: #
                    114: #  Prodcuces an ssi retry failure error message to the user:
                    115: #
                    116: 
                    117: sub ssi_print_error {
                    118:     my ($r) = @_;
1.516     raeburn   119:     my $helpurl = &Apache::loncommon::top_nav_help('Helpdesk');
                    120:     $r->print('
                    121: <br />
                    122: <h2>'.&mt('An unrecoverable network error occurred:').'</h2>
                    123: <p>
                    124: '.&mt('Unable to retrieve a resource from a server:').'<br />
                    125: '.&mt('Resource:').' '.$ssi_error_resource.'<br />
                    126: '.&mt('Error:').' '.$ssi_error_message.'
                    127: </p>
                    128: <p>'.
                    129: &mt('It is recommended that you try again later, as this error may mean the server was just temporarily unavailable, or is down for maintenance.').'<br />'.
                    130: &mt('If the error persists, please contact the [_1] for assistance.',$helpurl).
                    131: '</p>');
                    132:     return;
1.513     foxr      133: }
                    134: 
1.44      ng        135: #
1.146     albertel  136: # --- Retrieve the parts from the metadata file.---
1.44      ng        137: sub getpartlist {
1.324     albertel  138:     my ($symb) = @_;
1.439     albertel  139: 
                    140:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    141:     my $res      = $navmap->getBySymb($symb);
                    142:     my $partlist = $res->parts();
                    143:     my $url      = $res->src();
                    144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    145: 
1.146     albertel  146:     my @stores;
1.439     albertel  147:     foreach my $part (@{ $partlist }) {
1.146     albertel  148: 	foreach my $key (@metakeys) {
                    149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    150: 	}
                    151:     }
                    152:     return @stores;
1.2       albertel  153: }
                    154: 
1.44      ng        155: # --- Get the symbolic name of a problem and the url
1.324     albertel  156: sub get_symb {
1.173     albertel  157:     my ($request,$silent) = @_;
1.257     albertel  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  160:     if ($symb eq '') { 
                    161: 	if (!$silent) {
                    162: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    163: 	    return ();
                    164: 	}
                    165:     }
1.418     albertel  166:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  167:     return ($symb);
1.32      ng        168: }
                    169: 
1.129     ng        170: #--- Format fullname, username:domain if different for display
                    171: #--- Use anywhere where the student names are listed
                    172: sub nameUserString {
                    173:     my ($type,$fullname,$uname,$udom) = @_;
                    174:     if ($type eq 'header') {
1.485     albertel  175: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        176:     } else {
1.398     albertel  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        179:     }
                    180: }
                    181: 
1.44      ng        182: #--- Get the partlist and the response type for a given problem. ---
                    183: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        184: sub response_type {
1.324     albertel  185:     my ($symb) = shift;
1.377     albertel  186: 
                    187:     my $navmap = Apache::lonnavmaps::navmap->new();
                    188:     my $res = $navmap->getBySymb($symb);
                    189:     my $partlist = $res->parts();
1.392     albertel  190:     my %vPart = 
                    191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  192:     my (%response_types,%handgrade);
                    193:     foreach my $part (@{ $partlist }) {
1.392     albertel  194: 	next if (%vPart && !exists($vPart{$part}));
                    195: 
1.377     albertel  196: 	my @types = $res->responseType($part);
                    197: 	my @ids = $res->responseIds($part);
                    198: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    200: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    202: 				     '.handgrade',$symb);
1.41      ng        203: 	}
                    204:     }
1.377     albertel  205:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        206: }
                    207: 
1.375     albertel  208: sub flatten_responseType {
                    209:     my ($responseType) = @_;
                    210:     my @part_response_id =
                    211: 	map { 
                    212: 	    my $part = $_;
                    213: 	    map {
                    214: 		[$part,$_]
                    215: 		} sort(keys(%{ $responseType->{$part} }));
                    216: 	} sort(keys(%$responseType));
                    217:     return @part_response_id;
                    218: }
                    219: 
1.207     albertel  220: sub get_display_part {
1.324     albertel  221:     my ($partID,$symb)=@_;
1.207     albertel  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    223:     if (defined($display) and $display ne '') {
1.398     albertel  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  225:     } else {
                    226: 	$display=$partID;
                    227:     }
                    228:     return $display;
                    229: }
1.269     raeburn   230: 
1.118     ng        231: #--- Show resource title
                    232: #--- and parts and response type
                    233: sub showResourceInfo {
1.324     albertel  234:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  235:     my $col=3;
                    236:     if ($checkboxes) { $col=4; }
1.398     albertel  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    238:     $result .='<table border="0">';
1.324     albertel  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        240:     my %resptype = ();
1.122     ng        241:     my $hdgrade='no';
1.154     albertel  242:     my %partsseen;
1.524     raeburn   243:     foreach my $partID (sort(keys(%$responseType))) {
                    244: 	foreach my $resID (sort(keys(%{ $responseType->{$partID} }))) {
1.375     albertel  245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    246: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    248: 	    $result.='<tr>';
                    249: 	    if ($checkboxes) {
                    250: 		if (exists($partsseen{$partID})) {
                    251: 		    $result.="<td>&nbsp;</td>";
                    252: 		} else {
1.401     albertel  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  254: 		}
                    255: 		$partsseen{$partID}=1;
1.154     albertel  256: 	    }
1.375     albertel  257: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  258: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  259: 		$resID.'</span></td>'.
1.485     albertel  260: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    261: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  262: 	}
1.118     ng        263:     }
                    264:     $result.='</table>'."\n";
1.147     albertel  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        266: }
                    267: 
1.434     albertel  268: sub reset_caches {
                    269:     &reset_analyze_cache();
                    270:     &reset_perm();
                    271: }
                    272: 
                    273: {
                    274:     my %analyze_cache;
1.148     albertel  275: 
1.434     albertel  276:     sub reset_analyze_cache {
                    277: 	undef(%analyze_cache);
                    278:     }
                    279: 
                    280:     sub get_analyze {
1.525     raeburn   281: 	my ($symb,$uname,$udom,$no_increment)=@_;
1.434     albertel  282: 	my $key = "$symb\0$uname\0$udom";
                    283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    284: 
                    285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    286: 	$url=&Apache::lonnet::clutter($url);
1.513     foxr      287: 	my $subresult=&ssi_with_retries($url, $ssi_retries,
1.516     raeburn   288: 					   ('grade_target' => 'analyze',
                    289: 					    'grade_domain' => $udom,
                    290: 					    'grade_symb' => $symb,
                    291: 					    'grade_courseid' => 
                    292: 					    $env{'request.course.id'},
1.525     raeburn   293: 					    'grade_username' => $uname,
                    294:                                             'grade_noincrement' => $no_increment));
1.434     albertel  295: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    296: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    297: 	return $analyze_cache{$key} = \%analyze;
                    298:     }
                    299: 
                    300:     sub get_order {
1.525     raeburn   301: 	my ($partid,$respid,$symb,$uname,$udom,$no_increment)=@_;
                    302: 	my $analyze = &get_analyze($symb,$uname,$udom,$no_increment);
1.434     albertel  303: 	return $analyze->{"$partid.$respid.shown"};
                    304:     }
                    305: 
                    306:     sub get_radiobutton_correct_foil {
                    307: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    308: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    309: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    310: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    311: 		return $foil;
                    312: 	    }
                    313: 	}
                    314:     }
1.148     albertel  315: }
1.434     albertel  316: 
1.118     ng        317: #--- Clean response type for display
1.335     albertel  318: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    319: #        response types only.
1.118     ng        320: sub cleanRecord {
1.336     albertel  321:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    322: 	$uname,$udom) = @_;
1.398     albertel  323:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  324:     if ($response =~ /^(option|rank)$/) {
                    325: 	my %answer=&Apache::lonnet::str2hash($answer);
                    326: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    327: 	my ($toprow,$bottomrow);
                    328: 	foreach my $foil (@$order) {
                    329: 	    if ($grading{$foil} == 1) {
                    330: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    331: 	    } else {
                    332: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    333: 	    }
1.398     albertel  334: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  335: 	}
                    336: 	return '<blockquote><table border="1">'.
1.466     albertel  337: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    338: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  339: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    340:     } elsif ($response eq 'match') {
                    341: 	my %answer=&Apache::lonnet::str2hash($answer);
                    342: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    343: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    344: 	my ($toprow,$middlerow,$bottomrow);
                    345: 	foreach my $foil (@$order) {
                    346: 	    my $item=shift(@items);
                    347: 	    if ($grading{$foil} == 1) {
                    348: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  349: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  350: 	    } else {
                    351: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  352: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  353: 	    }
1.398     albertel  354: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        355: 	}
1.126     ng        356: 	return '<blockquote><table border="1">'.
1.466     albertel  357: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  359: 	    $middlerow.'</tr>'.
1.466     albertel  360: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  361: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    362:     } elsif ($response eq 'radiobutton') {
                    363: 	my %answer=&Apache::lonnet::str2hash($answer);
                    364: 	my ($toprow,$bottomrow);
1.434     albertel  365: 	my $correct = 
                    366: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    367: 	foreach my $foil (@$order) {
1.148     albertel  368: 	    if (exists($answer{$foil})) {
1.434     albertel  369: 		if ($foil eq $correct) {
1.466     albertel  370: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  371: 		} else {
1.466     albertel  372: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  373: 		}
                    374: 	    } else {
1.466     albertel  375: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  376: 	    }
1.398     albertel  377: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  378: 	}
                    379: 	return '<blockquote><table border="1">'.
1.466     albertel  380: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    381: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  382: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    383:     } elsif ($response eq 'essay') {
1.257     albertel  384: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        385: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  386: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    387: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        388: 
1.257     albertel  389: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    390: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    391: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    392: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    393: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    394: 	    $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        395: 	}
1.166     albertel  396: 	$answer =~ s-\n-<br />-g;
                    397: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  398:     } elsif ( $response eq 'organic') {
                    399: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    400: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    401: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    402: 	return $result;
1.335     albertel  403:     } elsif ( $response eq 'Task') {
                    404: 	if ( $answer eq 'SUBMITTED') {
                    405: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  406: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  407: 	    return $result;
                    408: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    409: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    410: 			       keys(%{$record}));
                    411: 	    return join('<br />',($version,@matches));
                    412: 			       
                    413: 			       
                    414: 	} else {
                    415: 	    my $result =
                    416: 		'<p>'
                    417: 		.&mt('Overall result: [_1]',
                    418: 		     $record->{$version."resource.$respid.$partid.status"})
                    419: 		.'</p>';
                    420: 	    
                    421: 	    $result .= '<ul>';
                    422: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    423: 			     keys(%{$record}));
                    424: 	    foreach my $grade (sort(@grade)) {
                    425: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    426: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    427: 				     $dim, $record->{$grade}).
                    428: 			  '</li>';
                    429: 	    }
                    430: 	    $result.='</ul>';
                    431: 	    return $result;
                    432: 	}
1.440     albertel  433:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    434: 	$answer = 
                    435: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    436: 							      $answer);
1.122     ng        437:     }
1.118     ng        438:     return $answer;
                    439: }
                    440: 
                    441: #-- A couple of common js functions
                    442: sub commonJSfunctions {
                    443:     my $request = shift;
                    444:     $request->print(<<COMMONJSFUNCTIONS);
                    445: <script type="text/javascript" language="javascript">
                    446:     function radioSelection(radioButton) {
                    447: 	var selection=null;
                    448: 	if (radioButton.length > 1) {
                    449: 	    for (var i=0; i<radioButton.length; i++) {
                    450: 		if (radioButton[i].checked) {
                    451: 		    return radioButton[i].value;
                    452: 		}
                    453: 	    }
                    454: 	} else {
                    455: 	    if (radioButton.checked) return radioButton.value;
                    456: 	}
                    457: 	return selection;
                    458:     }
                    459: 
                    460:     function pullDownSelection(selectOne) {
                    461: 	var selection="";
                    462: 	if (selectOne.length > 1) {
                    463: 	    for (var i=0; i<selectOne.length; i++) {
                    464: 		if (selectOne[i].selected) {
                    465: 		    return selectOne[i].value;
                    466: 		}
                    467: 	    }
                    468: 	} else {
1.138     albertel  469:             // only one value it must be the selected one
                    470: 	    return selectOne.value;
1.118     ng        471: 	}
                    472:     }
                    473: </script>
                    474: COMMONJSFUNCTIONS
                    475: }
                    476: 
1.44      ng        477: #--- Dumps the class list with usernames,list of sections,
                    478: #--- section, ids and fullnames for each user.
                    479: sub getclasslist {
1.449     banghart  480:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  481:     my @getsec;
1.450     banghart  482:     my @getgroup;
1.442     banghart  483:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  484:     if (!ref($getsec)) {
                    485: 	if ($getsec ne '' && $getsec ne 'all') {
                    486: 	    @getsec=($getsec);
                    487: 	}
                    488:     } else {
                    489: 	@getsec=@{$getsec};
                    490:     }
                    491:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  492:     if (!ref($getgroup)) {
                    493: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    494: 	    @getgroup=($getgroup);
                    495: 	}
                    496:     } else {
                    497: 	@getgroup=@{$getgroup};
                    498:     }
                    499:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  500: 
1.449     banghart  501:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  502:     # Bail out if we were unable to get the classlist
1.56      matthew   503:     return if (! defined($classlist));
1.449     banghart  504:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   505:     #
                    506:     my %sections;
                    507:     my %fullnames;
1.205     matthew   508:     foreach my $student (keys(%$classlist)) {
                    509:         my $end      = 
                    510:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    511:         my $start    = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    513:         my $id       = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    515:         my $section  = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    517:         my $fullname = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    519:         my $status   = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  521:         my $group   = 
                    522:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        523: 	# filter students according to status selected
1.442     banghart  524: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    525: 	    if (!($stu_status =~ $status)) {
1.450     banghart  526: 		delete($classlist->{$student});
1.76      ng        527: 		next;
                    528: 	    }
                    529: 	}
1.450     banghart  530: 	# filter students according to groups selected
1.453     banghart  531: 	my @stu_groups = split(/,/,$group);
1.450     banghart  532: 	if (@getgroup) {
                    533: 	    my $exclude = 1;
1.454     banghart  534: 	    foreach my $grp (@getgroup) {
                    535: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  536: 	            if ($stu_group eq $grp) {
                    537: 	                $exclude = 0;
                    538:     	            } 
1.450     banghart  539: 	        }
1.453     banghart  540:     	        if (($grp eq 'none') && !$group) {
                    541:         	        $exclude = 0;
                    542:         	}
1.450     banghart  543: 	    }
                    544: 	    if ($exclude) {
                    545: 	        delete($classlist->{$student});
                    546: 	    }
                    547: 	}
1.205     matthew   548: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  549: 	if (&canview($section)) {
1.291     albertel  550: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  551: 		$sections{$section}++;
1.450     banghart  552: 		if ($classlist->{$student}) {
                    553: 		    $fullnames{$student}=$fullname;
                    554: 		}
1.103     albertel  555: 	    } else {
1.205     matthew   556: 		delete($classlist->{$student});
1.103     albertel  557: 	    }
                    558: 	} else {
1.205     matthew   559: 	    delete($classlist->{$student});
1.103     albertel  560: 	}
1.44      ng        561:     }
                    562:     my %seen = ();
1.56      matthew   563:     my @sections = sort(keys(%sections));
                    564:     return ($classlist,\@sections,\%fullnames);
1.44      ng        565: }
                    566: 
1.103     albertel  567: sub canmodify {
                    568:     my ($sec)=@_;
                    569:     if ($perm{'mgr'}) {
                    570: 	if (!defined($perm{'mgr_section'})) {
                    571: 	    # can modify whole class
                    572: 	    return 1;
                    573: 	} else {
                    574: 	    if ($sec eq $perm{'mgr_section'}) {
                    575: 		#can modify the requested section
                    576: 		return 1;
                    577: 	    } else {
                    578: 		# can't modify the request section
                    579: 		return 0;
                    580: 	    }
                    581: 	}
                    582:     }
                    583:     #can't modify
                    584:     return 0;
                    585: }
                    586: 
                    587: sub canview {
                    588:     my ($sec)=@_;
                    589:     if ($perm{'vgr'}) {
                    590: 	if (!defined($perm{'vgr_section'})) {
                    591: 	    # can modify whole class
                    592: 	    return 1;
                    593: 	} else {
                    594: 	    if ($sec eq $perm{'vgr_section'}) {
                    595: 		#can modify the requested section
                    596: 		return 1;
                    597: 	    } else {
                    598: 		# can't modify the request section
                    599: 		return 0;
                    600: 	    }
                    601: 	}
                    602:     }
                    603:     #can't modify
                    604:     return 0;
                    605: }
                    606: 
1.44      ng        607: #--- Retrieve the grade status of a student for all the parts
                    608: sub student_gradeStatus {
1.324     albertel  609:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  610:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        611:     my %partstatus = ();
                    612:     foreach (@$partlist) {
1.128     ng        613: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        614: 	$status              = 'nothing' if ($status eq '');
                    615: 	$partstatus{$_}      = $status;
                    616: 	my $subkey           = "resource.$_.submitted_by";
                    617: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    618:     }
                    619:     return %partstatus;
                    620: }
                    621: 
1.45      ng        622: # hidden form and javascript that calls the form
                    623: # Use by verifyscript and viewgrades
                    624: # Shows a student's view of problem and submission
                    625: sub jscriptNform {
1.324     albertel  626:     my ($symb) = @_;
1.442     banghart  627:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        628:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    629: 	'    function viewOneStudent(user,domain) {'."\n".
                    630: 	'	document.onestudent.student.value = user;'."\n".
                    631: 	'	document.onestudent.userdom.value = domain;'."\n".
                    632: 	'	document.onestudent.submit();'."\n".
                    633: 	'    }'."\n".
                    634: 	'</script>'."\n";
                    635:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  636: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  637: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    638: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  639: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        640: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    641: 	'<input type="hidden" name="student" value="" />'."\n".
                    642: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    643: 	'</form>'."\n";
                    644:     return $jscript;
                    645: }
1.39      ng        646: 
1.447     foxr      647: 
                    648: 
1.315     bowersj2  649: # Given the score (as a number [0-1] and the weight) what is the final
                    650: # point value? This function will round to the nearest tenth, third,
                    651: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  652: sub compute_points {
1.315     bowersj2  653:     my ($score, $weight) = @_;
                    654:     
                    655:     my $tolerance = .00001;
                    656:     my $points = $score * $weight;
                    657: 
                    658:     # Check for nearness to 1/x.
                    659:     my $check_for_nearness = sub {
                    660:         my ($factor) = @_;
                    661:         my $num = ($points * $factor) + $tolerance;
                    662:         my $floored_num = floor($num);
1.316     albertel  663:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  664:             return $floored_num / $factor;
                    665:         }
                    666:         return $points;
                    667:     };
                    668: 
                    669:     $points = $check_for_nearness->(10);
                    670:     $points = $check_for_nearness->(3);
                    671:     $points = $check_for_nearness->(4);
                    672:     
                    673:     return $points;
                    674: }
                    675: 
1.44      ng        676: #------------------ End of general use routines --------------------
1.87      www       677: 
                    678: #
                    679: # Find most similar essay
                    680: #
                    681: 
                    682: sub most_similar {
1.426     albertel  683:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       684: 
                    685: # ignore spaces and punctuation
                    686: 
                    687:     $uessay=~s/\W+/ /gs;
                    688: 
1.282     www       689: # ignore empty submissions (occuring when only files are sent)
                    690: 
                    691:     unless ($uessay=~/\w+/) { return ''; }
                    692: 
1.87      www       693: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       694:     my $limit=0.6;
1.87      www       695:     my $sname='';
                    696:     my $sdom='';
                    697:     my $scrsid='';
                    698:     my $sessay='';
                    699: # go through all essays ...
1.426     albertel  700:     foreach my $tkey (keys(%$old_essays)) {
                    701: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       702: # ... except the same student
1.426     albertel  703:         next if (($tname eq $uname) && ($tdom eq $udom));
                    704: 	my $tessay=$old_essays->{$tkey};
                    705: 	$tessay=~s/\W+/ /gs;
1.87      www       706: # String similarity gives up if not even limit
1.426     albertel  707: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       708: # Found one
1.426     albertel  709: 	if ($tsimilar>$limit) {
                    710: 	    $limit=$tsimilar;
                    711: 	    $sname=$tname;
                    712: 	    $sdom=$tdom;
                    713: 	    $scrsid=$tcrsid;
                    714: 	    $sessay=$old_essays->{$tkey};
                    715: 	}
1.87      www       716:     }
1.88      www       717:     if ($limit>0.6) {
1.87      www       718:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    719:     } else {
                    720:        return ('','','','',0);
                    721:     }
                    722: }
                    723: 
1.44      ng        724: #-------------------------------------------------------------------
                    725: 
                    726: #------------------------------------ Receipt Verification Routines
1.45      ng        727: #
1.44      ng        728: #--- Check whether a receipt number is valid.---
                    729: sub verifyreceipt {
                    730:     my $request  = shift;
                    731: 
1.257     albertel  732:     my $courseid = $env{'request.course.id'};
1.184     www       733:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  734: 	$env{'form.receipt'};
1.44      ng        735:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  736:     my ($symb)   = &get_symb($request);
1.44      ng        737: 
1.487     albertel  738:     my $title.=
                    739: 	'<h3><span class="LC_info">'.
                    740: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    741: 	'</span></h3>'."\n".
                    742: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    743: 	'</h4>'."\n";
1.44      ng        744: 
                    745:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   746:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  747:     
                    748:     my $receiptparts=0;
1.390     albertel  749:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    750: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  751:     my $parts=['0'];
1.324     albertel  752:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  753:     
                    754:     my $header = 
                    755: 	&Apache::loncommon::start_data_table().
                    756: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  757: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    758: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    759: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  760:     if ($receiptparts) {
1.487     albertel  761: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  762:     }
                    763:     $header.=
                    764: 	&Apache::loncommon::end_data_table_header_row();
                    765: 
1.294     albertel  766:     foreach (sort 
                    767: 	     {
                    768: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    769: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    770: 		 }
                    771: 		 return $a cmp $b;
                    772: 	     } (keys(%$fullname))) {
1.44      ng        773: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  774: 	foreach my $part (@$parts) {
                    775: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  776: 		$contents.=
                    777: 		    &Apache::loncommon::start_data_table_row().
                    778: 		    '<td>&nbsp;'."\n".
1.177     albertel  779: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  780: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  781: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    782: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    783: 		if ($receiptparts) {
                    784: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    785: 		}
1.486     albertel  786: 		$contents.= 
                    787: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  788: 		
                    789: 		$matches++;
                    790: 	    }
1.44      ng        791: 	}
                    792:     }
                    793:     if ($matches == 0) {
1.487     albertel  794: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        795:     } else {
1.324     albertel  796: 	$string = &jscriptNform($symb).$title.
1.487     albertel  797: 	    '<p>'.
                    798: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    799: 	    '</p>'.
1.486     albertel  800: 	    $header.
                    801: 	    $contents.
                    802: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        803:     }
1.324     albertel  804:     return $string.&show_grading_menu_form($symb);
1.44      ng        805: }
                    806: 
                    807: #--- This is called by a number of programs.
                    808: #--- Called from the Grading Menu - View/Grade an individual student
                    809: #--- Also called directly when one clicks on the subm button 
                    810: #    on the problem page.
1.30      ng        811: sub listStudents {
1.41      ng        812:     my ($request) = shift;
1.49      albertel  813: 
1.324     albertel  814:     my ($symb) = &get_symb($request);
1.257     albertel  815:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    816:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    817:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  818:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  819:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    820:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    821:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    822: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  823: 
1.485     albertel  824:     my $result='<h3><span class="LC_info">&nbsp;'.
                    825: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    826: 	.'</span></h3>';
1.118     ng        827: 
1.324     albertel  828:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  829: 
1.485     albertel  830:     my %lt = ( 'multiple' =>
                    831: 	       "Please select a student or group of students before clicking on the Next button.",
                    832: 	       'single'   =>
                    833: 	       "Please select the student before clicking on the Next button.",
                    834: 	       );
                    835:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        836:     $request->print(<<LISTJAVASCRIPT);
                    837: <script type="text/javascript" language="javascript">
1.110     ng        838:     function checkSelect(checkBox) {
                    839: 	var ctr=0;
                    840: 	var sense="";
                    841: 	if (checkBox.length > 1) {
                    842: 	    for (var i=0; i<checkBox.length; i++) {
                    843: 		if (checkBox[i].checked) {
                    844: 		    ctr++;
                    845: 		}
                    846: 	    }
1.485     albertel  847: 	    sense = '$lt{'multiple'}';
1.110     ng        848: 	} else {
                    849: 	    if (checkBox.checked) {
                    850: 		ctr = 1;
                    851: 	    }
1.485     albertel  852: 	    sense = '$lt{'single'}';
1.110     ng        853: 	}
                    854: 	if (ctr == 0) {
1.485     albertel  855: 	    alert(sense);
1.110     ng        856: 	    return false;
                    857: 	}
                    858: 	document.gradesub.submit();
                    859:     }
                    860: 
                    861:     function reLoadList(formname) {
1.112     ng        862: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        863: 	formname.command.value = 'submission';
                    864: 	formname.submit();
                    865:     }
1.45      ng        866: </script>
                    867: LISTJAVASCRIPT
                    868: 
1.118     ng        869:     &commonJSfunctions($request);
1.41      ng        870:     $request->print($result);
1.39      ng        871: 
1.401     albertel  872:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    873:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  874:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  875: 	"\n".$table;
                    876: 	
                    877:     $gradeTable .= 
                    878: 	'&nbsp;'.
                    879: 	&mt('<b>View Problem Text: </b>[_1]',
                    880: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    881: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                    882: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                    883:     $gradeTable .= 
                    884: 	'&nbsp;'.
                    885: 	&mt('<b>View Answer: </b>[_1]',
                    886: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    887: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                    888: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                    889: 
                    890:     my $submission_options;
1.257     albertel  891:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  892: 	$submission_options.=
                    893: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  894:     }
1.442     banghart  895:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    896:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  897:     $env{'form.Status'} = $saveStatus;
1.485     albertel  898:     $submission_options.=
                    899: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    900: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    901: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    902: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    903:     $gradeTable .= 
                    904: 	'&nbsp;'.
                    905: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                    906: 
                    907:     $gradeTable .= 
                    908:         '&nbsp;'.
                    909: 	&mt('<b>Grading Increments:</b> [_1]',
                    910: 	    '<select name="increment">'.
                    911: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    912: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    913: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    914: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                    915: 	    '</select>');
                    916:     
                    917:     $gradeTable .= 
1.432     banghart  918:         &build_section_inputs().
1.45      ng        919: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  920: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    921: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    922: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    923: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  924: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        925: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    926: 
1.257     albertel  927:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  928: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        929:     } else {
1.485     albertel  930: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    931: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        932:     }
1.112     ng        933: 
1.485     albertel  934:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    935: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        936: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  937: 
                    938: # checkall buttons
                    939:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        940:     $gradeTable.='<input type="button" '."\n".
1.45      ng        941: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel  942: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  943:     $gradeTable.=&check_buttons();
1.485     albertel  944:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  945:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  946:     $gradeTable.= &Apache::loncommon::start_data_table().
                    947: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        948:     my $loop = 0;
                    949:     while ($loop < 2) {
1.485     albertel  950: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    951: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  952: 	if ($env{'form.showgrading'} eq 'yes' 
                    953: 	    && $submitonly ne 'queued'
                    954: 	    && $submitonly ne 'all') {
1.485     albertel  955: 	    foreach my $part (sort(@$partlist)) {
                    956: 		my $display_part=
                    957: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    958: 		$gradeTable.=
                    959: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        960: 	    }
1.301     albertel  961: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  962: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        963: 	}
                    964: 	$loop++;
1.126     ng        965: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        966:     }
1.474     albertel  967:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        968: 
1.45      ng        969:     my $ctr = 0;
1.294     albertel  970:     foreach my $student (sort 
                    971: 			 {
                    972: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    973: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    974: 			     }
                    975: 			     return $a cmp $b;
                    976: 			 }
                    977: 			 (keys(%$fullname))) {
1.41      ng        978: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  979: 
1.110     ng        980: 	my %status = ();
1.301     albertel  981: 
                    982: 	if ($submitonly eq 'queued') {
                    983: 	    my %queue_status = 
                    984: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    985: 							$udom,$uname);
                    986: 	    next if (!defined($queue_status{'gradingqueue'}));
                    987: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    988: 	}
                    989: 
                    990: 	if ($env{'form.showgrading'} eq 'yes' 
                    991: 	    && $submitonly ne 'queued'
                    992: 	    && $submitonly ne 'all') {
1.324     albertel  993: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  994: 	    my $submitted = 0;
1.164     albertel  995: 	    my $graded = 0;
1.248     albertel  996: 	    my $incorrect = 0;
1.110     ng        997: 	    foreach (keys(%status)) {
1.145     albertel  998: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  999: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                   1000: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                   1001: 		
1.110     ng       1002: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1003: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1004: 		    $submitted = 0;
1.150     albertel 1005: 		    my ($part)=split(/\./,$partid);
1.110     ng       1006: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1007: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1008: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1009: 		}
1.41      ng       1010: 	    }
1.248     albertel 1011: 	    
1.156     albertel 1012: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1013: 				     $submitonly eq 'incorrect' ||
                   1014: 				     $submitonly eq 'graded'));
1.248     albertel 1015: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1016: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1017: 	}
1.34      ng       1018: 
1.45      ng       1019: 	$ctr++;
1.249     albertel 1020: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1021:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1022: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1023: 	    if ($ctr%2 ==1) {
                   1024: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1025: 	    }
1.126     ng       1026: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1027:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1028:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1029: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1030: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1031: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1032: 
1.257     albertel 1033: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.524     raeburn  1034: 		foreach (sort(keys(%status))) {
1.485     albertel 1035: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1036: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1037: 		}
1.41      ng       1038: 	    }
1.126     ng       1039: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1040: 	    if ($ctr%2 ==0) {
                   1041: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1042: 	    }
1.41      ng       1043: 	}
                   1044:     }
1.110     ng       1045:     if ($ctr%2 ==1) {
1.126     ng       1046: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1047: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1048: 		&& $submitonly ne 'queued'
                   1049: 		&& $submitonly ne 'all') {
1.110     ng       1050: 		foreach (@$partlist) {
                   1051: 		    $gradeTable.='<td>&nbsp;</td>';
                   1052: 		}
1.301     albertel 1053: 	    } elsif ($submitonly eq 'queued') {
                   1054: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1055: 	    }
1.474     albertel 1056: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1057:     }
                   1058: 
1.474     albertel 1059:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1060: 	'<input type="button" '.
                   1061: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1062: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1063:     if ($ctr == 0) {
1.96      albertel 1064: 	my $num_students=(scalar(keys(%$fullname)));
                   1065: 	if ($num_students eq 0) {
1.485     albertel 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1067: 	} else {
1.171     albertel 1068: 	    my $submissions='submissions';
                   1069: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1070: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1071: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1072: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1073: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1074: 		    $num_students).
                   1075: 		'</span><br />';
1.96      albertel 1076: 	}
1.46      ng       1077:     } elsif ($ctr == 1) {
1.474     albertel 1078: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1079:     }
1.324     albertel 1080:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1081:     $request->print($gradeTable);
1.44      ng       1082:     return '';
1.10      ng       1083: }
                   1084: 
1.44      ng       1085: #---- Called from the listStudents routine
1.249     albertel 1086: 
                   1087: sub check_script {
                   1088:     my ($form, $type)=@_;
                   1089:     my $chkallscript='<script type="text/javascript">
                   1090:     function checkall() {
                   1091:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1092:             ele = document.forms.'.$form.'.elements[i];
                   1093:             if (ele.name == "'.$type.'") {
                   1094:             document.forms.'.$form.'.elements[i].checked=true;
                   1095:                                        }
                   1096:         }
                   1097:     }
                   1098: 
                   1099:     function checksec() {
                   1100:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1101:             ele = document.forms.'.$form.'.elements[i];
                   1102:            string = document.forms.'.$form.'.chksec.value;
                   1103:            if
                   1104:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1105:               document.forms.'.$form.'.elements[i].checked=true;
                   1106:             }
                   1107:         }
                   1108:     }
                   1109: 
                   1110: 
                   1111:     function uncheckall() {
                   1112:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1113:             ele = document.forms.'.$form.'.elements[i];
                   1114:             if (ele.name == "'.$type.'") {
                   1115:             document.forms.'.$form.'.elements[i].checked=false;
                   1116:                                        }
                   1117:         }
                   1118:     }
                   1119: 
                   1120: </script>'."\n";
                   1121:     return $chkallscript;
                   1122: }
                   1123: 
                   1124: sub check_buttons {
1.485     albertel 1125:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1126:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1127:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1128:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1129:     return $buttons;
                   1130: }
                   1131: 
1.44      ng       1132: #     Displays the submissions for one student or a group of students
1.34      ng       1133: sub processGroup {
1.41      ng       1134:     my ($request)  = shift;
                   1135:     my $ctr        = 0;
1.155     albertel 1136:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1137:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1138: 
1.396     banghart 1139:     foreach my $student (@stuchecked) {
                   1140: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1141: 	$env{'form.student'}        = $uname;
                   1142: 	$env{'form.userdom'}        = $udom;
                   1143: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1144: 	&submission($request,$ctr,$total);
                   1145: 	$ctr++;
                   1146:     }
                   1147:     return '';
1.35      ng       1148: }
1.34      ng       1149: 
1.44      ng       1150: #------------------------------------------------------------------------------------
                   1151: #
                   1152: #-------------------------- Next few routines handles grading by student, essentially
                   1153: #                           handles essay response type problem/part
                   1154: #
                   1155: #--- Javascript to handle the submission page functionality ---
                   1156: sub sub_page_js {
                   1157:     my $request = shift;
                   1158:     $request->print(<<SUBJAVASCRIPT);
                   1159: <script type="text/javascript" language="javascript">
1.71      ng       1160:     function updateRadio(formname,id,weight) {
1.125     ng       1161: 	var gradeBox = formname["GD_BOX"+id];
                   1162: 	var radioButton = formname["RADVAL"+id];
                   1163: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1164: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1165: 	gradeBox.value = pts;
                   1166: 	var resetbox = false;
                   1167: 	if (isNaN(pts) || pts < 0) {
                   1168: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1169: 	    for (var i=0; i<radioButton.length; i++) {
                   1170: 		if (radioButton[i].checked) {
                   1171: 		    gradeBox.value = i;
                   1172: 		    resetbox = true;
                   1173: 		}
                   1174: 	    }
                   1175: 	    if (!resetbox) {
                   1176: 		formtextbox.value = "";
                   1177: 	    }
                   1178: 	    return;
1.44      ng       1179: 	}
1.71      ng       1180: 
                   1181: 	if (pts > weight) {
                   1182: 	    var resp = confirm("You entered a value ("+pts+
                   1183: 			       ") greater than the weight for the part. Accept?");
                   1184: 	    if (resp == false) {
1.125     ng       1185: 		gradeBox.value = oldpts;
1.71      ng       1186: 		return;
                   1187: 	    }
1.44      ng       1188: 	}
1.13      albertel 1189: 
1.71      ng       1190: 	for (var i=0; i<radioButton.length; i++) {
                   1191: 	    radioButton[i].checked=false;
                   1192: 	    if (pts == i && pts != "") {
                   1193: 		radioButton[i].checked=true;
                   1194: 	    }
                   1195: 	}
                   1196: 	updateSelect(formname,id);
1.125     ng       1197: 	formname["stores"+id].value = "0";
1.41      ng       1198:     }
1.5       albertel 1199: 
1.72      ng       1200:     function writeBox(formname,id,pts) {
1.125     ng       1201: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1202: 	if (checkSolved(formname,id) == 'update') {
                   1203: 	    gradeBox.value = pts;
                   1204: 	} else {
1.125     ng       1205: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1206: 	    gradeBox.value = oldpts;
1.125     ng       1207: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1208: 	    for (var i=0; i<radioButton.length; i++) {
                   1209: 		radioButton[i].checked=false;
1.72      ng       1210: 		if (i == oldpts) {
1.71      ng       1211: 		    radioButton[i].checked=true;
                   1212: 		}
                   1213: 	    }
1.41      ng       1214: 	}
1.125     ng       1215: 	formname["stores"+id].value = "0";
1.71      ng       1216: 	updateSelect(formname,id);
                   1217: 	return;
1.41      ng       1218:     }
1.44      ng       1219: 
1.71      ng       1220:     function clearRadBox(formname,id) {
                   1221: 	if (checkSolved(formname,id) == 'noupdate') {
                   1222: 	    updateSelect(formname,id);
                   1223: 	    return;
                   1224: 	}
1.125     ng       1225: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1226: 	for (var i=0; i<gradeSelect.length; i++) {
                   1227: 	    if (gradeSelect[i].selected) {
                   1228: 		var selectx=i;
                   1229: 	    }
                   1230: 	}
1.125     ng       1231: 	var stores = formname["stores"+id];
1.71      ng       1232: 	if (selectx == stores.value) { return };
1.125     ng       1233: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1234: 	gradeBox.value = "";
1.125     ng       1235: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1236: 	for (var i=0; i<radioButton.length; i++) {
                   1237: 	    radioButton[i].checked=false;
                   1238: 	}
                   1239: 	stores.value = selectx;
                   1240:     }
1.5       albertel 1241: 
1.71      ng       1242:     function checkSolved(formname,id) {
1.125     ng       1243: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1244: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1245: 	    if (!reply) {return "noupdate";}
1.120     ng       1246: 	    formname.overRideScore.value = 'yes';
1.41      ng       1247: 	}
1.71      ng       1248: 	return "update";
1.13      albertel 1249:     }
1.71      ng       1250: 
                   1251:     function updateSelect(formname,id) {
1.125     ng       1252: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1253: 	return;
1.41      ng       1254:     }
1.33      ng       1255: 
1.121     ng       1256: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1257:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1258: 	formname.gradeOpt.value = val;
1.71      ng       1259: 	if (val == "Save & Next") {
                   1260: 	    for (i=0;i<=total;i++) {
                   1261: 		for (j=0;j<parttot;j++) {
1.125     ng       1262: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1263: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1264: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1265: 			if (points == "") {
1.125     ng       1266: 			    var name = formname["name"+i].value;
1.129     ng       1267: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1268: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1269: 					       ", part "+partid+". Continue?");
1.71      ng       1270: 			    if (resp == false) {
1.125     ng       1271: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1272: 				return false;
                   1273: 			    }
                   1274: 			}
                   1275: 		    }
                   1276: 		    
                   1277: 		}
                   1278: 	    }
                   1279: 	    
                   1280: 	}
1.121     ng       1281: 	if (val == "Grade Student") {
                   1282: 	    formname.showgrading.value = "yes";
                   1283: 	    if (formname.Status.value == "") {
                   1284: 		formname.Status.value = "Active";
                   1285: 	    }
                   1286: 	    formname.studentNo.value = total;
                   1287: 	}
1.120     ng       1288: 	formname.submit();
                   1289:     }
                   1290: 
1.71      ng       1291: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1292:     function checkSubmitPage(formname,total) {
                   1293: 	noscore = new Array(100);
                   1294: 	var ptr = 0;
                   1295: 	for (i=1;i<total;i++) {
1.125     ng       1296: 	    var partid = formname["q_"+i].value;
1.127     ng       1297: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1298: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1299: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1300: 		if (points == "" && status != "correct_by_student") {
                   1301: 		    noscore[ptr] = i;
                   1302: 		    ptr++;
                   1303: 		}
                   1304: 	    }
                   1305: 	}
                   1306: 	if (ptr != 0) {
                   1307: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1308: 	    var prolist = "";
                   1309: 	    if (ptr == 1) {
                   1310: 		prolist = noscore[0];
                   1311: 	    } else {
                   1312: 		var i = 0;
                   1313: 		while (i < ptr-1) {
                   1314: 		    prolist += noscore[i]+", ";
                   1315: 		    i++;
                   1316: 		}
                   1317: 		prolist += "and "+noscore[i];
                   1318: 	    }
                   1319: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1320: 	    if (resp == false) {
                   1321: 		return false;
                   1322: 	    }
                   1323: 	}
1.45      ng       1324: 
1.71      ng       1325: 	formname.submit();
                   1326:     }
                   1327: </script>
                   1328: SUBJAVASCRIPT
                   1329: }
1.45      ng       1330: 
1.71      ng       1331: #--- javascript for essay type problem --
                   1332: sub sub_page_kw_js {
                   1333:     my $request = shift;
1.80      ng       1334:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1335:     &commonJSfunctions($request);
1.350     albertel 1336: 
1.351     albertel 1337:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1338:     <script text="text/javascript">
                   1339:     function checkInput() {
                   1340:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1341:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1342:       var usrctr = document.msgcenter.usrctr.value;
                   1343:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1344:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1345: 
                   1346:       var msgchk = "";
                   1347:       if (document.msgcenter.subchk.checked) {
                   1348:          msgchk = "msgsub,";
                   1349:       }
                   1350:       var includemsg = 0;
                   1351:       for (var i=1; i<=nmsg; i++) {
                   1352:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1353:           var frmmsg = document.msgcenter["msg"+i];
                   1354:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1355:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1356:           showflg.value = "1";
                   1357:           var chkbox = document.msgcenter["msgn"+i];
                   1358:           if (chkbox.checked) {
                   1359:              msgchk += "savemsg"+i+",";
                   1360:              includemsg = 1;
                   1361:           }
                   1362:       }
                   1363:       if (document.msgcenter.newmsgchk.checked) {
                   1364:          msgchk += "newmsg"+usrctr;
                   1365:          includemsg = 1;
                   1366:       }
                   1367:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1368:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1369:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1370:       includemsg.value = msgchk;
                   1371: 
                   1372:       self.close()
                   1373: 
                   1374:     }
                   1375:     </script>
                   1376: INNERJS
                   1377: 
1.351     albertel 1378:     my $inner_js_highlight_central=<<INNERJS;
                   1379:  <script type="text/javascript">
                   1380:     function updateChoice(flag) {
                   1381:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1382:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1383:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1384:       opener.document.SCORE.refresh.value = "on";
                   1385:       if (opener.document.SCORE.keywords.value!=""){
                   1386:          opener.document.SCORE.submit();
                   1387:       }
                   1388:       self.close()
                   1389:     }
                   1390: </script>
                   1391: INNERJS
                   1392: 
                   1393:     my $start_page_msg_central = 
                   1394:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1395: 				       {'js_ready'  => 1,
                   1396: 					'only_body' => 1,
                   1397: 					'bgcolor'   =>'#FFFFFF',});
                   1398:     my $end_page_msg_central = 
                   1399: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1400: 
                   1401: 
                   1402:     my $start_page_highlight_central = 
                   1403:         &Apache::loncommon::start_page('Highlight Central',
                   1404: 				       $inner_js_highlight_central,
1.350     albertel 1405: 				       {'js_ready'  => 1,
                   1406: 					'only_body' => 1,
                   1407: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1408:     my $end_page_highlight_central = 
1.350     albertel 1409: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1410: 
1.219     www      1411:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1412:     $docopen=~s/^document\.//;
1.71      ng       1413:     $request->print(<<SUBJAVASCRIPT);
                   1414: <script type="text/javascript" language="javascript">
1.45      ng       1415: 
1.44      ng       1416: //===================== Show list of keywords ====================
1.122     ng       1417:   function keywords(formname) {
                   1418:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1419:     if (nret==null) return;
1.122     ng       1420:     formname.keywords.value = nret;
1.44      ng       1421: 
1.122     ng       1422:     if (formname.keywords.value != "") {
1.128     ng       1423: 	formname.refresh.value = "on";
1.122     ng       1424: 	formname.submit();
1.44      ng       1425:     }
                   1426:     return;
                   1427:   }
                   1428: 
                   1429: //===================== Script to view submitted by ==================
                   1430:   function viewSubmitter(submitter) {
                   1431:     document.SCORE.refresh.value = "on";
                   1432:     document.SCORE.NCT.value = "1";
                   1433:     document.SCORE.unamedom0.value = submitter;
                   1434:     document.SCORE.submit();
                   1435:     return;
                   1436:   }
                   1437: 
                   1438: //===================== Script to add keyword(s) ==================
                   1439:   function getSel() {
                   1440:     if (document.getSelection) txt = document.getSelection();
                   1441:     else if (document.selection) txt = document.selection.createRange().text;
                   1442:     else return;
                   1443:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1444:     if (cleantxt=="") {
1.46      ng       1445: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1446: 	return;
                   1447:     }
                   1448:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1449:     if (nret==null) return;
1.127     ng       1450:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1451:     if (document.SCORE.keywords.value != "") {
1.127     ng       1452: 	document.SCORE.refresh.value = "on";
1.44      ng       1453: 	document.SCORE.submit();
                   1454:     }
                   1455:     return;
                   1456:   }
                   1457: 
                   1458: //====================== Script for composing message ==============
1.80      ng       1459:    // preload images
                   1460:    img1 = new Image();
                   1461:    img1.src = "$iconpath/mailbkgrd.gif";
                   1462:    img2 = new Image();
                   1463:    img2.src = "$iconpath/mailto.gif";
                   1464: 
1.44      ng       1465:   function msgCenter(msgform,usrctr,fullname) {
                   1466:     var Nmsg  = msgform.savemsgN.value;
                   1467:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1468:     var subject = msgform.msgsub.value;
1.127     ng       1469:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1470:     re = /msgsub/;
                   1471:     var shwsel = "";
                   1472:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1473:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1474:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1475:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1476: 	var testmsg = "savemsg"+i+",";
                   1477: 	re = new RegExp(testmsg,"g");
1.44      ng       1478: 	shwsel = "";
                   1479: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1480: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1481: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1482: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1483: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1484:     }
1.125     ng       1485:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1486:     shwsel = "";
                   1487:     re = /newmsg/;
                   1488:     if (re.test(msgchk)) { shwsel = "checked" }
                   1489:     newMsg(newmsg,shwsel);
                   1490:     msgTail(); 
                   1491:     return;
                   1492:   }
                   1493: 
1.123     ng       1494:   function checkEntities(strx) {
                   1495:     if (strx.length == 0) return strx;
                   1496:     var orgStr = ["&", "<", ">", '"']; 
                   1497:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1498:     var counter = 0;
                   1499:     while (counter < 4) {
                   1500: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1501: 	counter++;
                   1502:     }
                   1503:     return strx;
                   1504:   }
                   1505: 
                   1506:   function strReplace(strx, orgStr, newStr) {
                   1507:     return strx.split(orgStr).join(newStr);
                   1508:   }
                   1509: 
1.44      ng       1510:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1511:     var height = 70*Nmsg+250;
1.44      ng       1512:     var scrollbar = "no";
                   1513:     if (height > 600) {
                   1514: 	height = 600;
                   1515: 	scrollbar = "yes";
                   1516:     }
1.118     ng       1517:     var xpos = (screen.width-600)/2;
                   1518:     xpos = (xpos < 0) ? '0' : xpos;
                   1519:     var ypos = (screen.height-height)/2-30;
                   1520:     ypos = (ypos < 0) ? '0' : ypos;
                   1521: 
1.206     albertel 1522:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1523:     pWin.focus();
                   1524:     pDoc = pWin.document;
1.219     www      1525:     pDoc.$docopen;
1.351     albertel 1526:     pDoc.write('$start_page_msg_central');
1.76      ng       1527: 
                   1528:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1529:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1530:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1531: 
                   1532:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1533:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1534:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1535: }
                   1536:     function displaySubject(msg,shwsel) {
1.76      ng       1537:     pDoc = pWin.document;
                   1538:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1539:     pDoc.write("<td>Subject<\\/td>");
                   1540:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1541:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1542: }
                   1543: 
1.72      ng       1544:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1545:     pDoc = pWin.document;
                   1546:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1547:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1548:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1549:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1550: }
                   1551: 
                   1552:   function newMsg(newmsg,shwsel) {
1.76      ng       1553:     pDoc = pWin.document;
                   1554:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1555:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1556:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1557:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1558: }
                   1559: 
                   1560:   function msgTail() {
1.76      ng       1561:     pDoc = pWin.document;
1.465     albertel 1562:     pDoc.write("<\\/table>");
                   1563:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1564:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1565:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1566:     pDoc.write("<\\/form>");
1.351     albertel 1567:     pDoc.write('$end_page_msg_central');
1.128     ng       1568:     pDoc.close();
1.44      ng       1569: }
                   1570: 
                   1571: //====================== Script for keyword highlight options ==============
                   1572:   function kwhighlight() {
                   1573:     var kwclr    = document.SCORE.kwclr.value;
                   1574:     var kwsize   = document.SCORE.kwsize.value;
                   1575:     var kwstyle  = document.SCORE.kwstyle.value;
                   1576:     var redsel = "";
                   1577:     var grnsel = "";
                   1578:     var blusel = "";
                   1579:     if (kwclr=="red")   {var redsel="checked"};
                   1580:     if (kwclr=="green") {var grnsel="checked"};
                   1581:     if (kwclr=="blue")  {var blusel="checked"};
                   1582:     var sznsel = "";
                   1583:     var sz1sel = "";
                   1584:     var sz2sel = "";
                   1585:     if (kwsize=="0")  {var sznsel="checked"};
                   1586:     if (kwsize=="+1") {var sz1sel="checked"};
                   1587:     if (kwsize=="+2") {var sz2sel="checked"};
                   1588:     var synsel = "";
                   1589:     var syisel = "";
                   1590:     var sybsel = "";
                   1591:     if (kwstyle=="")    {var synsel="checked"};
                   1592:     if (kwstyle=="<i>") {var syisel="checked"};
                   1593:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1594:     highlightCentral();
                   1595:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1596:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1597:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1598:     highlightend();
                   1599:     return;
                   1600:   }
                   1601: 
                   1602:   function highlightCentral() {
1.76      ng       1603: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1604:     var xpos = (screen.width-400)/2;
                   1605:     xpos = (xpos < 0) ? '0' : xpos;
                   1606:     var ypos = (screen.height-330)/2-30;
                   1607:     ypos = (ypos < 0) ? '0' : ypos;
                   1608: 
1.206     albertel 1609:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1610:     hwdWin.focus();
                   1611:     var hDoc = hwdWin.document;
1.219     www      1612:     hDoc.$docopen;
1.351     albertel 1613:     hDoc.write('$start_page_highlight_central');
1.76      ng       1614:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1615:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1616: 
                   1617:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1618:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1619:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1620:   }
                   1621: 
                   1622:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1623:     var hDoc = hwdWin.document;
                   1624:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1625:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1626:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1627:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1628:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1629:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1630:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1631:     hDoc.write("<\\/tr>");
1.44      ng       1632:   }
                   1633: 
                   1634:   function highlightend() { 
1.76      ng       1635:     var hDoc = hwdWin.document;
1.465     albertel 1636:     hDoc.write("<\\/table>");
                   1637:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1638:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1639:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1640:     hDoc.write("<\\/form>");
1.351     albertel 1641:     hDoc.write('$end_page_highlight_central');
1.128     ng       1642:     hDoc.close();
1.44      ng       1643:   }
                   1644: 
                   1645: </script>
                   1646: SUBJAVASCRIPT
                   1647: }
                   1648: 
1.349     albertel 1649: sub get_increment {
1.348     bowersj2 1650:     my $increment = $env{'form.increment'};
                   1651:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1652:         $increment != .1) {
                   1653:         $increment = 1;
                   1654:     }
                   1655:     return $increment;
                   1656: }
                   1657: 
1.71      ng       1658: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1659: sub gradeBox {
1.322     albertel 1660:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1661:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1662: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1663:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1664:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1665:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1666:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1667:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1668: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1669:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1670:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1671:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1672: 				       [$partid]);
                   1673:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1674:     if ($last_resets{$partid}) {
                   1675:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1676:     }
1.485     albertel 1677:     $result.='<table border="0"><tr>';
1.71      ng       1678:     my $ctr = 0;
1.348     bowersj2 1679:     my $thisweight = 0;
1.349     albertel 1680:     my $increment = &get_increment();
1.485     albertel 1681: 
                   1682:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1683:     while ($thisweight<=$wgt) {
1.485     albertel 1684: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1685: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1686: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1687: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1688: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1689:         $thisweight += $increment;
1.71      ng       1690: 	$ctr++;
                   1691:     }
1.485     albertel 1692:     $radio.='</tr></table>';
                   1693: 
                   1694:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1695: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1696: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1697: 	$wgt.')" /></td>'."\n";
1.485     albertel 1698:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1699: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1700: 	' </td><td>'."\n";
1.485     albertel 1701:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1702: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1703:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1704: 	$line.='<option></option>'.
                   1705: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1706:     } else {
1.485     albertel 1707: 	$line.='<option selected="selected"></option>'.
                   1708: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1709:     }
1.485     albertel 1710:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1711: 
                   1712: 
                   1713:     $result .= 
                   1714: 	&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);
                   1715: 
                   1716:     
                   1717:     $result.='</tr></table>'."\n";
1.71      ng       1718:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1719: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1720: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1721: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1722:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1723:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1724:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1725:         $aggtries.'" />'."\n";
1.323     banghart 1726:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1727:     return $result;
                   1728: }
1.322     albertel 1729: 
                   1730: sub handback_box {
1.323     banghart 1731:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1732:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1733:     my (@respids);
1.375     albertel 1734:      my @part_response_id = &flatten_responseType($responseType);
                   1735:     foreach my $part_response_id (@part_response_id) {
                   1736:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1737:         if ($part eq $partid) {
1.375     albertel 1738:             push(@respids,$resp);
1.323     banghart 1739:         }
                   1740:     }
1.318     banghart 1741:     my $result;
1.323     banghart 1742:     foreach my $respid (@respids) {
1.322     albertel 1743: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1744: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1745: 	next if (!@$files);
                   1746: 	my $file_counter = 1;
1.313     banghart 1747: 	foreach my $file (@$files) {
1.368     banghart 1748: 	    if ($file =~ /\/portfolio\//) {
                   1749:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1750:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1751:     	        $file_disp = "$name.$ext";
                   1752:     	        $file = $file_path.$file_disp;
                   1753:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1754:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1755:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1756:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1757:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1758:     	        $file_counter++;
                   1759: 	    }
1.322     albertel 1760: 	}
1.313     banghart 1761:     }
1.318     banghart 1762:     return $result;    
1.71      ng       1763: }
1.44      ng       1764: 
1.58      albertel 1765: sub show_problem {
1.382     albertel 1766:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1767:     my $rendered;
1.382     albertel 1768:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1769:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1770:     if ($mode eq 'both' or $mode eq 'text') {
                   1771: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1772: 						       $env{'request.course.id'},
                   1773: 						       undef,\%form);
1.144     albertel 1774:     }
1.58      albertel 1775:     if ($removeform) {
                   1776: 	$rendered=~s|<form(.*?)>||g;
                   1777: 	$rendered=~s|</form>||g;
1.374     albertel 1778: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1779:     }
1.144     albertel 1780:     my $companswer;
                   1781:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1782: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1783: 	$companswer=
                   1784: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1785: 						    $env{'request.course.id'},
                   1786: 						    %form);
1.144     albertel 1787:     }
1.58      albertel 1788:     if ($removeform) {
                   1789: 	$companswer=~s|<form(.*?)>||g;
                   1790: 	$companswer=~s|</form>||g;
1.144     albertel 1791: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1792:     }
1.468     albertel 1793:     $rendered=
                   1794: 	'<div class="LC_grade_show_problem_header">'.
                   1795: 	&mt('View of the problem').
                   1796: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1797: 	$rendered.
                   1798: 	'</div>';
                   1799:     $companswer=
                   1800: 	'<div class="LC_grade_show_problem_header">'.
                   1801: 	&mt('Correct answer').
                   1802: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1803: 	$companswer.
                   1804: 	'</div>';
                   1805:     my $result;
1.144     albertel 1806:     if ($mode eq 'both') {
1.468     albertel 1807: 	$result=$rendered.$companswer;
1.144     albertel 1808:     } elsif ($mode eq 'text') {
1.468     albertel 1809: 	$result=$rendered;
1.144     albertel 1810:     } elsif ($mode eq 'answer') {
1.468     albertel 1811: 	$result=$companswer;
1.144     albertel 1812:     }
1.468     albertel 1813:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1814:     return $result;
1.58      albertel 1815: }
1.397     albertel 1816: 
1.396     banghart 1817: sub files_exist {
                   1818:     my ($r, $symb) = @_;
                   1819:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1820: 
1.396     banghart 1821:     foreach my $student (@students) {
                   1822:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1823:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1824: 					      $udom,$uname);
1.396     banghart 1825:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1826:         foreach my $submission (@$string) {
                   1827:             my ($partid,$respid) =
                   1828: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1829:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1830: 					   \%record);
                   1831:             return 1 if (@$files);
1.396     banghart 1832:         }
                   1833:     }
1.397     albertel 1834:     return 0;
1.396     banghart 1835: }
1.397     albertel 1836: 
1.394     banghart 1837: sub download_all_link {
                   1838:     my ($r,$symb) = @_;
1.395     albertel 1839:     my $all_students = 
                   1840: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1841: 
                   1842:     my $parts =
                   1843: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1844: 
1.394     banghart 1845:     my $identifier = &Apache::loncommon::get_cgi_id();
1.514     raeburn  1846:     &Apache::lonnet::appenv({'cgi.'.$identifier.'.students' => $all_students,
                   1847:                              'cgi.'.$identifier.'.symb' => $symb,
                   1848:                              'cgi.'.$identifier.'.parts' => $parts,});
1.395     albertel 1849:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1850: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1851:     return
                   1852: }
1.395     albertel 1853: 
1.432     banghart 1854: sub build_section_inputs {
                   1855:     my $section_inputs;
                   1856:     if ($env{'form.section'} eq '') {
                   1857:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1858:     } else {
                   1859:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1860:         foreach my $section (@sections) {
1.432     banghart 1861:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1862:         }
                   1863:     }
                   1864:     return $section_inputs;
                   1865: }
                   1866: 
1.44      ng       1867: # --------------------------- show submissions of a student, option to grade 
                   1868: sub submission {
                   1869:     my ($request,$counter,$total) = @_;
1.257     albertel 1870:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1871:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1872:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1873:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1874:     my $symb = &get_symb($request); 
                   1875:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1876: 
                   1877:     if (!&canview($usec)) {
1.398     albertel 1878: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1879: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1880: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1881: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1882: 	return;
                   1883:     }
                   1884: 
1.257     albertel 1885:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1886:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1887:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1888:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1889:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1890: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1891: 	'/check.gif" height="16" border="0" />';
1.41      ng       1892: 
1.426     albertel 1893:     my %old_essays;
1.41      ng       1894:     # header info
                   1895:     if ($counter == 0) {
                   1896: 	&sub_page_js($request);
1.257     albertel 1897: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1898: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1899: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1900: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1901: 	    &download_all_link($request, $symb);
                   1902: 	}
1.485     albertel 1903: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1904: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1905: 
1.44      ng       1906: 	# option to display problem, only once else it cause problems 
                   1907:         # with the form later since the problem has a form.
1.257     albertel 1908: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1909: 	    my $mode;
1.257     albertel 1910: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1911: 		$mode='both';
1.257     albertel 1912: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1913: 		$mode='text';
1.257     albertel 1914: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1915: 		$mode='answer';
                   1916: 	    }
1.329     albertel 1917: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1918: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1919: 	}
1.441     www      1920: 
1.44      ng       1921: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1922:         # if this subroutine has been called once.
1.41      ng       1923: 	my %keyhash = ();
1.257     albertel 1924: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1925: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1926: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1927: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1928: 
1.257     albertel 1929: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1930: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1931: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1932: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1933: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1934: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1935: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1936: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1937: 	}
1.257     albertel 1938: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1939: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1940: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1941: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1942: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1943: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1944: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1945: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1946: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1947: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1948: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1949: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1950: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1951: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1952: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1953: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1954: 			&build_section_inputs().
1.326     albertel 1955: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1956: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1957: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1958: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1959: 	if ($env{'form.handgrade'} eq 'yes') {
                   1960: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1961: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1962: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1963: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1964: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1965: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1966: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1967: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1968: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1969: 	    }
1.123     ng       1970: 	}
1.41      ng       1971: 	
                   1972: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1973: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1974: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1975: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1976: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1977: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1978: 		'" />'."\n".
                   1979: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1980: 	    $cts++;
                   1981: 	}
                   1982: 	$request->print($prnmsg);
1.32      ng       1983: 
1.257     albertel 1984: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1985: #
                   1986: # Print out the keyword options line
                   1987: #
1.41      ng       1988: 	    $request->print(<<KEYWORDS);
1.38      ng       1989: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1990: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1991: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1992:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1993: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1994: KEYWORDS
1.88      www      1995: #
                   1996: # Load the other essays for similarity check
                   1997: #
1.324     albertel 1998:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1999: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      2000: 	    $apath=&escape($apath);
1.88      www      2001: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2002: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2003:         }
                   2004:     }
1.44      ng       2005: 
1.441     www      2006: # This is where output for one specific student would start
1.468     albertel 2007:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2008:     $request->print("\n\n".
1.468     albertel 2009:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2010: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2011: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2012: 
1.257     albertel 2013:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2014: 	my $mode;
1.257     albertel 2015: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2016: 	    $mode='both';
1.257     albertel 2017: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2018: 	    $mode='text';
1.257     albertel 2019: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2020: 	    $mode='answer';
                   2021: 	}
1.329     albertel 2022: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2023: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2024:     }
1.144     albertel 2025: 
1.257     albertel 2026:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2027:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2028: 
1.44      ng       2029:     # Display student info
1.41      ng       2030:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2031:     my $result='<div class="LC_grade_submissions">';
                   2032:     
                   2033:     $result.='<div class="LC_grade_submissions_header">';
                   2034:     $result.= &mt('Submissions');
1.45      ng       2035:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2036: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2037:     if ($env{'form.handgrade'} eq 'no') {
                   2038: 	$result.='<span class="LC_grade_check_note">'.
                   2039: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2040: 
                   2041:     }
                   2042: 
                   2043: 
1.41      ng       2044: 
1.118     ng       2045:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2046:     my $fullname;
                   2047:     my $col_fullnames = [];
1.257     albertel 2048:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2049: 	(my $sub_result,$fullname,$col_fullnames)=
                   2050: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2051: 				 $counter);
                   2052: 	$result.=$sub_result;
1.41      ng       2053:     }
1.44      ng       2054:     $request->print($result."\n");
1.468     albertel 2055:     $request->print('</div>'."\n");
1.44      ng       2056:     # print student answer/submission
                   2057:     # Options are (1) Handgaded submission only
                   2058:     #             (2) Last submission, includes submission that is not handgraded 
                   2059:     #                  (for multi-response type part)
                   2060:     #             (3) Last submission plus the parts info
                   2061:     #             (4) The whole record for this student
1.257     albertel 2062:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2063: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2064: 	
                   2065: 	my $lastsubonly;
                   2066: 
1.151     albertel 2067: 	if ($$timestamp eq '') {
1.468     albertel 2068: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2069: 	} else {
1.468     albertel 2070: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2071: 
1.151     albertel 2072: 	    my %seenparts;
1.375     albertel 2073: 	    my @part_response_id = &flatten_responseType($responseType);
                   2074: 	    foreach my $part (@part_response_id) {
1.393     albertel 2075: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2076: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2077: 
1.375     albertel 2078: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2079: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2080: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2081: 		    if (exists($seenparts{$partid})) { next; }
                   2082: 		    $seenparts{$partid}=1;
1.207     albertel 2083: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2084: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2085: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2086: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2087: 			'\');" target="_self">'.
1.257     albertel 2088: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2089: 		    $request->print($submitby);
                   2090: 		    next;
                   2091: 		}
                   2092: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2093: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2094: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2095: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2096: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2097: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2098: 		    next;
                   2099: 		}
1.468     albertel 2100: 		foreach my $submission (@$string) {
                   2101: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2102: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2103: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2104: 		    # Similarity check
                   2105: 		    my $similar='';
1.257     albertel 2106: 		    if($env{'form.checkPlag'}){
1.151     albertel 2107: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2108: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2109: 			if ($osim) {
                   2110: 			    $osim=int($osim*100.0);
1.426     albertel 2111: 			    my %old_course_desc = 
                   2112: 				&Apache::lonnet::coursedescription($ocrsid,
                   2113: 								   {'one_time' => 1});
                   2114: 
                   2115: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2116: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2117: 				    $osim,
                   2118: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2119: 				    $oname,$odom,
1.426     albertel 2120: 				    $old_course_desc{'description'},
1.427     albertel 2121: 				    $old_course_desc{'num'},
1.426     albertel 2122: 				    $old_course_desc{'domain'}).
1.398     albertel 2123: 				'</span></h3><blockquote><i>'.
1.151     albertel 2124: 				&keywords_highlight($oessay).
                   2125: 				'</i></blockquote><hr />';
                   2126: 			}
1.150     albertel 2127: 		    }
1.151     albertel 2128: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2129: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2130: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2131: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2132: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2133: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2134: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2135: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2136: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2137: 			if (@$files) {
1.468     albertel 2138: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2139: 			    my $file_counter = 0;
1.313     banghart 2140: 			    foreach my $file (@$files) {
1.468     albertel 2141: 			        $file_counter++;
1.232     albertel 2142: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2143: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2144: 			    }
1.236     albertel 2145: 			    $lastsubonly.='<br />';
1.41      ng       2146: 			}
1.468     albertel 2147: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2148: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2149: 					 $respid,\%record,$order);
                   2150: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2151: 			$lastsubonly.='</div>';
1.41      ng       2152: 		    }
                   2153: 		}
                   2154: 	    }
1.468     albertel 2155: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2156: 	}
                   2157: 	$request->print($lastsubonly);
1.468     albertel 2158:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2159: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2160: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2161:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2162: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2163: 								 $env{'request.course.id'},
1.44      ng       2164: 								 $last,'.submission',
                   2165: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2166:     }
1.120     ng       2167: 
1.121     ng       2168:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2169: 	.$udom.'" />'."\n");
1.44      ng       2170:     # return if view submission with no grading option
1.257     albertel 2171:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2172: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2173: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2174: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2175: 	$toGrade.='</div>'."\n";
1.257     albertel 2176: 	if (($env{'form.command'} eq 'submission') || 
                   2177: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2178: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2179: 	}
1.180     albertel 2180: 	$request->print($toGrade);
1.41      ng       2181: 	return;
1.180     albertel 2182:     } else {
1.468     albertel 2183: 	$request->print('</div>'."\n");
1.41      ng       2184:     }
1.33      ng       2185: 
1.121     ng       2186:     # essay grading message center
1.257     albertel 2187:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2188: 	my $result='<div class="LC_grade_message_center">';
                   2189:     
                   2190: 	$result.='<div class="LC_grade_message_center_header">'.
                   2191: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2192: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2193: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2194: 	if (scalar(@$col_fullnames) > 0) {
                   2195: 	    my $lastone = pop(@$col_fullnames);
                   2196: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2197: 	}
                   2198: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2199: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2200: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2201: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2202: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2203: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2204: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2205: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2206: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2207: 	    '<br />&nbsp;('.
1.468     albertel 2208: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2209: 	$result.='</div></div>';
1.121     ng       2210: 	$request->print($result);
1.118     ng       2211:     }
1.41      ng       2212: 
                   2213:     my %seen = ();
                   2214:     my @partlist;
1.129     ng       2215:     my @gradePartRespid;
1.375     albertel 2216:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2217:     $request->print('<div class="LC_grade_assign">'.
                   2218: 		    
                   2219: 		    '<div class="LC_grade_assign_header">'.
                   2220: 		    &mt('Assign Grades').'</div>'.
                   2221: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2222:     foreach my $part_response_id (@part_response_id) {
                   2223:     	my ($partid,$respid) = @{ $part_response_id };
                   2224: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2225: 	next if ($seen{$partid} > 0);
1.41      ng       2226: 	$seen{$partid}++;
1.393     albertel 2227: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2228: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.524     raeburn  2229: 	push(@partlist,$partid);
                   2230: 	push(@gradePartRespid,$partid.'.'.$respid);
1.322     albertel 2231: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2232:     }
1.468     albertel 2233:     $request->print('</div></div>');
                   2234: 
                   2235:     $request->print('<div class="LC_grade_info_links">');
                   2236:     if ($perm{'vgr'}) {
                   2237: 	$request->print(
                   2238: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2239: 						   $uname,$udom,'check'));
                   2240:     }
                   2241:     if ($perm{'opa'}) {
                   2242: 	$request->print(
                   2243: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2244: 					 $uname,$udom,$symb,'check'));
                   2245:     }
                   2246:     $request->print('</div>');
                   2247: 
1.45      ng       2248:     $result='<input type="hidden" name="partlist'.$counter.
                   2249: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2250:     $result.='<input type="hidden" name="gradePartRespid'.
                   2251: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2252:     my $ctr = 0;
                   2253:     while ($ctr < scalar(@partlist)) {
                   2254: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2255: 	    $partlist[$ctr].'" />'."\n";
                   2256: 	$ctr++;
                   2257:     }
1.468     albertel 2258:     $request->print($result.''."\n");
1.41      ng       2259: 
1.441     www      2260: # Done with printing info for one student
                   2261: 
1.468     albertel 2262:     $request->print('</div>');#LC_grade_show_user_body
                   2263:     $request->print('</div>');#LC_grade_show_user
1.441     www      2264: 
                   2265: 
1.41      ng       2266:     # print end of form
                   2267:     if ($counter == $total) {
1.297     www      2268: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2269: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2270: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2271: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2272: 	my $ntstu ='<select name="NTSTU">'.
                   2273: 	    '<option>1</option><option>2</option>'.
                   2274: 	    '<option>3</option><option>5</option>'.
                   2275: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2276: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2277: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2278: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2279: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2280: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2281: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2282: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2283: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2284:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2285:             "' name='increment' />";
1.485     albertel 2286: 	$endform.='</td></tr></table></form>';
1.324     albertel 2287: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2288: 	$request->print($endform);
                   2289:     }
                   2290:     return '';
1.38      ng       2291: }
                   2292: 
1.464     albertel 2293: sub check_collaborators {
                   2294:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2295:     my ($result,@col_fullnames);
                   2296:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2297:     foreach my $part (keys(%$handgrade)) {
                   2298: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2299: 					'.maxcollaborators',
                   2300: 					$symb,$udom,$uname);
                   2301: 	next if ($ncol <= 0);
                   2302: 	$part =~ s/\_/\./g;
                   2303: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2304: 	my (@good_collaborators, @bad_collaborators);
                   2305: 	foreach my $possible_collaborator
                   2306: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2307: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2308: 	    next if ($possible_collaborator eq '');
                   2309: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2310: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2311: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2312: 	    # Doing this grep allows 'fuzzy' specification
                   2313: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2314: 			       keys(%$classlist));
                   2315: 	    if (! scalar(@matches)) {
                   2316: 		push(@bad_collaborators, $possible_collaborator);
                   2317: 	    } else {
                   2318: 		push(@good_collaborators, @matches);
                   2319: 	    }
                   2320: 	}
                   2321: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2322: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2323: 	    foreach my $name (@good_collaborators) {
                   2324: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2325: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2326: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2327: 	    }
                   2328: 	    $result.='<br />'."\n";
1.466     albertel 2329: 	    my ($part)=split(/\./,$part);
1.464     albertel 2330: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2331: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2332: 		"\n";
                   2333: 	}
                   2334: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2335: 	    $result.='<div class="LC_warning">';
1.464     albertel 2336: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2337: 	    $result .= '</div>';
                   2338: 	}         
                   2339: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2340: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2341: 	    $result .= &mt('This student has submitted too many '.
                   2342: 		'collaborators.  Maximum is [_1].',$ncol);
                   2343: 	    $result .= '</div>';
                   2344: 	}
                   2345:     }
                   2346:     return ($result,$fullname,\@col_fullnames);
                   2347: }
                   2348: 
1.44      ng       2349: #--- Retrieve the last submission for all the parts
1.38      ng       2350: sub get_last_submission {
1.119     ng       2351:     my ($returnhash)=@_;
1.46      ng       2352:     my (@string,$timestamp);
1.119     ng       2353:     if ($$returnhash{'version'}) {
1.46      ng       2354: 	my %lasthash=();
                   2355: 	my ($version);
1.119     ng       2356: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2357: 	    foreach my $key (sort(split(/\:/,
                   2358: 					$$returnhash{$version.':keys'}))) {
                   2359: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2360: 		$timestamp = 
                   2361: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2362: 	    }
                   2363: 	}
1.397     albertel 2364: 	foreach my $key (keys(%lasthash)) {
                   2365: 	    next if ($key !~ /\.submission$/);
                   2366: 
                   2367: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2368: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2369: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2370: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2371: 	}
                   2372:     }
1.397     albertel 2373:     if (!@string) {
                   2374: 	$string[0] =
1.398     albertel 2375: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2376:     }
                   2377:     return (\@string,\$timestamp);
1.38      ng       2378: }
1.35      ng       2379: 
1.44      ng       2380: #--- High light keywords, with style choosen by user.
1.38      ng       2381: sub keywords_highlight {
1.44      ng       2382:     my $string    = shift;
1.257     albertel 2383:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2384:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2385:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2386:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2387:     foreach my $keyword (@keylist) {
                   2388: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2389:     }
                   2390:     return $string;
1.38      ng       2391: }
1.36      ng       2392: 
1.44      ng       2393: #--- Called from submission routine
1.38      ng       2394: sub processHandGrade {
1.41      ng       2395:     my ($request) = shift;
1.324     albertel 2396:     my $symb   = &get_symb($request);
                   2397:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2398:     my $button = $env{'form.gradeOpt'};
                   2399:     my $ngrade = $env{'form.NCT'};
                   2400:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2401:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2402:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2403: 
1.44      ng       2404:     if ($button eq 'Save & Next') {
                   2405: 	my $ctr = 0;
                   2406: 	while ($ctr < $ngrade) {
1.257     albertel 2407: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2408: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2409: 	    if ($errorflag eq 'no_score') {
                   2410: 		$ctr++;
                   2411: 		next;
                   2412: 	    }
1.104     albertel 2413: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2414: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2415: 		$ctr++;
                   2416: 		next;
                   2417: 	    }
1.257     albertel 2418: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2419: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2420: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2421:             my ($feedurl,$showsymb) =
                   2422: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2423: 	    my $messagetail;
1.62      albertel 2424: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2425: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2426: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2427: 		$subject.=' ['.$restitle.']';
1.44      ng       2428: 		my (@msgnum) = split(/,/,$includemsg);
                   2429: 		foreach (@msgnum) {
1.257     albertel 2430: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2431: 		}
1.80      ng       2432: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2433: 		if ($env{'form.withgrades'.$ctr}) {
                   2434: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2435: 		    $messagetail = " for <a href=\"".
1.418     albertel 2436: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2437: 		}
                   2438: 		$msgstatus = 
                   2439:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2440: 						     $message.$messagetail,
1.418     albertel 2441:                                                      undef,$feedurl,undef,
1.386     raeburn  2442:                                                      undef,undef,$showsymb,
                   2443:                                                      $restitle);
                   2444: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2445: 				$msgstatus);
1.44      ng       2446: 	    }
1.257     albertel 2447: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2448: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2449: 		foreach my $collabstr (@collabstrs) {
                   2450: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2451: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2452: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2453: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2454: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2455: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2456: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2457: 			    next;
1.418     albertel 2458: 			} elsif ($message ne '') {
                   2459: 			    my ($baseurl,$showsymb) = 
                   2460: 				&get_feedurl_and_symb($symb,$collaborator,
                   2461: 						      $udom);
                   2462: 			    if ($env{'form.withgrades'.$ctr}) {
                   2463: 				$messagetail = " for <a href=\"".
1.386     raeburn  2464:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2465: 			    }
1.418     albertel 2466: 			    $msgstatus = 
                   2467: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2468: 			}
1.44      ng       2469: 		    }
                   2470: 		}
                   2471: 	    }
                   2472: 	    $ctr++;
                   2473: 	}
                   2474:     }
                   2475: 
1.257     albertel 2476:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2477: 	# Keywords sorted in alphabatical order
1.257     albertel 2478: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2479: 	my %keyhash = ();
1.257     albertel 2480: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2481: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2482: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2483: 	$env{'form.keywords'} = join(' ',@keywords);
                   2484: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2485: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2486: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2487: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2488: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2489: 
                   2490: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2491: 	# New messages are saved in env for the next student.
1.119     ng       2492: 	# All messages are saved in nohist_handgrade.db
                   2493: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2494: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2495: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2496: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2497: 		$idx++;
                   2498: 	    }
                   2499: 	    $ctr++;
1.41      ng       2500: 	}
1.119     ng       2501: 	$ctr = 0;
                   2502: 	while ($ctr < $ngrade) {
1.257     albertel 2503: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2504: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2505: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2506: 		$idx++;
                   2507: 	    }
                   2508: 	    $ctr++;
1.41      ng       2509: 	}
1.257     albertel 2510: 	$env{'form.savemsgN'} = --$idx;
                   2511: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2512: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2513: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2514:     }
1.44      ng       2515:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2516:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2517:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2518: 	my ($ctr,$total) = (0,0);
                   2519: 	while ($ctr < $ngrade) {
1.257     albertel 2520: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2521: 	    $ctr++;
                   2522: 	}
1.257     albertel 2523: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2524: 	$ctr = 0;
                   2525: 	while ($ctr < $total) {
1.257     albertel 2526: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2527: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2528: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2529: 	    &submission($request,$ctr,$total-1);
1.41      ng       2530: 	    $ctr++;
                   2531: 	}
                   2532: 	return '';
                   2533:     }
1.36      ng       2534: 
1.121     ng       2535: # Go directly to grade student - from submission or link from chart page
1.120     ng       2536:     if ($button eq 'Grade Student') {
1.324     albertel 2537: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2538: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2539: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2540: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2541: 	&submission($request,0,0);
                   2542: 	return '';
                   2543:     }
                   2544: 
1.44      ng       2545:     # Get the next/previous one or group of students
1.257     albertel 2546:     my $firststu = $env{'form.unamedom0'};
                   2547:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2548:     my $ctr = 2;
1.41      ng       2549:     while ($laststu eq '') {
1.257     albertel 2550: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2551: 	$ctr++;
                   2552: 	$laststu = $firststu if ($ctr > $ngrade);
                   2553:     }
1.44      ng       2554: 
1.41      ng       2555:     my (@parsedlist,@nextlist);
                   2556:     my ($nextflg) = 0;
1.524     raeburn  2557:     foreach my $item (sort 
1.294     albertel 2558: 	     {
                   2559: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2560: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2561: 		 }
                   2562: 		 return $a cmp $b;
                   2563: 	     } (keys(%$fullname))) {
1.41      ng       2564: 	if ($nextflg == 1 && $button =~ /Next$/) {
1.524     raeburn  2565: 	    push(@parsedlist,$item);
1.41      ng       2566: 	}
1.524     raeburn  2567: 	$nextflg = 1 if ($item eq $laststu);
1.41      ng       2568: 	if ($button eq 'Previous') {
1.524     raeburn  2569: 	    last if ($item eq $firststu);
                   2570: 	    push(@parsedlist,$item);
1.41      ng       2571: 	}
                   2572:     }
                   2573:     $ctr = 0;
                   2574:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2575:     my ($partlist) = &response_type($symb);
1.41      ng       2576:     foreach my $student (@parsedlist) {
1.257     albertel 2577: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2578: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2579: 	
                   2580: 	if ($submitonly eq 'queued') {
                   2581: 	    my %queue_status = 
                   2582: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2583: 							$udom,$uname);
                   2584: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2585: 	}
                   2586: 
1.156     albertel 2587: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2588: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2589: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2590: 	    my $submitted = 0;
1.248     albertel 2591: 	    my $ungraded = 0;
                   2592: 	    my $incorrect = 0;
1.524     raeburn  2593: 	    foreach my $item (keys(%status)) {
                   2594: 		$submitted = 1 if ($status{$item} ne 'nothing');
                   2595: 		$ungraded = 1 if ($status{$item} =~ /^ungraded/);
                   2596: 		$incorrect = 1 if ($status{$item} =~ /^incorrect/);
                   2597: 		my ($foo,$partid,$foo1) = split(/\./,$item);
1.145     albertel 2598: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2599: 		    $submitted = 0;
                   2600: 		}
1.41      ng       2601: 	    }
1.156     albertel 2602: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2603: 				     $submitonly eq 'incorrect' ||
                   2604: 				     $submitonly eq 'graded'));
1.248     albertel 2605: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2606: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2607: 	}
1.524     raeburn  2608: 	push(@nextlist,$student) if ($ctr < $ntstu);
1.129     ng       2609: 	last if ($ctr == $ntstu);
1.41      ng       2610: 	$ctr++;
                   2611:     }
1.36      ng       2612: 
1.41      ng       2613:     $ctr = 0;
                   2614:     my $total = scalar(@nextlist)-1;
1.39      ng       2615: 
1.524     raeburn  2616:     foreach (sort(@nextlist)) {
1.41      ng       2617: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2618: 	$env{'form.student'}  = $uname;
                   2619: 	$env{'form.userdom'}  = $udom;
                   2620: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2621: 	&submission($request,$ctr,$total);
                   2622: 	$ctr++;
                   2623:     }
                   2624:     if ($total < 0) {
1.485     albertel 2625: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2626: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2627: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2628: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2629: 	$request->print($the_end);
                   2630:     }
                   2631:     return '';
1.38      ng       2632: }
1.36      ng       2633: 
1.44      ng       2634: #---- Save the score and award for each student, if changed
1.38      ng       2635: sub saveHandGrade {
1.324     albertel 2636:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2637:     my @version_parts;
1.104     albertel 2638:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2639: 					   $env{'request.course.id'});
1.104     albertel 2640:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2641:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2642:     my @parts_graded;
1.77      ng       2643:     my %newrecord  = ();
                   2644:     my ($pts,$wgt) = ('','');
1.269     raeburn  2645:     my %aggregate = ();
                   2646:     my $aggregateflag = 0;
1.301     albertel 2647:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2648:     foreach my $new_part (@parts) {
1.337     banghart 2649: 	#collaborator ($submi may vary for different parts
1.259     banghart 2650: 	if ($submitter && $new_part ne $part) { next; }
                   2651: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2652: 	if ($dropMenu eq 'excused') {
1.259     banghart 2653: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2654: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2655: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2656: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2657: 		}
1.364     banghart 2658: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2659: 	    }
1.125     ng       2660: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2661: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.524     raeburn  2662: 	    foreach my $key (keys(%record)) {
1.259     banghart 2663: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2664: 	    }
1.259     banghart 2665: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2666: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2667:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2668: 
                   2669:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2670: 					       [$new_part]);
                   2671:             my $aggtries =$totaltries;
1.269     raeburn  2672:             if ($last_resets{$new_part}) {
1.270     albertel 2673:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2674: 					   $new_part);
1.269     raeburn  2675:             }
1.270     albertel 2676: 
                   2677:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2678:             if ($aggtries > 0) {
1.327     albertel 2679:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2680:                 $aggregateflag = 1;
                   2681:             }
1.125     ng       2682: 	} elsif ($dropMenu eq '') {
1.259     banghart 2683: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2684: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2685: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2686: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2687: 		next;
                   2688: 	    }
1.259     banghart 2689: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2690: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2691: 	    my $partial= $pts/$wgt;
1.259     banghart 2692: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2693: 		#do not update score for part if not changed.
1.346     banghart 2694:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2695: 		next;
1.251     banghart 2696: 	    } else {
1.524     raeburn  2697: 	        push(@parts_graded,$new_part);
1.153     albertel 2698: 	    }
1.259     banghart 2699: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2700: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2701: 	    }
1.259     banghart 2702: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2703: 	    if ($partial == 0) {
1.153     albertel 2704: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2705: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2706: 		}
1.41      ng       2707: 	    } else {
1.153     albertel 2708: 		if ($record{$reckey} ne 'correct_by_override') {
                   2709: 		    $newrecord{$reckey} = 'correct_by_override';
                   2710: 		}
                   2711: 	    }	    
                   2712: 	    if ($submitter && 
1.259     banghart 2713: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2714: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2715: 	    }
1.259     banghart 2716: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2717: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2718: 	}
1.259     banghart 2719: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2720: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2721: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2722: 	        $dropMenu eq 'reset status')
                   2723: 	   {
1.524     raeburn  2724: 	    push(@version_parts,$new_part);
1.259     banghart 2725: 	}
1.41      ng       2726:     }
1.301     albertel 2727:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2728:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2729: 
1.344     albertel 2730:     if (%newrecord) {
                   2731:         if (@version_parts) {
1.364     banghart 2732:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2733:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2734: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2735: 	    foreach my $new_part (@version_parts) {
                   2736: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2737: 				$new_part,\%newrecord);
                   2738: 	    }
1.259     banghart 2739:         }
1.44      ng       2740: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2741: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2742: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2743: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2744:     }
1.269     raeburn  2745:     if ($aggregateflag) {
                   2746:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2747: 			      $cdom,$cnum);
1.269     raeburn  2748:     }
1.301     albertel 2749:     return ('',$pts,$wgt);
1.36      ng       2750: }
1.322     albertel 2751: 
1.380     albertel 2752: sub check_and_remove_from_queue {
                   2753:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2754:     my @ungraded_parts;
                   2755:     foreach my $part (@{$parts}) {
                   2756: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2757: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2758: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2759: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2760: 		) {
                   2761: 	    push(@ungraded_parts, $part);
                   2762: 	}
                   2763:     }
                   2764:     if ( !@ungraded_parts ) {
                   2765: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2766: 					       $cnum,$domain,$stuname);
                   2767:     }
                   2768: }
                   2769: 
1.337     banghart 2770: sub handback_files {
                   2771:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.517     raeburn  2772:     my $portfolio_root = '/userfiles/portfolio';
1.359     www      2773:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2774: 
                   2775:     my @part_response_id = &flatten_responseType($responseType);
                   2776:     foreach my $part_response_id (@part_response_id) {
                   2777:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2778: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2779:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2780:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2781:                 my $file_counter = 1;
1.367     albertel 2782: 		my $file_msg;
1.337     banghart 2783:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2784:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2785:                     my ($directory,$answer_file) = 
                   2786:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2787:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2788: 		        &file_name_version_ext($answer_file);
1.355     banghart 2789: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.517     raeburn  2790:                     my $getpropath = 1;
                   2791: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$portfolio_path,$domain,$stuname,$getpropath);
1.338     banghart 2792: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2793:                     # fix file name
                   2794:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2795:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2796:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2797:             	                                $save_file_name);
1.337     banghart 2798:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2799:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2800:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2801:                     } else {
1.360     banghart 2802:                         # mark the file as read only
                   2803:                         my @files = ($save_file_name);
1.372     albertel 2804:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2805:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2806: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2807: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2808: 			}
                   2809:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2810: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2811: 
1.337     banghart 2812:                     }
                   2813:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2814:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2815:                     $file_counter++;
                   2816:                 }
1.367     albertel 2817: 		my $subject = "File Handed Back by Instructor ";
                   2818: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2819: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2820: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2821: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2822: 		my ($feedurl,$showsymb) = 
                   2823: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2824:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2825: 		my $msgstatus = 
                   2826:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2827: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2828:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2829:             }
                   2830:         }
1.338     banghart 2831:     return;
1.337     banghart 2832: }
                   2833: 
1.418     albertel 2834: sub get_feedurl_and_symb {
                   2835:     my ($symb,$uname,$udom) = @_;
                   2836:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2837:     $url = &Apache::lonnet::clutter($url);
                   2838:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2839: 					$symb,$udom,$uname);
                   2840:     if ($encrypturl =~ /^yes$/i) {
                   2841: 	&Apache::lonenc::encrypted(\$url,1);
                   2842: 	&Apache::lonenc::encrypted(\$symb,1);
                   2843:     }
                   2844:     return ($url,$symb);
                   2845: }
                   2846: 
1.313     banghart 2847: sub get_submitted_files {
                   2848:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2849:     my @files;
                   2850:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2851:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2852:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2853:     	    push(@files,$file_url.$file);
                   2854:         }
                   2855:     }
                   2856:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2857:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2858:     }
                   2859:     return (\@files);
                   2860: }
1.322     albertel 2861: 
1.269     raeburn  2862: # ----------- Provides number of tries since last reset.
                   2863: sub get_num_tries {
                   2864:     my ($record,$last_reset,$part) = @_;
                   2865:     my $timestamp = '';
                   2866:     my $num_tries = 0;
                   2867:     if ($$record{'version'}) {
                   2868:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2869:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2870:                 $timestamp = $$record{$version.':timestamp'};
                   2871:                 if ($timestamp > $last_reset) {
                   2872:                     $num_tries ++;
                   2873:                 } else {
                   2874:                     last;
                   2875:                 }
                   2876:             }
                   2877:         }
                   2878:     }
                   2879:     return $num_tries;
                   2880: }
                   2881: 
                   2882: # ----------- Determine decrements required in aggregate totals 
                   2883: sub decrement_aggs {
                   2884:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2885:     my %decrement = (
                   2886:                         attempts => 0,
                   2887:                         users => 0,
                   2888:                         correct => 0
                   2889:                     );
                   2890:     $decrement{'attempts'} = $aggtries;
                   2891:     if ($solvedstatus =~ /^correct/) {
                   2892:         $decrement{'correct'} = 1;
                   2893:     }
                   2894:     if ($aggtries == $totaltries) {
                   2895:         $decrement{'users'} = 1;
                   2896:     }
1.524     raeburn  2897:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2898:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2899:     }
                   2900:     return;
                   2901: }
                   2902: 
                   2903: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2904: sub get_last_resets {
1.270     albertel 2905:     my ($symb,$courseid,$partids) =@_;
                   2906:     my %last_resets;
1.269     raeburn  2907:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2908:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2909:     my @keys;
                   2910:     foreach my $part (@{$partids}) {
                   2911: 	push(@keys,"$symb\0$part\0resettime");
                   2912:     }
                   2913:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2914: 				     $cdom,$cname);
                   2915:     foreach my $part (@{$partids}) {
                   2916: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2917:     }
1.270     albertel 2918:     return %last_resets;
1.269     raeburn  2919: }
                   2920: 
1.251     banghart 2921: # ----------- Handles creating versions for portfolio files as answers
                   2922: sub version_portfiles {
1.343     banghart 2923:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2924:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2925:     my @returned_keys;
1.255     banghart 2926:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2927:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2928:     foreach my $key (keys(%$record)) {
1.259     banghart 2929:         my $new_portfiles;
1.263     banghart 2930:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2931:             my @versioned_portfiles;
1.367     albertel 2932:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2933:             foreach my $file (@portfiles) {
1.306     banghart 2934:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2935:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2936: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2937: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2938:                 my $getpropath = 1;    
                   2939:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2940:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2941:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2942:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2943:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2944:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2945:                         [$directory.$new_answer],
1.306     banghart 2946:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2947:                 }
1.252     banghart 2948:             }
1.343     banghart 2949:             $$record{$key} = join(',',@versioned_portfiles);
                   2950:             push(@returned_keys,$key);
1.251     banghart 2951:         }
                   2952:     } 
1.343     banghart 2953:     return (@returned_keys);   
1.305     banghart 2954: }
                   2955: 
1.307     banghart 2956: sub get_next_version {
1.341     banghart 2957:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2958:     my $version;
                   2959:     foreach my $row (@$dir_list) {
                   2960:         my ($file) = split(/\&/,$row,2);
                   2961:         my ($file_name,$file_version,$file_ext) =
                   2962: 	    &file_name_version_ext($file);
                   2963:         if (($file_name eq $answer_name) && 
                   2964: 	    ($file_ext eq $answer_ext)) {
                   2965:                 # gets here if filename and extension match, regardless of version
                   2966:                 if ($file_version ne '') {
                   2967:                 # a versioned file is found  so save it for later
                   2968:                 if ($file_version > $version) {
                   2969: 		    $version = $file_version;
                   2970: 	        }
                   2971:             }
                   2972:         }
                   2973:     } 
                   2974:     $version ++;
                   2975:     return($version);
                   2976: }
                   2977: 
1.305     banghart 2978: sub version_selected_portfile {
1.306     banghart 2979:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2980:     my ($answer_name,$answer_ver,$answer_ext) =
                   2981:         &file_name_version_ext($file_name);
                   2982:     my $new_answer;
                   2983:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2984:     if($env{'form.copy'} eq '-1') {
                   2985:         $new_answer = 'problem getting file';
                   2986:     } else {
                   2987:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2988:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2989:                             $stu_name,$domain,'copy',
                   2990: 		        '/portfolio'.$directory.$new_answer);
                   2991:     }    
                   2992:     return ($new_answer);
1.251     banghart 2993: }
                   2994: 
1.304     albertel 2995: sub file_name_version_ext {
                   2996:     my ($file)=@_;
                   2997:     my @file_parts = split(/\./, $file);
                   2998:     my ($name,$version,$ext);
                   2999:     if (@file_parts > 1) {
                   3000: 	$ext=pop(@file_parts);
                   3001: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3002: 	    $version=pop(@file_parts);
                   3003: 	}
                   3004: 	$name=join('.',@file_parts);
                   3005:     } else {
                   3006: 	$name=join('.',@file_parts);
                   3007:     }
                   3008:     return($name,$version,$ext);
                   3009: }
                   3010: 
1.44      ng       3011: #--------------------------------------------------------------------------------------
                   3012: #
                   3013: #-------------------------- Next few routines handles grading by section or whole class
                   3014: #
                   3015: #--- Javascript to handle grading by section or whole class
1.42      ng       3016: sub viewgrades_js {
                   3017:     my ($request) = shift;
                   3018: 
1.41      ng       3019:     $request->print(<<VIEWJAVASCRIPT);
                   3020: <script type="text/javascript" language="javascript">
1.45      ng       3021:    function writePoint(partid,weight,point) {
1.125     ng       3022: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3023: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3024: 	if (point == "textval") {
1.125     ng       3025: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3026: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3027: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3028: 		var resetbox = false;
                   3029: 		for (var i=0; i<radioButton.length; i++) {
                   3030: 		    if (radioButton[i].checked) {
                   3031: 			textbox.value = i;
                   3032: 			resetbox = true;
                   3033: 		    }
                   3034: 		}
                   3035: 		if (!resetbox) {
                   3036: 		    textbox.value = "";
                   3037: 		}
                   3038: 		return;
                   3039: 	    }
1.109     matthew  3040: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3041: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3042: 				   ") greater than the weight for the part. Accept?");
                   3043: 		if (resp == false) {
                   3044: 		    textbox.value = "";
                   3045: 		    return;
                   3046: 		}
                   3047: 	    }
1.42      ng       3048: 	    for (var i=0; i<radioButton.length; i++) {
                   3049: 		radioButton[i].checked=false;
1.109     matthew  3050: 		if (parseFloat(point) == i) {
1.42      ng       3051: 		    radioButton[i].checked=true;
                   3052: 		}
                   3053: 	    }
1.41      ng       3054: 
1.42      ng       3055: 	} else {
1.125     ng       3056: 	    textbox.value = parseFloat(point);
1.42      ng       3057: 	}
1.41      ng       3058: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3059: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3060: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3061: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3062: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3063: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3064: 	    if (saveval != "correct") {
                   3065: 		scorename.value = point;
1.43      ng       3066: 		if (selname[0].selected != true) {
                   3067: 		    selname[0].selected = true;
                   3068: 		}
1.42      ng       3069: 	    }
                   3070: 	}
1.125     ng       3071: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3072:     }
                   3073: 
                   3074:     function writeRadText(partid,weight) {
1.125     ng       3075: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3076: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3077:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3078: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3079: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3080: 	    for (var i=0; i<radioButton.length; i++) {
                   3081: 		radioButton[i].checked=false;
                   3082: 
                   3083: 	    }
                   3084: 	    textbox.value = "";
                   3085: 
                   3086: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3087: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3088: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3089: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3090: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3091: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3092: 		if ((saveval != "correct") || override) {
1.42      ng       3093: 		    scorename.value = "";
1.125     ng       3094: 		    if (selval[1].selected) {
                   3095: 			selname[1].selected = true;
                   3096: 		    } else {
                   3097: 			selname[2].selected = true;
                   3098: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3099: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3100: 		    }
1.42      ng       3101: 		}
                   3102: 	    }
1.43      ng       3103: 	} else {
                   3104: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3105: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3106: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3107: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3108: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3109: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3110: 		if ((saveval != "correct") || override) {
1.125     ng       3111: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3112: 		    selname[0].selected = true;
                   3113: 		}
                   3114: 	    }
                   3115: 	}	    
1.42      ng       3116:     }
                   3117: 
                   3118:     function changeSelect(partid,user) {
1.125     ng       3119: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3120: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3121: 	var point  = textbox.value;
1.125     ng       3122: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3123: 
1.109     matthew  3124: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3125: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3126: 	    textbox.value = "";
                   3127: 	    return;
                   3128: 	}
1.109     matthew  3129: 	if (parseFloat(point) > parseFloat(weight)) {
                   3130: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3131: 			       ") greater than the weight of the part. Accept?");
                   3132: 	    if (resp == false) {
                   3133: 		textbox.value = "";
                   3134: 		return;
                   3135: 	    }
                   3136: 	}
1.42      ng       3137: 	selval[0].selected = true;
                   3138:     }
                   3139: 
                   3140:     function changeOneScore(partid,user) {
1.125     ng       3141: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3142: 	if (selval[1].selected || selval[2].selected) {
                   3143: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3144: 	    if (selval[2].selected) {
                   3145: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3146: 	    }
1.269     raeburn  3147:         }
1.42      ng       3148:     }
                   3149: 
                   3150:     function resetEntry(numpart) {
                   3151: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3152: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3153: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3154: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3155: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3156: 	    for (var i=0; i<radioButton.length; i++) {
                   3157: 		radioButton[i].checked=false;
                   3158: 
                   3159: 	    }
                   3160: 	    textbox.value = "";
                   3161: 	    selval[0].selected = true;
                   3162: 
                   3163: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3164: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3165: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3166: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3167: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3168: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3169: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3170: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3171: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3172: 		if (saveselval == "excused") {
1.43      ng       3173: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3174: 		} else {
1.43      ng       3175: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3176: 		}
                   3177: 	    }
1.41      ng       3178: 	}
1.42      ng       3179:     }
                   3180: 
1.41      ng       3181: </script>
                   3182: VIEWJAVASCRIPT
1.42      ng       3183: }
                   3184: 
1.44      ng       3185: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3186: sub viewgrades {
                   3187:     my ($request) = shift;
                   3188:     &viewgrades_js($request);
1.41      ng       3189: 
1.324     albertel 3190:     my ($symb) = &get_symb($request);
1.168     albertel 3191:     #need to make sure we have the correct data for later EXT calls, 
                   3192:     #thus invalidate the cache
                   3193:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3194:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3195:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3196:     &Apache::lonnet::clear_EXT_cache_status();
                   3197: 
1.398     albertel 3198:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3199:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3200: 
                   3201:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3202:     $result.=&jscriptNform($symb);
1.41      ng       3203: 
1.44      ng       3204:     #beginning of class grading form
1.442     banghart 3205:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3206:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3207: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3208: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3209: 	&build_section_inputs().
1.257     albertel 3210: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3211: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3212: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3213: 
1.126     ng       3214:     my $sectionClass;
1.430     banghart 3215:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3216:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3217: 	$sectionClass='Class';
1.257     albertel 3218:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3219: 	$sectionClass='Students in no Section';
1.52      albertel 3220:     } else {
1.485     albertel 3221: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3222:     }
1.485     albertel 3223:     $result.=
                   3224: 	'<h3>'.
                   3225: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3226:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3227:     #radio buttons/text box for assigning points for a section or class.
                   3228:     #handles different parts of a problem
1.375     albertel 3229:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3230:     my %weight = ();
                   3231:     my $ctsparts = 0;
1.45      ng       3232:     my %seen = ();
1.375     albertel 3233:     my @part_response_id = &flatten_responseType($responseType);
                   3234:     foreach my $part_response_id (@part_response_id) {
                   3235:     	my ($partid,$respid) = @{ $part_response_id };
                   3236: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3237: 	next if $seen{$partid};
                   3238: 	$seen{$partid}++;
1.375     albertel 3239: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3240: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3241: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3242: 
1.324     albertel 3243: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3244: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3245: 	my $ctr = 0;
1.42      ng       3246: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3247: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3248: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3249: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3250: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3251: 	    $ctr++;
                   3252: 	}
1.485     albertel 3253: 	$radio.='</tr></table>';
                   3254: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3255: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3256: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3257: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3258: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3259: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3260: 		$weight{$partid}.')"> '.
1.401     albertel 3261: 	    '<option selected="selected"> </option>'.
1.485     albertel 3262: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3263: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3264: 	    '</select></td>'.
                   3265:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3266: 	$line.='<input type="hidden" name="partid_'.
                   3267: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3268: 	$line.='<input type="hidden" name="weight_'.
                   3269: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3270: 
                   3271: 	$result.=
                   3272: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3273: 	    &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).
                   3274: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3275: 	$ctsparts++;
1.41      ng       3276:     }
1.474     albertel 3277:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3278: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3279:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3280: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3281: 
1.44      ng       3282:     #table listing all the students in a section/class
                   3283:     #header of table
1.485     albertel 3284:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3285: 			 $section_display).'</h3>';
1.474     albertel 3286:     $result.= &Apache::loncommon::start_data_table().
                   3287: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3288: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3289: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3290:     my (@parts) = sort(&getpartlist($symb));
                   3291:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3292:     my @partids = ();
1.41      ng       3293:     foreach my $part (@parts) {
                   3294: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3295: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3296: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3297: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3298:         push(@partids,$partid);
1.324     albertel 3299: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3300: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3301: 	    $result.='<th>'.
                   3302: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3303: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3304: 	    next;
1.485     albertel 3305: 	    
1.207     albertel 3306: 	} else {
1.485     albertel 3307: 	    if ($display =~ /Problem Status/) {
                   3308: 		my $grade_status_mt = &mt('Grade Status');
                   3309: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3310: 	    }
                   3311: 	    my $part_mt = &mt('Part:');
                   3312: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3313: 	}
1.485     albertel 3314: 
1.474     albertel 3315: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3316:     }
1.474     albertel 3317:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3318: 
1.270     albertel 3319:     my %last_resets = 
                   3320: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3321: 
1.41      ng       3322:     #get info for each student
1.44      ng       3323:     #list all the students - with points and grade status
1.257     albertel 3324:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3325:     my $ctr = 0;
1.294     albertel 3326:     foreach (sort 
                   3327: 	     {
                   3328: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3329: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3330: 		 }
                   3331: 		 return $a cmp $b;
                   3332: 	     } (keys(%$fullname))) {
1.126     ng       3333: 	$ctr++;
1.324     albertel 3334: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3335: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3336:     }
1.474     albertel 3337:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3338:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3339:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3340: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3341:     if (scalar(%$fullname) eq 0) {
                   3342: 	my $colspan=3+scalar(@parts);
1.433     banghart 3343: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3344:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3345: 	$result='<span class="LC_warning">'.
1.485     albertel 3346: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3347: 	        $section_display, $stu_status).
1.433     banghart 3348: 	    '</span>';
1.96      albertel 3349:     }
1.324     albertel 3350:     $result.=&show_grading_menu_form($symb);
1.41      ng       3351:     return $result;
                   3352: }
                   3353: 
1.44      ng       3354: #--- call by previous routine to display each student
1.41      ng       3355: sub viewstudentgrade {
1.324     albertel 3356:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3357:     my ($uname,$udom) = split(/:/,$student);
                   3358:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3359:     my %aggregates = (); 
1.474     albertel 3360:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3361: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3362: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3363: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3364: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3365: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3366:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3367:     foreach my $apart (@$parts) {
                   3368: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3369: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3370:         $result.='<td align="center">';
1.269     raeburn  3371:         my ($aggtries,$totaltries);
                   3372:         unless (exists($aggregates{$part})) {
1.270     albertel 3373: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3374: 
                   3375: 	    $aggtries = $totaltries;
1.269     raeburn  3376:             if ($$last_resets{$part}) {  
1.270     albertel 3377:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3378: 					   $part);
                   3379:             }
1.269     raeburn  3380:             $result.='<input type="hidden" name="'.
                   3381:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3382:             $result.='<input type="hidden" name="'.
                   3383:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3384:             $aggregates{$part} = 1;
                   3385:         }
1.41      ng       3386: 	if ($type eq 'awarded') {
1.320     albertel 3387: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3388: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3389: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3390: 	    $result.='<input type="text" name="'.
1.89      albertel 3391: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3392: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3393: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3394: 	} elsif ($type eq 'solved') {
                   3395: 	    my ($status,$foo)=split(/_/,$score,2);
                   3396: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3397: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3398: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3399: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3400: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3401: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3402: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3403: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3404: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3405: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3406: 	} else {
                   3407: 	    $result.='<input type="hidden" name="'.
                   3408: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3409: 		    "\n";
1.233     albertel 3410: 	    $result.='<input type="text" name="'.
1.122     ng       3411: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3412: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3413: 	}
                   3414:     }
1.474     albertel 3415:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3416:     return $result;
1.38      ng       3417: }
                   3418: 
1.44      ng       3419: #--- change scores for all the students in a section/class
                   3420: #    record does not get update if unchanged
1.38      ng       3421: sub editgrades {
1.41      ng       3422:     my ($request) = @_;
                   3423: 
1.324     albertel 3424:     my $symb=&get_symb($request);
1.433     banghart 3425:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3426:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3427:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3428:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3429: 
1.477     albertel 3430:     my $result= &Apache::loncommon::start_data_table().
                   3431: 	&Apache::loncommon::start_data_table_header_row().
                   3432: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3433: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3434:     my %scoreptr = (
                   3435: 		    'correct'  =>'correct_by_override',
                   3436: 		    'incorrect'=>'incorrect_by_override',
                   3437: 		    'excused'  =>'excused',
                   3438: 		    'ungraded' =>'ungraded_attempted',
                   3439: 		    'nothing'  => '',
                   3440: 		    );
1.257     albertel 3441:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3442: 
1.44      ng       3443:     my (@partid);
                   3444:     my %weight = ();
1.54      albertel 3445:     my %columns = ();
1.44      ng       3446:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3447: 
1.324     albertel 3448:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3449:     my $header;
1.257     albertel 3450:     while ($ctr < $env{'form.totalparts'}) {
                   3451: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3452: 	push(@partid,$partid);
1.257     albertel 3453: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3454: 	$ctr++;
1.54      albertel 3455:     }
1.324     albertel 3456:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3457:     foreach my $partid (@partid) {
1.478     albertel 3458: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3459: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3460: 	$columns{$partid}=2;
                   3461: 	foreach my $stores (@parts) {
                   3462: 	    my ($part,$type) = &split_part_type($stores);
                   3463: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3464: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3465: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3466: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3467: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3468: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3469: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3470: 	    $columns{$partid}+=2;
                   3471: 	}
                   3472:     }
                   3473:     foreach my $partid (@partid) {
1.324     albertel 3474: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3475: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3476: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3477: 	    '</th>';
1.54      albertel 3478: 
1.44      ng       3479:     }
1.477     albertel 3480:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3481: 	&Apache::loncommon::start_data_table_header_row().
                   3482: 	$header.
                   3483: 	&Apache::loncommon::end_data_table_header_row();
                   3484:     my @noupdate;
1.126     ng       3485:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3486:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3487: 	my $line;
1.257     albertel 3488: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3489: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3490: 	my %newrecord;
                   3491: 	my $updateflag = 0;
1.281     albertel 3492: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3493: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3494: 	if (!&canmodify($usec)) {
1.126     ng       3495: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3496: 	    push(@noupdate,
1.478     albertel 3497: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3498: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3499: 	    next;
                   3500: 	}
1.269     raeburn  3501:         my %aggregate = ();
                   3502:         my $aggregateflag = 0;
1.281     albertel 3503: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3504: 	foreach (@partid) {
1.257     albertel 3505: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3506: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3507: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3508: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3509: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3510: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3511: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3512: 	    my $score;
                   3513: 	    if ($partial eq '') {
1.257     albertel 3514: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3515: 	    } elsif ($partial > 0) {
                   3516: 		$score = 'correct_by_override';
                   3517: 	    } elsif ($partial == 0) {
                   3518: 		$score = 'incorrect_by_override';
                   3519: 	    }
1.257     albertel 3520: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3521: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3522: 
1.292     albertel 3523: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3524: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3525: 	    if ($dropMenu eq 'reset status' &&
                   3526: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3527: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3528: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3529: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3530: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3531: 		$updateflag = 1;
1.269     raeburn  3532:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3533:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3534:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3535:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3536:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3537:                     $aggregateflag = 1;
                   3538:                 }
1.139     albertel 3539: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3540: 		$updateflag = 1;
                   3541: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3542: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3543: 		$rec_update++;
1.125     ng       3544: 	    }
                   3545: 
1.93      albertel 3546: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3547: 		'<td align="center">'.$awarded.
                   3548: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3549: 
1.54      albertel 3550: 
                   3551: 	    my $partid=$_;
                   3552: 	    foreach my $stores (@parts) {
                   3553: 		my ($part,$type) = &split_part_type($stores);
                   3554: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3555: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3556: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3557: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3558: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3559: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3560: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3561: 		    $updateflag=1;
                   3562: 		}
1.93      albertel 3563: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3564: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3565: 	    }
1.44      ng       3566: 	}
1.477     albertel 3567: 	$line.="\n";
1.301     albertel 3568: 
                   3569: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3570: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3571: 
1.44      ng       3572: 	if ($updateflag) {
                   3573: 	    $count++;
1.257     albertel 3574: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3575: 				    $udom,$uname);
1.301     albertel 3576: 
                   3577: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3578: 					      $cnum,$udom,$uname)) {
                   3579: 		# need to figure out if should be in queue.
                   3580: 		my %record =  
                   3581: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3582: 					     $udom,$uname);
                   3583: 		my $all_graded = 1;
                   3584: 		my $none_graded = 1;
                   3585: 		foreach my $part (@parts) {
                   3586: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3587: 			$all_graded = 0;
                   3588: 		    } else {
                   3589: 			$none_graded = 0;
                   3590: 		    }
                   3591: 		}
                   3592: 
                   3593: 		if ($all_graded || $none_graded) {
                   3594: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3595: 							   $symb,$cdom,$cnum,
                   3596: 							   $udom,$uname);
                   3597: 		}
                   3598: 	    }
                   3599: 
1.477     albertel 3600: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3601: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3602: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3603: 	    $updateCtr++;
1.93      albertel 3604: 	} else {
1.477     albertel 3605: 	    push(@noupdate,
                   3606: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3607: 	    $noupdateCtr++;
1.44      ng       3608: 	}
1.269     raeburn  3609:         if ($aggregateflag) {
                   3610:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3611: 				  $cdom,$cnum);
1.269     raeburn  3612:         }
1.93      albertel 3613:     }
1.477     albertel 3614:     if (@noupdate) {
1.126     ng       3615: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3616: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3617: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3618: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3619: 	    &mt('No Changes Occurred For the Students Below').
                   3620: 	    '</td>'.
1.477     albertel 3621: 	    &Apache::loncommon::end_data_table_row();
                   3622: 	foreach my $line (@noupdate) {
                   3623: 	    $result.=
                   3624: 		&Apache::loncommon::start_data_table_row().
                   3625: 		$line.
                   3626: 		&Apache::loncommon::end_data_table_row();
                   3627: 	}
1.44      ng       3628:     }
1.477     albertel 3629:     $result .= &Apache::loncommon::end_data_table().
                   3630: 	&show_grading_menu_form($symb);
1.478     albertel 3631:     my $msg = '<p><b>'.
                   3632: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3633: 	    $rec_update,$count).'</b><br />'.
                   3634: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3635: 	'</b></p>';
1.44      ng       3636:     return $title.$msg.$result;
1.5       albertel 3637: }
1.54      albertel 3638: 
                   3639: sub split_part_type {
                   3640:     my ($partstr) = @_;
                   3641:     my ($temp,@allparts)=split(/_/,$partstr);
                   3642:     my $type=pop(@allparts);
1.439     albertel 3643:     my $part=join('_',@allparts);
1.54      albertel 3644:     return ($part,$type);
                   3645: }
                   3646: 
1.44      ng       3647: #------------- end of section for handling grading by section/class ---------
                   3648: #
                   3649: #----------------------------------------------------------------------------
                   3650: 
1.5       albertel 3651: 
1.44      ng       3652: #----------------------------------------------------------------------------
                   3653: #
                   3654: #-------------------------- Next few routines handles grading by csv upload
                   3655: #
                   3656: #--- Javascript to handle csv upload
1.27      albertel 3657: sub csvupload_javascript_reverse_associate {
1.246     albertel 3658:     my $error1=&mt('You need to specify the username or ID');
                   3659:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3660:   return(<<ENDPICK);
                   3661:   function verify(vf) {
                   3662:     var foundsomething=0;
                   3663:     var founduname=0;
1.243     albertel 3664:     var foundID=0;
1.27      albertel 3665:     for (i=0;i<=vf.nfields.value;i++) {
                   3666:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3667:       if (i==0 && tw!=0) { foundID=1; }
                   3668:       if (i==1 && tw!=0) { founduname=1; }
                   3669:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3670:     }
1.246     albertel 3671:     if (founduname==0 && foundID==0) {
                   3672: 	alert('$error1');
                   3673: 	return;
1.27      albertel 3674:     }
                   3675:     if (foundsomething==0) {
1.246     albertel 3676: 	alert('$error2');
                   3677: 	return;
1.27      albertel 3678:     }
                   3679:     vf.submit();
                   3680:   }
                   3681:   function flip(vf,tf) {
                   3682:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3683:     var i;
                   3684:     for (i=0;i<=vf.nfields.value;i++) {
                   3685:       //can not pick the same destination field for both name and domain
                   3686:       if (((i ==0)||(i ==1)) && 
                   3687:           ((tf==0)||(tf==1)) && 
                   3688:           (i!=tf) &&
                   3689:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3690:         eval('vf.f'+i+'.selectedIndex=0;')
                   3691:       }
                   3692:     }
                   3693:   }
                   3694: ENDPICK
                   3695: }
                   3696: 
                   3697: sub csvupload_javascript_forward_associate {
1.246     albertel 3698:     my $error1=&mt('You need to specify the username or ID');
                   3699:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3700:   return(<<ENDPICK);
                   3701:   function verify(vf) {
                   3702:     var foundsomething=0;
                   3703:     var founduname=0;
1.243     albertel 3704:     var foundID=0;
1.27      albertel 3705:     for (i=0;i<=vf.nfields.value;i++) {
                   3706:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3707:       if (tw==1) { foundID=1; }
                   3708:       if (tw==2) { founduname=1; }
                   3709:       if (tw>3) { foundsomething=1; }
1.27      albertel 3710:     }
1.246     albertel 3711:     if (founduname==0 && foundID==0) {
                   3712: 	alert('$error1');
                   3713: 	return;
1.27      albertel 3714:     }
                   3715:     if (foundsomething==0) {
1.246     albertel 3716: 	alert('$error2');
                   3717: 	return;
1.27      albertel 3718:     }
                   3719:     vf.submit();
                   3720:   }
                   3721:   function flip(vf,tf) {
                   3722:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3723:     var i;
                   3724:     //can not pick the same destination field twice
                   3725:     for (i=0;i<=vf.nfields.value;i++) {
                   3726:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3727:         eval('vf.f'+i+'.selectedIndex=0;')
                   3728:       }
                   3729:     }
                   3730:   }
                   3731: ENDPICK
                   3732: }
                   3733: 
1.26      albertel 3734: sub csvuploadmap_header {
1.324     albertel 3735:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3736:     my $javascript;
1.257     albertel 3737:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3738: 	$javascript=&csvupload_javascript_reverse_associate();
                   3739:     } else {
                   3740: 	$javascript=&csvupload_javascript_forward_associate();
                   3741:     }
1.45      ng       3742: 
1.324     albertel 3743:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3744:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3745:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3746:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3747:     $request->print(<<ENDPICK);
1.26      albertel 3748: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3749: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3750: $result
1.326     albertel 3751: <hr />
1.26      albertel 3752: <h3>Identify fields</h3>
                   3753: Total number of records found in file: $distotal <hr />
                   3754: Enter as many fields as you can. The system will inform you and bring you back
                   3755: to this page if the data selected is insufficient to run your class.<hr />
                   3756: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3757: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3758: <input type="hidden" name="associate"  value="" />
                   3759: <input type="hidden" name="phase"      value="three" />
                   3760: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3761: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3762: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3763: <input type="hidden" name="upfile_associate" 
1.257     albertel 3764:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3765: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3766: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3767: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3768: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3769: <hr />
                   3770: <script type="text/javascript" language="Javascript">
                   3771: $javascript
                   3772: </script>
                   3773: ENDPICK
1.118     ng       3774:     return '';
1.26      albertel 3775: 
                   3776: }
                   3777: 
                   3778: sub csvupload_fields {
1.324     albertel 3779:     my ($symb) = @_;
                   3780:     my (@parts) = &getpartlist($symb);
1.243     albertel 3781:     my @fields=(['ID','Student ID'],
                   3782: 		['username','Student Username'],
                   3783: 		['domain','Student Domain']);
1.324     albertel 3784:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3785:     foreach my $part (sort(@parts)) {
                   3786: 	my @datum;
                   3787: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3788: 	my $name=$part;
                   3789: 	if  (!$display) { $display = $name; }
                   3790: 	@datum=($name,$display);
1.244     albertel 3791: 	if ($name=~/^stores_(.*)_awarded/) {
                   3792: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3793: 	}
1.41      ng       3794: 	push(@fields,\@datum);
                   3795:     }
                   3796:     return (@fields);
1.26      albertel 3797: }
                   3798: 
                   3799: sub csvuploadmap_footer {
1.41      ng       3800:     my ($request,$i,$keyfields) =@_;
                   3801:     $request->print(<<ENDPICK);
1.26      albertel 3802: </table>
                   3803: <input type="hidden" name="nfields" value="$i" />
                   3804: <input type="hidden" name="keyfields" value="$keyfields" />
                   3805: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3806: </form>
                   3807: ENDPICK
                   3808: }
                   3809: 
1.283     albertel 3810: sub checkforfile_js {
1.86      ng       3811:     my $result =<<CSVFORMJS;
                   3812: <script type="text/javascript" language="javascript">
                   3813:     function checkUpload(formname) {
                   3814: 	if (formname.upfile.value == "") {
                   3815: 	    alert("Please use the browse button to select a file from your local directory.");
                   3816: 	    return false;
                   3817: 	}
                   3818: 	formname.submit();
                   3819:     }
                   3820:     </script>
                   3821: CSVFORMJS
1.283     albertel 3822:     return $result;
                   3823: }
                   3824: 
                   3825: sub upcsvScores_form {
                   3826:     my ($request) = shift;
1.324     albertel 3827:     my ($symb)=&get_symb($request);
1.283     albertel 3828:     if (!$symb) {return '';}
                   3829:     my $result=&checkforfile_js();
1.257     albertel 3830:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3831:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3832:     $result.=$table;
1.326     albertel 3833:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3834:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3835:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3836: 	'.</b></td></tr>'."\n";
                   3837:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3838:     my $upload=&mt("Upload Scores");
1.86      ng       3839:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3840:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3841:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3842:     $result.=<<ENDUPFORM;
1.106     albertel 3843: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3844: <input type="hidden" name="symb" value="$symb" />
                   3845: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3846: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3847: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3848: $upfile_select
1.370     www      3849: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3850: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3851: </form>
                   3852: ENDUPFORM
1.370     www      3853:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3854:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3855:     .'</td></tr></table>'."\n";
1.86      ng       3856:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3857:     $result.=&show_grading_menu_form($symb);
1.86      ng       3858:     return $result;
                   3859: }
                   3860: 
                   3861: 
1.26      albertel 3862: sub csvuploadmap {
1.41      ng       3863:     my ($request)= @_;
1.324     albertel 3864:     my ($symb)=&get_symb($request);
1.41      ng       3865:     if (!$symb) {return '';}
1.72      ng       3866: 
1.41      ng       3867:     my $datatoken;
1.257     albertel 3868:     if (!$env{'form.datatoken'}) {
1.41      ng       3869: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3870:     } else {
1.257     albertel 3871: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3872: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3873:     }
1.41      ng       3874:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3875:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3876:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3877:     my ($i,$keyfields);
                   3878:     if (@records) {
1.324     albertel 3879: 	my @fields=&csvupload_fields($symb);
1.45      ng       3880: 
1.257     albertel 3881: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3882: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3883: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3884: 							  \@fields);
                   3885: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3886: 	    chop($keyfields);
                   3887: 	} else {
                   3888: 	    unshift(@fields,['none','']);
                   3889: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3890: 							    \@fields);
1.311     banghart 3891:             foreach my $rec (@records) {
                   3892:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3893:                 if (%temp) {
                   3894:                     $keyfields=join(',',sort(keys(%temp)));
                   3895:                     last;
                   3896:                 }
                   3897:             }
1.41      ng       3898: 	}
                   3899:     }
                   3900:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3901:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3902: 
1.41      ng       3903:     return '';
1.27      albertel 3904: }
                   3905: 
1.246     albertel 3906: sub csvuploadoptions {
1.41      ng       3907:     my ($request)= @_;
1.324     albertel 3908:     my ($symb)=&get_symb($request);
1.257     albertel 3909:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3910:     my $ignore=&mt('Ignore First Line');
                   3911:     $request->print(<<ENDPICK);
                   3912: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3913: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3914: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3915: <!--
1.246     albertel 3916: <p>
                   3917: <label>
                   3918:    <input type="checkbox" name="show_full_results" />
                   3919:    Show a table of all changes
                   3920: </label>
                   3921: </p>
1.302     albertel 3922: -->
1.246     albertel 3923: <p>
                   3924: <label>
                   3925:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3926:    Overwrite any existing score
                   3927: </label>
                   3928: </p>
                   3929: ENDPICK
                   3930:     my %fields=&get_fields();
                   3931:     if (!defined($fields{'domain'})) {
1.257     albertel 3932: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3933: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3934:     }
1.257     albertel 3935:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3936: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3937: 	my $cleankey=$1;
                   3938: 	if ($cleankey eq 'command') { next; }
                   3939: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3940: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3941:     }
                   3942:     # FIXME do a check for any duplicated user ids...
                   3943:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3944:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3945: <hr /></form>'."\n");
1.324     albertel 3946:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3947:     return '';
                   3948: }
                   3949: 
                   3950: sub get_fields {
                   3951:     my %fields;
1.257     albertel 3952:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3953:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3954: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3955: 	    if ($env{'form.f'.$i} ne 'none') {
                   3956: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3957: 	    }
                   3958: 	} else {
1.257     albertel 3959: 	    if ($env{'form.f'.$i} ne 'none') {
                   3960: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3961: 	    }
                   3962: 	}
1.27      albertel 3963:     }
1.246     albertel 3964:     return %fields;
                   3965: }
                   3966: 
                   3967: sub csvuploadassign {
                   3968:     my ($request)= @_;
1.324     albertel 3969:     my ($symb)=&get_symb($request);
1.246     albertel 3970:     if (!$symb) {return '';}
1.345     bowersj2 3971:     my $error_msg = '';
1.246     albertel 3972:     &Apache::loncommon::load_tmp_file($request);
                   3973:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3974:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3975:     my %fields=&get_fields();
1.41      ng       3976:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3977:     my $courseid=$env{'request.course.id'};
1.97      albertel 3978:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3979:     my @notallowed;
1.41      ng       3980:     my @skipped;
                   3981:     my $countdone=0;
                   3982:     foreach my $grade (@gradedata) {
                   3983: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3984: 	my $domain;
                   3985: 	if ($entries{$fields{'domain'}}) {
                   3986: 	    $domain=$entries{$fields{'domain'}};
                   3987: 	} else {
1.257     albertel 3988: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3989: 	}
1.243     albertel 3990: 	$domain=~s/\s//g;
1.41      ng       3991: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3992: 	$username=~s/\s//g;
1.243     albertel 3993: 	if (!$username) {
                   3994: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3995: 	    $id=~s/\s//g;
1.243     albertel 3996: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3997: 	    $username=$ids{$id};
                   3998: 	}
1.41      ng       3999: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4000: 	    my $id=$entries{$fields{'ID'}};
                   4001: 	    $id=~s/\s//g;
                   4002: 	    if ($id) {
                   4003: 		push(@skipped,"$id:$domain");
                   4004: 	    } else {
                   4005: 		push(@skipped,"$username:$domain");
                   4006: 	    }
1.41      ng       4007: 	    next;
                   4008: 	}
1.108     albertel 4009: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4010: 	if (!&canmodify($usec)) {
                   4011: 	    push(@notallowed,"$username:$domain");
                   4012: 	    next;
                   4013: 	}
1.244     albertel 4014: 	my %points;
1.41      ng       4015: 	my %grades;
                   4016: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4017: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4018: 		$dest eq 'domain') { next; }
                   4019: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4020: 	    if ($dest=~/stores_(.*)_points/) {
                   4021: 		my $part=$1;
                   4022: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4023: 					      $symb,$domain,$username);
1.345     bowersj2 4024:                 if ($wgt) {
                   4025:                     $entries{$fields{$dest}}=~s/\s//g;
                   4026:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4027:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4028:                                           : 'correct_by_override';
1.345     bowersj2 4029:                     $grades{"resource.$part.awarded"}=$pcr;
                   4030:                     $grades{"resource.$part.solved"}=$award;
                   4031:                     $points{$part}=1;
                   4032:                 } else {
                   4033:                     $error_msg = "<br />" .
                   4034:                         &mt("Some point values were assigned"
                   4035:                             ." for problems with a weight "
                   4036:                             ."of zero. These values were "
                   4037:                             ."ignored.");
                   4038:                 }
1.244     albertel 4039: 	    } else {
                   4040: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4041: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4042: 		my $store_key=$dest;
                   4043: 		$store_key=~s/^stores/resource/;
                   4044: 		$store_key=~s/_/\./g;
                   4045: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4046: 	    }
1.41      ng       4047: 	}
1.508     www      4048: 	if (! %grades) { 
                   4049:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4050:         } else {
                   4051: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4052: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4053: 					   $env{'request.course.id'},
                   4054: 					   $domain,$username);
1.508     www      4055: 	   if ($result eq 'ok') {
                   4056: 	      $request->print('.');
                   4057: 	   } else {
                   4058: 	      $request->print("<p><span class=\"LC_error\">".
                   4059:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4060:                                   "$username:$domain",$result)."</span></p>");
                   4061: 	   }
                   4062: 	   $request->rflush();
                   4063: 	   $countdone++;
                   4064:         }
1.41      ng       4065:     }
1.508     www      4066:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4067:     if (@skipped) {
1.508     www      4068: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4069: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4070:     }
                   4071:     if (@notallowed) {
1.508     www      4072: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4073: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4074:     }
1.106     albertel 4075:     $request->print("<br />\n");
1.324     albertel 4076:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4077:     return $error_msg;
1.26      albertel 4078: }
1.44      ng       4079: #------------- end of section for handling csv file upload ---------
                   4080: #
                   4081: #-------------------------------------------------------------------
                   4082: #
1.122     ng       4083: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4084: #
                   4085: #--- Select a page/sequence and a student to grade
1.68      ng       4086: sub pickStudentPage {
                   4087:     my ($request) = shift;
                   4088: 
                   4089:     $request->print(<<LISTJAVASCRIPT);
                   4090: <script type="text/javascript" language="javascript">
                   4091: 
                   4092: function checkPickOne(formname) {
1.76      ng       4093:     if (radioSelection(formname.student) == null) {
1.68      ng       4094: 	alert("Please select the student you wish to grade.");
                   4095: 	return;
                   4096:     }
1.125     ng       4097:     ptr = pullDownSelection(formname.selectpage);
                   4098:     formname.page.value = formname["page"+ptr].value;
                   4099:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4100:     formname.submit();
                   4101: }
                   4102: 
                   4103: </script>
                   4104: LISTJAVASCRIPT
1.118     ng       4105:     &commonJSfunctions($request);
1.324     albertel 4106:     my ($symb) = &get_symb($request);
1.257     albertel 4107:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4108:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4109:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4110: 
1.398     albertel 4111:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4112: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4113: 
1.80      ng       4114:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4115:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4116:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4117: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4118: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4119:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4120:     my $ctr=0;
1.68      ng       4121:     foreach (@$titles) {
                   4122: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4123: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4124: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4125: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4126: 	$ctr++;
1.68      ng       4127:     }
1.485     albertel 4128:     $select.= '</select>';
                   4129:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4130: 
1.70      ng       4131:     $ctr=0;
                   4132:     foreach (@$titles) {
                   4133: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4134: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4135: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4136: 	$ctr++;
                   4137:     }
1.72      ng       4138:     $result.='<input type="hidden" name="page" />'."\n".
                   4139: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4140: 
1.485     albertel 4141:     my $options =
                   4142: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4143: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4144:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4145: 
                   4146:     $options =
                   4147: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4148: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4149: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4150:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4151:     
                   4152:     $result.=&build_section_inputs();
1.442     banghart 4153:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4154:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4155: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4156: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4157: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4158: 
1.485     albertel 4159:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4160: 			  '<input type="text" name="CODE" value="" />').
                   4161: 			      '<br />'."\n";
1.382     albertel 4162: 
1.80      ng       4163:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4164: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4165: 
1.68      ng       4166:     $request->print($result);
                   4167: 
1.485     albertel 4168:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4169: 	&Apache::loncommon::start_data_table().
                   4170: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4171: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4172: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4173: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4174: 	'<th>'.&nameUserString('header').'</th>'.
                   4175: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4176:  
1.76      ng       4177:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4178:     my $ptr = 1;
1.294     albertel 4179:     foreach my $student (sort 
                   4180: 			 {
                   4181: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4182: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4183: 			     }
                   4184: 			     return $a cmp $b;
                   4185: 			 } (keys(%$fullname))) {
1.68      ng       4186: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4187: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4188:                                   : '</td>');
1.126     ng       4189: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4190: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4191: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4192: 	$studentTable.=
                   4193: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4194:                          : '');
1.68      ng       4195: 	$ptr++;
                   4196:     }
1.484     albertel 4197:     if ($ptr%2 == 0) {
                   4198: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4199: 	    &Apache::loncommon::end_data_table_row();
                   4200:     }
                   4201:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4202:     $studentTable.='<input type="button" '.
1.485     albertel 4203: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4204: 
1.324     albertel 4205:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4206:     $request->print($studentTable);
                   4207: 
                   4208:     return '';
                   4209: }
                   4210: 
                   4211: sub getSymbMap {
1.132     bowersj2 4212:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4213: 
                   4214:     my %symbx = ();
                   4215:     my @titles = ();
1.117     bowersj2 4216:     my $minder = 0;
                   4217: 
                   4218:     # Gather every sequence that has problems.
1.240     albertel 4219:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4220: 					       1,0,1);
1.117     bowersj2 4221:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4222: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4223: 	    my $title = $minder.'.'.
                   4224: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4225: 	    push(@titles, $title); # minder in case two titles are identical
                   4226: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4227: 	    $minder++;
1.241     albertel 4228: 	}
1.68      ng       4229:     }
                   4230:     return \@titles,\%symbx;
                   4231: }
                   4232: 
1.72      ng       4233: #
                   4234: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4235: sub displayPage {
                   4236:     my ($request) = shift;
                   4237: 
1.324     albertel 4238:     my ($symb) = &get_symb($request);
1.257     albertel 4239:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4240:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4241:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4242:     my $pageTitle = $env{'form.page'};
1.103     albertel 4243:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4244:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4245:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4246: 
                   4247:     #need to make sure we have the correct data for later EXT calls, 
                   4248:     #thus invalidate the cache
                   4249:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4250:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4251:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4252:     &Apache::lonnet::clear_EXT_cache_status();
                   4253: 
1.103     albertel 4254:     if (!&canview($usec)) {
1.485     albertel 4255: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4256: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4257: 	return;
                   4258:     }
1.398     albertel 4259:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4260:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4261: 	'</h3>'."\n";
1.500     albertel 4262:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4263:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4264: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4265:     } else {
                   4266: 	delete($env{'form.CODE'});
                   4267:     }
1.71      ng       4268:     &sub_page_js($request);
                   4269:     $request->print($result);
                   4270: 
1.132     bowersj2 4271:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4272:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4273:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4274:     if (!$map) {
1.485     albertel 4275: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4276: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4277: 	return; 
                   4278:     }
1.68      ng       4279:     my $iterator = $navmap->getIterator($map->map_start(),
                   4280: 					$map->map_finish());
                   4281: 
1.71      ng       4282:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4283: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4284: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4285: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4286: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4287: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4288: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4289: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4290: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4291: 
1.382     albertel 4292:     if (defined($env{'form.CODE'})) {
                   4293: 	$studentTable.=
                   4294: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4295:     }
1.381     albertel 4296:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4297: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4298: 
1.485     albertel 4299:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4300: 	&Apache::loncommon::start_data_table().
                   4301: 	&Apache::loncommon::start_data_table_header_row().
                   4302: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4303: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4304: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4305: 
1.329     albertel 4306:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4307:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4308:     $iterator->next(); # skip the first BEGIN_MAP
                   4309:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4310:     while ($depth > 0) {
1.68      ng       4311:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4312:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4313: 
1.385     albertel 4314:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4315: 	    my $parts = $curRes->parts();
1.68      ng       4316:             my $title = $curRes->compTitle();
1.71      ng       4317: 	    my $symbx = $curRes->symb();
1.484     albertel 4318: 	    $studentTable.=
                   4319: 		&Apache::loncommon::start_data_table_row().
                   4320: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4321: 		(scalar(@{$parts}) == 1 ? '' 
                   4322: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4323: 							scalar(@{$parts}))
                   4324: 		 ).
                   4325: 		 '</td>';
1.71      ng       4326: 	    $studentTable.='<td valign="top">';
1.382     albertel 4327: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4328: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4329: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4330: 					     undef,'both',\%form);
1.71      ng       4331: 	    } else {
1.382     albertel 4332: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4333: 		$companswer =~ s|<form(.*?)>||g;
                   4334: 		$companswer =~ s|</form>||g;
1.71      ng       4335: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4336: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4337: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4338: #		}
1.116     ng       4339: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4340: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4341: 	    }
                   4342: 
1.257     albertel 4343: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4344: 
1.257     albertel 4345: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4346: 		if ($record{'version'} eq '') {
1.485     albertel 4347: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4348: 		} else {
1.116     ng       4349: 		    my %responseType = ();
                   4350: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4351: 			my @responseIds =$curRes->responseIds($partid);
                   4352: 			my @responseType =$curRes->responseType($partid);
                   4353: 			my %responseIds;
                   4354: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4355: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4356: 			}
                   4357: 			$responseType{$partid} = \%responseIds;
1.116     ng       4358: 		    }
1.148     albertel 4359: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4360: 
1.71      ng       4361: 		}
1.257     albertel 4362: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4363: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4364: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4365: 									$env{'request.course.id'},
1.71      ng       4366: 									'','.submission');
                   4367:  
                   4368: 	    }
1.103     albertel 4369: 	    if (&canmodify($usec)) {
                   4370: 		foreach my $partid (@{$parts}) {
                   4371: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4372: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4373: 		    $question++;
                   4374: 		}
1.196     albertel 4375: 		$prob++;
1.71      ng       4376: 	    }
                   4377: 	    $studentTable.='</td></tr>';
1.68      ng       4378: 
1.103     albertel 4379: 	}
1.68      ng       4380:         $curRes = $iterator->next();
                   4381:     }
                   4382: 
1.485     albertel 4383:     $studentTable.='</table>'."\n".
                   4384: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4385: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4386: 	'</form>'."\n";
1.324     albertel 4387:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4388:     $request->print($studentTable);
                   4389: 
                   4390:     return '';
1.119     ng       4391: }
                   4392: 
                   4393: sub displaySubByDates {
1.148     albertel 4394:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4395:     my $isCODE=0;
1.335     albertel 4396:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4397:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4398:     my $studentTable=&Apache::loncommon::start_data_table().
                   4399: 	&Apache::loncommon::start_data_table_header_row().
                   4400: 	'<th>'.&mt('Date/Time').'</th>'.
                   4401: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4402: 	'<th>'.&mt('Submission').'</th>'.
                   4403: 	'<th>'.&mt('Status').'</th>'.
                   4404: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4405:     my ($version);
                   4406:     my %mark;
1.148     albertel 4407:     my %orders;
1.119     ng       4408:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4409:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4410: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4411:     }
1.335     albertel 4412: 
                   4413:     my $interaction;
1.525     raeburn  4414:     my $no_increment = 1;
1.119     ng       4415:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4416: 	my $timestamp = 
                   4417: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4418: 	if (exists($$record{$version.':resource.0.version'})) {
                   4419: 	    $interaction = $$record{$version.':resource.0.version'};
                   4420: 	}
                   4421: 
                   4422: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4423: 		             : "$version:resource");
1.467     albertel 4424: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4425: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4426: 	if ($isCODE) {
                   4427: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4428: 	}
1.119     ng       4429: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4430: 	my @displaySub = ();
                   4431: 	foreach my $partid (@{$parts}) {
1.335     albertel 4432: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4433: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4434: 	    
                   4435: 
1.122     ng       4436: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4437: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4438: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4439: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4440: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4441: 
                   4442: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4443: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4444: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4445: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4446: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4447: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4448: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4449: 		    } else {
1.467     albertel 4450: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4451: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4452: 		    }
1.335     albertel 4453: 		    my $responseType=($isTask ? 'Task'
                   4454:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4455: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4456: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4457: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4458: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4459:                                        $no_increment);
1.148     albertel 4460: 		    }
1.147     albertel 4461: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4462: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4463: 		}
                   4464: 	    }
1.335     albertel 4465: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4466: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4467: 				    $$record{"$where.$partid.checkedin"},
                   4468: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4469: 					'<br />';
1.335     albertel 4470: 	    }
                   4471: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4472: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4473: 		    lc($$record{"$where.$partid.award"}).' '.
                   4474: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4475: 		    '<br />';
                   4476: 	    }
1.335     albertel 4477: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4478: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4479: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4480: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4481: 		$displaySub[2].=
                   4482: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4483: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4484: 	    }
                   4485: 	}
                   4486: 	# needed because old essay regrader has not parts info
                   4487: 	if (exists $$record{"$version:resource.regrader"}) {
                   4488: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4489: 	}
                   4490: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4491: 	if ($displaySub[2]) {
1.467     albertel 4492: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4493: 	}
1.467     albertel 4494: 	$studentTable.='&nbsp;</td>'.
                   4495: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4496:     }
1.467     albertel 4497:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4498:     return $studentTable;
1.71      ng       4499: }
                   4500: 
                   4501: sub updateGradeByPage {
                   4502:     my ($request) = shift;
                   4503: 
1.257     albertel 4504:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4505:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4506:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4507:     my $pageTitle = $env{'form.page'};
1.103     albertel 4508:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4509:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4510:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4511:     if (!&canmodify($usec)) {
1.526     raeburn  4512: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4513: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4514: 	return;
                   4515:     }
1.398     albertel 4516:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4517:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4518: 	'</h3>'."\n";
1.70      ng       4519: 
1.68      ng       4520:     $request->print($result);
                   4521: 
1.132     bowersj2 4522:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4523:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4524:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4525:     if (!$map) {
1.527     raeburn  4526: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4527: 	my ($symb)=&get_symb($request);
                   4528: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4529: 	return; 
                   4530:     }
1.71      ng       4531:     my $iterator = $navmap->getIterator($map->map_start(),
                   4532: 					$map->map_finish());
1.70      ng       4533: 
1.484     albertel 4534:     my $studentTable=
                   4535: 	&Apache::loncommon::start_data_table().
                   4536: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4537: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4538: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4539: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4540: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4541: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4542: 
                   4543:     $iterator->next(); # skip the first BEGIN_MAP
                   4544:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4545:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4546:     while ($depth > 0) {
1.71      ng       4547:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4548:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4549: 
1.385     albertel 4550:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4551: 	    my $parts = $curRes->parts();
1.71      ng       4552:             my $title = $curRes->compTitle();
                   4553: 	    my $symbx = $curRes->symb();
1.484     albertel 4554: 	    $studentTable.=
                   4555: 		&Apache::loncommon::start_data_table_row().
                   4556: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4557: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4558:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4559: 		.')').'</td>';
1.71      ng       4560: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4561: 
                   4562: 	    my %newrecord=();
                   4563: 	    my @displayPts=();
1.269     raeburn  4564:             my %aggregate = ();
                   4565:             my $aggregateflag = 0;
1.71      ng       4566: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4567: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4568: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4569: 
1.257     albertel 4570: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4571: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4572: 		my $partial = $newpts/$wgt;
                   4573: 		my $score;
                   4574: 		if ($partial > 0) {
                   4575: 		    $score = 'correct_by_override';
1.125     ng       4576: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4577: 		    $score = 'incorrect_by_override';
                   4578: 		}
1.257     albertel 4579: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4580: 		if ($dropMenu eq 'excused') {
1.71      ng       4581: 		    $partial = '';
                   4582: 		    $score = 'excused';
1.125     ng       4583: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4584: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4585: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4586: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4587: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4588: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4589: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4590: 		    $changeflag++;
                   4591: 		    $newpts = '';
1.269     raeburn  4592:                     
                   4593:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4594:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4595:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4596:                     if ($aggtries > 0) {
                   4597:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4598:                         $aggregateflag = 1;
                   4599:                     }
1.71      ng       4600: 		}
1.324     albertel 4601: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4602: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4603: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4604: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4605: 		    '&nbsp;<br />';
1.526     raeburn  4606: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4607: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4608: 		    '&nbsp;<br />';
1.71      ng       4609: 		$question++;
1.380     albertel 4610: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4611: 
1.71      ng       4612: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4613: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4614: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4615: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4616: 
                   4617: 		$changeflag++;
                   4618: 	    }
                   4619: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4620: 		my %record = 
                   4621: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4622: 					     $udom,$uname);
                   4623: 
                   4624: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4625: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4626: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4627: 		    $newrecord{'resource.CODE'} = '';
                   4628: 		}
1.257     albertel 4629: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4630: 					$udom,$uname);
1.382     albertel 4631: 		%record = &Apache::lonnet::restore($symbx,
                   4632: 						   $env{'request.course.id'},
                   4633: 						   $udom,$uname);
1.380     albertel 4634: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4635: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4636: 	    }
1.380     albertel 4637: 	    
1.269     raeburn  4638:             if ($aggregateflag) {
                   4639:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4640:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4641:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4642:             }
1.125     ng       4643: 
1.71      ng       4644: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4645: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4646: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4647: 
1.196     albertel 4648: 	    $prob++;
1.68      ng       4649: 	}
1.71      ng       4650:         $curRes = $iterator->next();
1.68      ng       4651:     }
1.98      albertel 4652: 
1.484     albertel 4653:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4654:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4655:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4656: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4657: 		  $changeflag));
1.76      ng       4658:     $request->print($grademsg.$studentTable);
1.68      ng       4659: 
1.70      ng       4660:     return '';
                   4661: }
                   4662: 
1.72      ng       4663: #-------- end of section for handling grading by page/sequence ---------
                   4664: #
                   4665: #-------------------------------------------------------------------
                   4666: 
1.75      albertel 4667: #--------------------Scantron Grading-----------------------------------
                   4668: #
                   4669: #------ start of section for handling grading by page/sequence ---------
                   4670: 
1.423     albertel 4671: =pod
                   4672: 
                   4673: =head1 Bubble sheet grading routines
                   4674: 
1.424     albertel 4675:   For this documentation:
                   4676: 
                   4677:    'scanline' refers to the full line of characters
                   4678:    from the file that we are parsing that represents one entire sheet
                   4679: 
                   4680:    'bubble line' refers to the data
                   4681:    representing the line of bubbles that are on the physical bubble sheet
                   4682: 
                   4683: 
                   4684: The overall process is that a scanned in bubble sheet data is uploaded
                   4685: into a course. When a user wants to grade, they select a
                   4686: sequence/folder of resources, a file of bubble sheet info, and pick
                   4687: one of the predefined configurations for what each scanline looks
                   4688: like.
                   4689: 
                   4690: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4691: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4692: because too light bubbling), 'double bubble' (each bubble line should
                   4693: have no more that one letter picked), invalid or duplicated CODE,
                   4694: invalid student ID
                   4695: 
                   4696: If the CODE option is used that determines the randomization of the
                   4697: homework problems, either way the student ID is looked up into a
                   4698: username:domain.
                   4699: 
                   4700: During the validation phase the instructor can choose to skip scanlines. 
                   4701: 
1.435     foxr     4702: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4703: 
                   4704:   scantron_original_filename (unmodified original file)
                   4705:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4706:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4707: 
                   4708: Also there is a separate hash nohist_scantrondata that contains extra
                   4709: correction information that isn't representable in the bubble sheet
                   4710: file (see &scantron_getfile() for more information)
                   4711: 
                   4712: After all scanlines are either valid, marked as valid or skipped, then
                   4713: foreach line foreach problem in the picked sequence, an ssi request is
                   4714: made that simulates a user submitting their selected letter(s) against
                   4715: the homework problem.
1.423     albertel 4716: 
                   4717: =over 4
                   4718: 
                   4719: 
                   4720: 
                   4721: =item defaultFormData
                   4722: 
                   4723:   Returns html hidden inputs used to hold context/default values.
                   4724: 
                   4725:  Arguments:
                   4726:   $symb - $symb of the current resource 
                   4727: 
                   4728: =cut
1.422     foxr     4729: 
1.81      albertel 4730: sub defaultFormData {
1.324     albertel 4731:     my ($symb)=@_;
1.447     foxr     4732:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4733:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4734:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4735: }
                   4736: 
1.447     foxr     4737: 
1.423     albertel 4738: =pod 
                   4739: 
                   4740: =item getSequenceDropDown
                   4741: 
                   4742:    Return html dropdown of possible sequences to grade
                   4743:  
                   4744:  Arguments:
                   4745:    $symb - $symb of the current resource 
                   4746: 
                   4747: =cut
1.422     foxr     4748: 
1.75      albertel 4749: sub getSequenceDropDown {
1.423     albertel 4750:     my ($symb)=@_;
1.75      albertel 4751:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4752:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4753:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4754:     my $ctr=0;
                   4755:     foreach (@$titles) {
                   4756: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4757: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4758: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4759: 	    '>'.$showtitle.'</option>'."\n";
                   4760: 	$ctr++;
                   4761:     }
                   4762:     $result.= '</select>';
                   4763:     return $result;
                   4764: }
                   4765: 
1.495     albertel 4766: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4767:                                    # index is "symb.part_id"
                   4768: 
                   4769: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4770: 
1.509     raeburn  4771: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4772:                                    # matchresponse or rankresponse, where 
                   4773:                                    # an individual response can have multiple 
                   4774:                                    # lines
1.503     raeburn  4775: 
                   4776: my %responsetype_per_response;     # responsetype for each response
                   4777: 
1.495     albertel 4778: # Save and restore the bubble lines array to the form env.
                   4779: 
                   4780: 
                   4781: sub save_bubble_lines {
                   4782:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4783: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4784: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4785: 	    $first_bubble_line{$line};
1.503     raeburn  4786:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4787:             $subdivided_bubble_lines{$line};
                   4788:         $env{"form.scantron.responsetype.$line"} =
                   4789:             $responsetype_per_response{$line};
1.495     albertel 4790:     }
                   4791: }
                   4792: 
                   4793: 
                   4794: sub restore_bubble_lines {
                   4795:     my $line = 0;
                   4796:     %bubble_lines_per_response = ();
                   4797:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4798: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4799: 	$bubble_lines_per_response{$line} = $value;
                   4800: 	$first_bubble_line{$line}  =
                   4801: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4802:         $subdivided_bubble_lines{$line} =
                   4803:             $env{"form.scantron.sub_bubblelines.$line"};
                   4804:         $responsetype_per_response{$line} =
                   4805:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4806: 	$line++;
                   4807:     }
                   4808: 
                   4809: }
                   4810: 
                   4811: #  Given the parsed scanline, get the response for 
                   4812: #  'answer' number n:
                   4813: 
                   4814: sub get_response_bubbles {
                   4815:     my ($parsed_line, $response)  = @_;
                   4816: 
                   4817: 
                   4818:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4819:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4820:     
                   4821:     my $selected = "";
                   4822: 
                   4823:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4824: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4825: 	$bubble_line++;
                   4826:     }
                   4827:     return $selected;
                   4828: }
1.423     albertel 4829: 
                   4830: =pod 
                   4831: 
                   4832: =item scantron_filenames
                   4833: 
                   4834:    Returns a list of the scantron files in the current course 
                   4835: 
                   4836: =cut
1.422     foxr     4837: 
1.202     albertel 4838: sub scantron_filenames {
1.257     albertel 4839:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4840:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4841:     my $getpropath = 1;
1.157     albertel 4842:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4843:                                        $getpropath);
1.202     albertel 4844:     my @possiblenames;
1.201     albertel 4845:     foreach my $filename (sort(@files)) {
1.157     albertel 4846: 	($filename)=split(/&/,$filename);
                   4847: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4848: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4849: 	push(@possiblenames,$filename);
                   4850:     }
                   4851:     return @possiblenames;
                   4852: }
                   4853: 
1.423     albertel 4854: =pod 
                   4855: 
                   4856: =item scantron_uploads
                   4857: 
                   4858:    Returns  html drop-down list of scantron files in current course.
                   4859: 
                   4860:  Arguments:
                   4861:    $file2grade - filename to set as selected in the dropdown
                   4862: 
                   4863: =cut
1.422     foxr     4864: 
1.202     albertel 4865: sub scantron_uploads {
1.209     ng       4866:     my ($file2grade) = @_;
1.202     albertel 4867:     my $result=	'<select name="scantron_selectfile">';
                   4868:     $result.="<option></option>";
                   4869:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4870: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4871:     }
                   4872:     $result.="</select>";
                   4873:     return $result;
                   4874: }
                   4875: 
1.423     albertel 4876: =pod 
                   4877: 
                   4878: =item scantron_scantab
                   4879: 
                   4880:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4881:   file.
                   4882: 
                   4883: =cut
1.422     foxr     4884: 
1.82      albertel 4885: sub scantron_scantab {
                   4886:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4887:     $result.='<option></option>'."\n";
1.518     raeburn  4888:     my @lines = &get_scantronformat_file();
                   4889:     if (@lines > 0) {
                   4890:         foreach my $line (@lines) {
                   4891:             next if (($line =~ /^\#/) || ($line eq ''));
                   4892: 	    my ($name,$descrip)=split(/:/,$line);
                   4893: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4894:         }
1.82      albertel 4895:     }
                   4896:     $result.='</select>'."\n";
1.518     raeburn  4897:     return $result;
                   4898: }
                   4899: 
                   4900: =pod
                   4901: 
                   4902: =item get_scantronformat_file
                   4903: 
                   4904:   Returns an array containing lines from the scantron format file for
                   4905:   the domain of the course.
                   4906: 
                   4907:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4908:   lines are from this file.
                   4909: 
                   4910:   Otherwise, if a default.tab has been published in RES space by the 
                   4911:   domainconfig user, lines are from this file.
                   4912: 
                   4913:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4914:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4915: 
1.518     raeburn  4916: =cut
                   4917: 
                   4918: sub get_scantronformat_file {
                   4919:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4920:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4921:     my $gottab = 0;
                   4922:     my @lines;
                   4923:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4924:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4925:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4926:             if ($formatfile ne '-1') {
                   4927:                 @lines = split("\n",$formatfile,-1);
                   4928:                 $gottab = 1;
                   4929:             }
                   4930:         }
                   4931:     }
                   4932:     if (!$gottab) {
                   4933:         my $confname = $cdom.'-domainconfig';
                   4934:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4935:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4936:         if ($formatfile ne '-1') {
                   4937:             @lines = split("\n",$formatfile,-1);
                   4938:             $gottab = 1;
                   4939:         }
                   4940:     }
                   4941:     if (!$gottab) {
1.519     raeburn  4942:         my @domains = &Apache::lonnet::current_machine_domains();
                   4943:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4944:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4945:             @lines = <$fh>;
                   4946:             close($fh);
                   4947:         } else {
                   4948:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4949:             @lines = <$fh>;
                   4950:             close($fh);
                   4951:         }
1.518     raeburn  4952:     }
                   4953:     return @lines;
1.82      albertel 4954: }
                   4955: 
1.423     albertel 4956: =pod 
                   4957: 
                   4958: =item scantron_CODElist
                   4959: 
                   4960:   Returns html drop down of the saved CODE lists from current course,
                   4961:   generated from earlier printings.
                   4962: 
                   4963: =cut
1.422     foxr     4964: 
1.186     albertel 4965: sub scantron_CODElist {
1.257     albertel 4966:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4967:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4968:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4969:     my $namechoice='<option></option>';
1.225     albertel 4970:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4971: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4972: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4973: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4974:     }
                   4975:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4976:     return $namechoice;
                   4977: }
                   4978: 
1.423     albertel 4979: =pod 
                   4980: 
                   4981: =item scantron_CODEunique
                   4982: 
                   4983:   Returns the html for "Each CODE to be used once" radio.
                   4984: 
                   4985: =cut
1.422     foxr     4986: 
1.186     albertel 4987: sub scantron_CODEunique {
1.381     albertel 4988:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4989:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4990:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4991:                 </span>
                   4992:                 <span style="white-space: nowrap;">
1.272     albertel 4993:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4994:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4995:                 </span>';
1.186     albertel 4996:     return $result;
                   4997: }
1.423     albertel 4998: 
                   4999: =pod 
                   5000: 
                   5001: =item scantron_selectphase
                   5002: 
                   5003:   Generates the initial screen to start the bubble sheet process.
                   5004:   Allows for - starting a grading run.
1.424     albertel 5005:              - downloading existing scan data (original, corrected
1.423     albertel 5006:                                                 or skipped info)
                   5007: 
                   5008:              - uploading new scan data
                   5009: 
                   5010:  Arguments:
                   5011:   $r          - The Apache request object
                   5012:   $file2grade - name of the file that contain the scanned data to score
                   5013: 
                   5014: =cut
1.186     albertel 5015: 
1.75      albertel 5016: sub scantron_selectphase {
1.209     ng       5017:     my ($r,$file2grade) = @_;
1.324     albertel 5018:     my ($symb)=&get_symb($r);
1.75      albertel 5019:     if (!$symb) {return '';}
1.423     albertel 5020:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5021:     my $default_form_data=&defaultFormData($symb);
                   5022:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5023:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5024:     my $format_selector=&scantron_scantab();
1.186     albertel 5025:     my $CODE_selector=&scantron_CODElist();
                   5026:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5027:     my $result;
1.422     foxr     5028: 
1.513     foxr     5029:     $ssi_error = 0;
                   5030: 
1.422     foxr     5031:     # Chunk of form to prompt for a file to grade and how:
                   5032: 
1.489     albertel 5033:     $result.= '
                   5034:     <br />
                   5035:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5036:     <input type="hidden" name="command" value="scantron_warning" />
                   5037:     '.$default_form_data.'
                   5038:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5039:        '.&Apache::loncommon::start_data_table_header_row().'
                   5040:             <th colspan="2">
1.492     albertel 5041:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5042:             </th>
                   5043:        '.&Apache::loncommon::end_data_table_header_row().'
                   5044:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5045:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5046:        '.&Apache::loncommon::end_data_table_row().'
                   5047:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5048:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5049:        '.&Apache::loncommon::end_data_table_row().'
                   5050:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5051:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5052:        '.&Apache::loncommon::end_data_table_row().'
                   5053:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5054:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5055:        '.&Apache::loncommon::end_data_table_row().'
                   5056:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5057:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5058:        '.&Apache::loncommon::end_data_table_row().'
                   5059:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5060: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5061:             <td>
1.492     albertel 5062: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5063:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5064:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5065: 	    </td>
1.489     albertel 5066:        '.&Apache::loncommon::end_data_table_row().'
                   5067:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5068:             <td colspan="2">
1.492     albertel 5069:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5070:             </td>
1.489     albertel 5071:        '.&Apache::loncommon::end_data_table_row().'
                   5072:     '.&Apache::loncommon::end_data_table().'
                   5073:     </form>
                   5074: ';
1.162     albertel 5075:    
                   5076:     $r->print($result);
                   5077: 
1.257     albertel 5078:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5079:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5080: 
1.422     foxr     5081: 	# Chunk of form to prompt for a scantron file upload.
                   5082: 
1.489     albertel 5083:         $r->print('
                   5084:     <br />
                   5085:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5086:        '.&Apache::loncommon::start_data_table_header_row().'
                   5087:             <th>
1.492     albertel 5088:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5089:             </th>
                   5090:        '.&Apache::loncommon::end_data_table_header_row().'
                   5091:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5092:             <td>
1.489     albertel 5093: ');
1.324     albertel 5094:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5095:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5096:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5097:     $r->print('
1.174     albertel 5098:               <script type="text/javascript" language="javascript">
                   5099:     function checkUpload(formname) {
                   5100: 	if (formname.upfile.value == "") {
1.492     albertel 5101: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5102: 	    return false;
                   5103: 	}
                   5104: 	formname.submit();
                   5105:     }
                   5106:               </script>
                   5107: 
1.492     albertel 5108:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5109:                 '.$default_form_data.'
                   5110:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5111:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5112:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5113:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5114:                 <br />
1.492     albertel 5115:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5116:               </form>
1.492     albertel 5117: ');
1.162     albertel 5118: 
1.489     albertel 5119:         $r->print('
1.162     albertel 5120:             </td>
1.489     albertel 5121:        '.&Apache::loncommon::end_data_table_row().'
                   5122:        '.&Apache::loncommon::end_data_table().'
                   5123: ');
1.162     albertel 5124:     }
1.422     foxr     5125: 
                   5126:     # Chunk of the form that prompts to view a scoring office file,
                   5127:     # corrected file, skipped records in a file.
                   5128: 
1.489     albertel 5129:     $r->print('
                   5130:    <br />
                   5131:    <form action="/adm/grades" name="scantron_download">
                   5132:      '.$default_form_data.'
                   5133:      <input type="hidden" name="command" value="scantron_download" />
                   5134:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5135:        '.&Apache::loncommon::start_data_table_header_row().'
                   5136:               <th>
1.492     albertel 5137:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5138:               </th>
                   5139:        '.&Apache::loncommon::end_data_table_header_row().'
                   5140:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5141:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5142:                 <br />
1.492     albertel 5143:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5144:        '.&Apache::loncommon::end_data_table_row().'
                   5145:      '.&Apache::loncommon::end_data_table().'
                   5146:    </form>
                   5147:    <br />
                   5148: ');
1.162     albertel 5149: 
1.457     banghart 5150:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5151: 
1.528   ! raeburn  5152:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5153:              $default_form_data."\n".
                   5154:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5155:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5156:              '<th colspan="2">
                   5157:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5158:              '</th>'."\n".
                   5159:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5160:               &Apache::loncommon::start_data_table_row()."\n".
                   5161:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5162:               '<td> '.$sequence_selector.' </td>'.
                   5163:               &Apache::loncommon::end_data_table_row()."\n".
                   5164:               &Apache::loncommon::start_data_table_row()."\n".
                   5165:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5166:               '<td> '.$file_selector.' </td>'."\n".
                   5167:               &Apache::loncommon::end_data_table_row()."\n".
                   5168:               &Apache::loncommon::start_data_table_row()."\n".
                   5169:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5170:               '<td> '.$format_selector.' </td>'."\n".
                   5171:               &Apache::loncommon::end_data_table_row()."\n".
                   5172:               &Apache::loncommon::start_data_table_row()."\n".
                   5173:               '<td colspan="2">'."\n".
                   5174:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5175:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5176:               '</td>'."\n".
                   5177:               &Apache::loncommon::end_data_table_row()."\n".
                   5178:               &Apache::loncommon::end_data_table()."\n".
                   5179:               '</form><br />');
1.457     banghart 5180:     $r->print($grading_menu_button);
1.523     raeburn  5181:     return;
1.75      albertel 5182: }
                   5183: 
1.423     albertel 5184: =pod
                   5185: 
                   5186: =item get_scantron_config
                   5187: 
                   5188:    Parse and return the scantron configuration line selected as a
                   5189:    hash of configuration file fields.
                   5190: 
                   5191:  Arguments:
                   5192:     which - the name of the configuration to parse from the file.
                   5193: 
                   5194: 
                   5195:  Returns:
                   5196:             If the named configuration is not in the file, an empty
                   5197:             hash is returned.
                   5198:     a hash with the fields
                   5199:       name         - internal name for the this configuration setup
                   5200:       description  - text to display to operator that describes this config
                   5201:       CODElocation - if 0 or the string 'none'
                   5202:                           - no CODE exists for this config
                   5203:                      if -1 || the string 'letter'
                   5204:                           - a CODE exists for this config and is
                   5205:                             a string of letters
                   5206:                      Unsupported value (but planned for future support)
                   5207:                           if a positive integer
                   5208:                                - The CODE exists as the first n items from
                   5209:                                  the question section of the form
                   5210:                           if the string 'number'
                   5211:                                - The CODE exists for this config and is
                   5212:                                  a string of numbers
                   5213:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5214:                      the CODE starts
                   5215:       CODElength  - length of the CODE
                   5216:       IDstart     - column where the student ID number starts
                   5217:       IDlength    - length of the student ID info
                   5218:       Qstart      - column where the information from the bubbled
                   5219:                     'questions' start
                   5220:       Qlength     - number of columns comprising a single bubble line from
                   5221:                     the sheet. (usually either 1 or 10)
1.424     albertel 5222:       Qon         - either a single character representing the character used
1.423     albertel 5223:                     to signal a bubble was chosen in the positional setup, or
                   5224:                     the string 'letter' if the letter of the chosen bubble is
                   5225:                     in the final, or 'number' if a number representing the
                   5226:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5227:       Qoff        - the character used to represent that a bubble was
                   5228:                     left blank
1.423     albertel 5229:       PaperID     - if the scanning process generates a unique number for each
                   5230:                     sheet scanned the column that this ID number starts in
                   5231:       PaperIDlength - number of columns that comprise the unique ID number
                   5232:                       for the sheet of paper
1.424     albertel 5233:       FirstName   - column that the first name starts in
1.423     albertel 5234:       FirstNameLength - number of columns that the first name spans
                   5235:  
                   5236:       LastName    - column that the last name starts in
                   5237:       LastNameLength - number of columns that the last name spans
                   5238: 
                   5239: =cut
1.422     foxr     5240: 
1.82      albertel 5241: sub get_scantron_config {
                   5242:     my ($which) = @_;
1.518     raeburn  5243:     my @lines = &get_scantronformat_file();
1.82      albertel 5244:     my %config;
1.157     albertel 5245:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5246:     foreach my $line (@lines) {
1.82      albertel 5247: 	my ($name,$descrip)=split(/:/,$line);
                   5248: 	if ($name ne $which ) { next; }
                   5249: 	chomp($line);
                   5250: 	my @config=split(/:/,$line);
                   5251: 	$config{'name'}=$config[0];
                   5252: 	$config{'description'}=$config[1];
                   5253: 	$config{'CODElocation'}=$config[2];
                   5254: 	$config{'CODEstart'}=$config[3];
                   5255: 	$config{'CODElength'}=$config[4];
                   5256: 	$config{'IDstart'}=$config[5];
                   5257: 	$config{'IDlength'}=$config[6];
                   5258: 	$config{'Qstart'}=$config[7];
1.497     foxr     5259:  	$config{'Qlength'}=$config[8];
1.82      albertel 5260: 	$config{'Qoff'}=$config[9];
                   5261: 	$config{'Qon'}=$config[10];
1.157     albertel 5262: 	$config{'PaperID'}=$config[11];
                   5263: 	$config{'PaperIDlength'}=$config[12];
                   5264: 	$config{'FirstName'}=$config[13];
                   5265: 	$config{'FirstNamelength'}=$config[14];
                   5266: 	$config{'LastName'}=$config[15];
                   5267: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5268: 	last;
                   5269:     }
                   5270:     return %config;
                   5271: }
                   5272: 
1.423     albertel 5273: =pod 
                   5274: 
                   5275: =item username_to_idmap
                   5276: 
                   5277:     creates a hash keyed by student id with values of the corresponding
                   5278:     student username:domain.
                   5279: 
                   5280:   Arguments:
                   5281: 
                   5282:     $classlist - reference to the class list hash. This is a hash
                   5283:                  keyed by student name:domain  whose elements are references
1.424     albertel 5284:                  to arrays containing various chunks of information
1.423     albertel 5285:                  about the student. (See loncoursedata for more info).
                   5286: 
                   5287:   Returns
                   5288:     %idmap - the constructed hash
                   5289: 
                   5290: =cut
                   5291: 
1.82      albertel 5292: sub username_to_idmap {
                   5293:     my ($classlist)= @_;
                   5294:     my %idmap;
                   5295:     foreach my $student (keys(%$classlist)) {
                   5296: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5297: 	    $student;
                   5298:     }
                   5299:     return %idmap;
                   5300: }
1.423     albertel 5301: 
                   5302: =pod
                   5303: 
1.424     albertel 5304: =item scantron_fixup_scanline
1.423     albertel 5305: 
                   5306:    Process a requested correction to a scanline.
                   5307: 
                   5308:   Arguments:
                   5309:     $scantron_config   - hash from &get_scantron_config()
                   5310:     $scan_data         - hash of correction information 
                   5311:                           (see &scantron_getfile())
                   5312:     $line              - existing scanline
                   5313:     $whichline         - line number of the passed in scanline
                   5314:     $field             - type of change to process 
                   5315:                          (either 
                   5316:                           'ID'     -> correct the student ID number
                   5317:                           'CODE'   -> correct the CODE
                   5318:                           'answer' -> fixup the submitted answers)
                   5319:     
                   5320:    $args               - hash of additional info,
                   5321:                           - 'ID' 
                   5322:                                'newid' -> studentID to use in replacement
1.424     albertel 5323:                                           of existing one
1.423     albertel 5324:                           - 'CODE' 
                   5325:                                'CODE_ignore_dup' - set to true if duplicates
                   5326:                                                    should be ignored.
                   5327: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5328:                                         if the existing unfound code should
1.423     albertel 5329:                                         be used as is
                   5330:                           - 'answer'
                   5331:                                'response' - new answer or 'none' if blank
                   5332:                                'question' - the bubble line to change
1.503     raeburn  5333:                                'questionnum' - the question identifier,
                   5334:                                                may include subquestion. 
1.423     albertel 5335: 
                   5336:   Returns:
                   5337:     $line - the modified scanline
                   5338: 
                   5339:   Side effects: 
                   5340:     $scan_data - may be updated
                   5341: 
                   5342: =cut
                   5343: 
1.82      albertel 5344: 
1.157     albertel 5345: sub scantron_fixup_scanline {
                   5346:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5347:     if ($field eq 'ID') {
                   5348: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5349: 	    return ($line,1,'New value too large');
1.157     albertel 5350: 	}
                   5351: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5352: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5353: 				     $args->{'newid'});
                   5354: 	}
                   5355: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5356: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5357: 	if ($args->{'newid'}=~/^\s*$/) {
                   5358: 	    &scan_data($scan_data,"$whichline.user",
                   5359: 		       $args->{'username'}.':'.$args->{'domain'});
                   5360: 	}
1.186     albertel 5361:     } elsif ($field eq 'CODE') {
1.192     albertel 5362: 	if ($args->{'CODE_ignore_dup'}) {
                   5363: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5364: 	}
                   5365: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5366: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5367: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5368: 		return ($line,1,'New CODE value too large');
                   5369: 	    }
                   5370: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5371: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5372: 	    }
                   5373: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5374: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5375: 	}
1.157     albertel 5376:     } elsif ($field eq 'answer') {
1.497     foxr     5377: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5378: 	my $off=$scantron_config->{'Qoff'};
                   5379: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5380: 	my $answer=${off}x$length;
                   5381: 	if ($args->{'response'} eq 'none') {
                   5382: 	    &scan_data($scan_data,
1.503     raeburn  5383: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5384: 	} else {
                   5385: 	    if ($on eq 'letter') {
                   5386: 		my @alphabet=('A'..'Z');
                   5387: 		$answer=$alphabet[$args->{'response'}];
                   5388: 	    } elsif ($on eq 'number') {
                   5389: 		$answer=$args->{'response'}+1;
                   5390: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5391: 	    } else {
1.497     foxr     5392: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5393: 	    }
1.497     foxr     5394: 	    &scan_data($scan_data,
1.503     raeburn  5395: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5396: 	}
1.497     foxr     5397: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5398: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5399:     }
                   5400:     return $line;
                   5401: }
1.423     albertel 5402: 
                   5403: =pod
                   5404: 
                   5405: =item scan_data
                   5406: 
                   5407:     Edit or look up  an item in the scan_data hash.
                   5408: 
                   5409:   Arguments:
                   5410:     $scan_data  - The hash (see scantron_getfile)
                   5411:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5412:                   scantronfilename_key).
1.423     albertel 5413:     $data        - New value of the hash entry.
                   5414:     $delete      - If true, the entry is removed from the hash.
                   5415: 
                   5416:   Returns:
                   5417:     The new value of the hash table field (undefined if deleted).
                   5418: 
                   5419: =cut
                   5420: 
                   5421: 
1.157     albertel 5422: sub scan_data {
                   5423:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5424:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5425:     if (defined($value)) {
                   5426: 	$scan_data->{$filename.'_'.$key} = $value;
                   5427:     }
                   5428:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5429:     return $scan_data->{$filename.'_'.$key};
                   5430: }
1.423     albertel 5431: 
1.495     albertel 5432: # ----- These first few routines are general use routines.----
                   5433: 
                   5434: # Return the number of occurences of a pattern in a string.
                   5435: 
                   5436: sub occurence_count {
                   5437:     my ($string, $pattern) = @_;
                   5438: 
                   5439:     my @matches = ($string =~ /$pattern/g);
                   5440: 
                   5441:     return scalar(@matches);
                   5442: }
                   5443: 
                   5444: 
                   5445: # Take a string known to have digits and convert all the
                   5446: # digits into letters in the range J,A..I.
                   5447: 
                   5448: sub digits_to_letters {
                   5449:     my ($input) = @_;
                   5450: 
                   5451:     my @alphabet = ('J', 'A'..'I');
                   5452: 
                   5453:     my @input    = split(//, $input);
                   5454:     my $output ='';
                   5455:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5456: 	if ($input[$i] =~ /\d/) {
                   5457: 	    $output .= $alphabet[$input[$i]];
                   5458: 	} else {
                   5459: 	    $output .= $input[$i];
                   5460: 	}
                   5461:     }
                   5462:     return $output;
                   5463: }
                   5464: 
1.423     albertel 5465: =pod 
                   5466: 
                   5467: =item scantron_parse_scanline
                   5468: 
                   5469:   Decodes a scanline from the selected scantron file
                   5470: 
                   5471:  Arguments:
                   5472:     line             - The text of the scantron file line to process
                   5473:     whichline        - Line number
                   5474:     scantron_config  - Hash describing the format of the scantron lines.
                   5475:     scan_data        - Hash of extra information about the scanline
                   5476:                        (see scantron_getfile for more information)
                   5477:     just_header      - True if should not process question answers but only
                   5478:                        the stuff to the left of the answers.
                   5479:  Returns:
                   5480:    Hash containing the result of parsing the scanline
                   5481: 
                   5482:    Keys are all proceeded by the string 'scantron.'
                   5483: 
                   5484:        CODE    - the CODE in use for this scanline
                   5485:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5486:                  by the operator
                   5487:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5488:                             CODEs were selected, but the usage has been
                   5489:                             forced by the operator
                   5490:        ID  - student ID
                   5491:        PaperID - if used, the ID number printed on the sheet when the 
                   5492:                  paper was scanned
                   5493:        FirstName - first name from the sheet
                   5494:        LastName  - last name from the sheet
                   5495: 
                   5496:      if just_header was not true these key may also exist
                   5497: 
1.447     foxr     5498:        missingerror - a list of bubble ranges that are considered to be answers
                   5499:                       to a single question that don't have any bubbles filled in.
                   5500:                       Of the form questionnumber:firstbubblenumber:count.
                   5501:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5502:                       to a single question that have more than one bubble filled in.
                   5503:                       Of the form questionnumber::firstbubblenumber:count
                   5504:    
                   5505:                 In the above, count is the number of bubble responses in the
                   5506:                 input line needed to represent the possible answers to the question.
                   5507:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5508:                 per line would have count = 2.
                   5509: 
1.423     albertel 5510:        maxquest     - the number of the last bubble line that was parsed
                   5511: 
                   5512:        (<number> starts at 1)
                   5513:        <number>.answer - zero or more letters representing the selected
                   5514:                          letters from the scanline for the bubble line 
                   5515:                          <number>.
                   5516:                          if blank there was either no bubble or there where
                   5517:                          multiple bubbles, (consult the keys missingerror and
                   5518:                          doubleerror if this is an error condition)
                   5519: 
                   5520: =cut
                   5521: 
1.82      albertel 5522: sub scantron_parse_scanline {
1.423     albertel 5523:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5524: 
1.82      albertel 5525:     my %record;
1.422     foxr     5526:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5527:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5528:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5529: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5530: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5531: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5532: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5533: 	    $record{'scantron.CODE'}=substr($data,
                   5534: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5535: 					    $$scantron_config{'CODElength'});
1.191     albertel 5536: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5537: 		$record{'scantron.useCODE'}=1;
                   5538: 	    }
1.192     albertel 5539: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5540: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5541: 	    }
1.82      albertel 5542: 	} else {
                   5543: 	    #FIXME interpret first N questions
                   5544: 	}
                   5545:     }
1.83      albertel 5546:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5547: 				  $$scantron_config{'IDlength'});
1.157     albertel 5548:     $record{'scantron.PaperID'}=
                   5549: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5550: 	       $$scantron_config{'PaperIDlength'});
                   5551:     $record{'scantron.FirstName'}=
                   5552: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5553: 	       $$scantron_config{'FirstNamelength'});
                   5554:     $record{'scantron.LastName'}=
                   5555: 	substr($data,$$scantron_config{'LastName'}-1,
                   5556: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5557:     if ($just_header) { return \%record; }
1.194     albertel 5558: 
1.82      albertel 5559:     my @alphabet=('A'..'Z');
                   5560:     my $questnum=0;
1.447     foxr     5561:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5562: 
1.470     foxr     5563:     chomp($questions);		# Get rid of any trailing \n.
                   5564:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5565:     while (length($questions)) {
1.447     foxr     5566: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5567:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5568:                              || 1;
                   5569:         $questnum++;
                   5570:         my $quest_id = $questnum;
                   5571:         my $currentquest = substr($questions,0,$answer_length);
                   5572:         $questions       = substr($questions,$answer_length);
                   5573:         if (length($currentquest) < $answer_length) { next; }
                   5574: 
                   5575:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5576:             my $subquestnum = 1;
                   5577:             my $subquestions = $currentquest;
                   5578:             my @subanswers_needed = 
                   5579:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5580:             foreach my $subans (@subanswers_needed) {
                   5581:                 my $subans_length =
                   5582:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5583:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5584:                 $subquestions   = substr($subquestions,$subans_length);
                   5585:                 $quest_id = "$questnum.$subquestnum";
                   5586:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5587:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5588:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5589:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5590:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5591:                 } else {
                   5592:                     $ansnum = &scantron_validator_positional($ansnum,
                   5593:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5594:                 }
                   5595:                 $subquestnum ++;
                   5596:             }
                   5597:         } else {
                   5598:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5599:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5600:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5601:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5602:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5603:             } else {
                   5604:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5605:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5606:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5607:             }
                   5608:         }
                   5609:     }
                   5610:     $record{'scantron.maxquest'}=$questnum;
                   5611:     return \%record;
                   5612: }
1.447     foxr     5613: 
1.503     raeburn  5614: sub scantron_validator_lettnum {
                   5615:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5616:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5617: 
                   5618:     # Qon 'letter' implies for each slot in currquest we have:
                   5619:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5620:     #    about anything else (esp. a value of Qoff) for missing
                   5621:     #    bubbles.
                   5622:     #
                   5623:     # Qon 'number' implies each slot gives a digit that indexes the
                   5624:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5625:     #    and * or ? for double bubbles on a single line.
                   5626:     #
1.447     foxr     5627: 
1.503     raeburn  5628:     my $matchon;
                   5629:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5630:         $matchon = '[A-Z]';
                   5631:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5632:         $matchon = '\d';
                   5633:     }
                   5634:     my $occurrences = 0;
                   5635:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5636:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5637:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5638:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5639:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5640:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5641:         my @singlelines = split('',$currquest);
                   5642:         foreach my $entry (@singlelines) {
                   5643:             $occurrences = &occurence_count($entry,$matchon);
                   5644:             if ($occurrences > 1) {
                   5645:                 last;
                   5646:             }
                   5647:         } 
                   5648:     } else {
                   5649:         $occurrences = &occurence_count($currquest,$matchon); 
                   5650:     }
                   5651:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5652:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5653:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5654:             my $bubble = substr($currquest,$ans,1);
                   5655:             if ($bubble =~ /$matchon/ ) {
                   5656:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5657:                     if ($bubble == 0) {
                   5658:                         $bubble = 10; 
                   5659:                     }
                   5660:                     $record->{"scantron.$ansnum.answer"} = 
                   5661:                         $alphabet->[$bubble-1];
                   5662:                 } else {
                   5663:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5664:                 }
                   5665:             } else {
                   5666:                 $record->{"scantron.$ansnum.answer"}='';
                   5667:             }
                   5668:             $ansnum++;
                   5669:         }
                   5670:     } elsif (!defined($currquest)
                   5671:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5672:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5673:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5674:             $record->{"scantron.$ansnum.answer"}='';
                   5675:             $ansnum++;
                   5676:         }
                   5677:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5678:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5679:         }
                   5680:     } else {
                   5681:         if ($$scantron_config{'Qon'} eq 'number') {
                   5682:             $currquest = &digits_to_letters($currquest);            
                   5683:         }
                   5684:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5685:             my $bubble = substr($currquest,$ans,1);
                   5686:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5687:             $ansnum++;
                   5688:         }
                   5689:     }
                   5690:     return $ansnum;
                   5691: }
1.447     foxr     5692: 
1.503     raeburn  5693: sub scantron_validator_positional {
                   5694:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5695:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5696: 
1.503     raeburn  5697:     # Otherwise there's a positional notation;
                   5698:     # each bubble line requires Qlength items, and there are filled in
                   5699:     # bubbles for each case where there 'Qon' characters.
                   5700:     #
1.447     foxr     5701: 
1.503     raeburn  5702:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5703: 
1.503     raeburn  5704:     # If the split only gives us one element.. the full length of the
                   5705:     # answer string, no bubbles are filled in:
1.447     foxr     5706: 
1.507     raeburn  5707:     if ($answers_needed eq '') {
                   5708:         return;
                   5709:     }
                   5710: 
1.503     raeburn  5711:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5712:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5713:             $record->{"scantron.$ansnum.answer"}='';
                   5714:             $ansnum++;
                   5715:         }
                   5716:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5717:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5718:         }
                   5719:     } elsif (scalar(@array) == 2) {
                   5720:         my $location = length($array[0]);
                   5721:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5722:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5723:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5724:             if ($ans eq $line_num) {
                   5725:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5726:             } else {
                   5727:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5728:             }
                   5729:             $ansnum++;
                   5730:          }
                   5731:     } else {
                   5732:         #  If there's more than one instance of a bubble character
                   5733:         #  That's a double bubble; with positional notation we can
                   5734:         #  record all the bubbles filled in as well as the
                   5735:         #  fact this response consists of multiple bubbles.
                   5736:         #
                   5737:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5738:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5739:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5740:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5741:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5742:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5743:             my $doubleerror = 0;
                   5744:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5745:                    (!$doubleerror)) {
                   5746:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5747:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5748:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5749:                if (length(@currarray) > 2) {
                   5750:                    $doubleerror = 1;
                   5751:                } 
                   5752:             }
                   5753:             if ($doubleerror) {
                   5754:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5755:             }
                   5756:         } else {
                   5757:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5758:         }
                   5759:         my $item = $ansnum;
                   5760:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5761:             $record->{"scantron.$item.answer"} = '';
                   5762:             $item ++;
                   5763:         }
1.447     foxr     5764: 
1.503     raeburn  5765:         my @ans=@array;
                   5766:         my $i=0;
                   5767:         my $increment = 0;
                   5768:         while ($#ans) {
                   5769:             $i+=length($ans[0]) + $increment;
                   5770:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5771:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5772:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5773:             shift(@ans);
                   5774:             $increment = 1;
                   5775:         }
                   5776:         $ansnum += $answers_needed;
1.82      albertel 5777:     }
1.503     raeburn  5778:     return $ansnum;
1.82      albertel 5779: }
                   5780: 
1.423     albertel 5781: =pod
                   5782: 
                   5783: =item scantron_add_delay
                   5784: 
                   5785:    Adds an error message that occurred during the grading phase to a
                   5786:    queue of messages to be shown after grading pass is complete
                   5787: 
                   5788:  Arguments:
1.424     albertel 5789:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5790:    $scanline    - the scanline that caused the error
                   5791:    $errormesage - the error message
                   5792:    $errorcode   - a numeric code for the error
                   5793: 
                   5794:  Side Effects:
1.424     albertel 5795:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5796: 
                   5797: =cut
                   5798: 
1.82      albertel 5799: sub scantron_add_delay {
1.140     albertel 5800:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5801:     push(@$delayqueue,
                   5802: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5803: 	  'ecode' => $errorcode }
                   5804: 	 );
1.82      albertel 5805: }
                   5806: 
1.423     albertel 5807: =pod
                   5808: 
                   5809: =item scantron_find_student
                   5810: 
1.424     albertel 5811:    Finds the username for the current scanline
                   5812: 
                   5813:   Arguments:
                   5814:    $scantron_record - hash result from scantron_parse_scanline
                   5815:    $scan_data       - hash of correction information 
                   5816:                       (see &scantron_getfile() form more information)
                   5817:    $idmap           - hash from &username_to_idmap()
                   5818:    $line            - number of current scanline
                   5819:  
                   5820:   Returns:
                   5821:    Either 'username:domain' or undef if unknown
                   5822: 
1.423     albertel 5823: =cut
                   5824: 
1.82      albertel 5825: sub scantron_find_student {
1.157     albertel 5826:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5827:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5828:     if ($scanID =~ /^\s*$/) {
                   5829:  	return &scan_data($scan_data,"$line.user");
                   5830:     }
1.83      albertel 5831:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5832:  	if (lc($id) eq lc($scanID)) {
                   5833:  	    return $$idmap{$id};
                   5834:  	}
1.83      albertel 5835:     }
                   5836:     return undef;
                   5837: }
                   5838: 
1.423     albertel 5839: =pod
                   5840: 
                   5841: =item scantron_filter
                   5842: 
1.424     albertel 5843:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5844:    hidden resources was selected
                   5845: 
1.423     albertel 5846: =cut
                   5847: 
1.83      albertel 5848: sub scantron_filter {
                   5849:     my ($curres)=@_;
1.331     albertel 5850: 
                   5851:     if (ref($curres) && $curres->is_problem()) {
                   5852: 	# if the user has asked to not have either hidden
                   5853: 	# or 'randomout' controlled resources to be graded
                   5854: 	# don't include them
                   5855: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5856: 	    && $curres->randomout) {
                   5857: 	    return 0;
                   5858: 	}
1.83      albertel 5859: 	return 1;
                   5860:     }
                   5861:     return 0;
1.82      albertel 5862: }
                   5863: 
1.423     albertel 5864: =pod
                   5865: 
                   5866: =item scantron_process_corrections
                   5867: 
1.424     albertel 5868:    Gets correction information out of submitted form data and corrects
                   5869:    the scanline
                   5870: 
1.423     albertel 5871: =cut
                   5872: 
1.157     albertel 5873: sub scantron_process_corrections {
                   5874:     my ($r) = @_;
1.257     albertel 5875:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5876:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5877:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5878:     my $which=$env{'form.scantron_line'};
1.200     albertel 5879:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5880:     my ($skip,$err,$errmsg);
1.257     albertel 5881:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5882: 	$skip=1;
1.257     albertel 5883:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5884: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5885: 	    $env{'form.scantron_domain'};
1.157     albertel 5886: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5887: 	($line,$err,$errmsg)=
                   5888: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5889: 				     'ID',{'newid'=>$newid,
1.257     albertel 5890: 				    'username'=>$env{'form.scantron_username'},
                   5891: 				    'domain'=>$env{'form.scantron_domain'}});
                   5892:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5893: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5894: 	my $newCODE;
1.192     albertel 5895: 	my %args;
1.190     albertel 5896: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5897: 	    $newCODE='use_unfound';
1.190     albertel 5898: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5899: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5900: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5901: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5902: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5903: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5904: 	}
1.257     albertel 5905: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5906: 	    $args{'CODE_ignore_dup'}=1;
                   5907: 	}
                   5908: 	$args{'CODE'}=$newCODE;
1.186     albertel 5909: 	($line,$err,$errmsg)=
                   5910: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5911: 				     'CODE',\%args);
1.257     albertel 5912:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5913: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5914: 	    ($line,$err,$errmsg)=
                   5915: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5916: 					 $which,'answer',
                   5917: 					 { 'question'=>$question,
1.503     raeburn  5918: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5919:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5920: 	    if ($err) { last; }
                   5921: 	}
                   5922:     }
                   5923:     if ($err) {
1.398     albertel 5924: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5925:     } else {
1.200     albertel 5926: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5927: 	&scantron_putfile($scanlines,$scan_data);
                   5928:     }
                   5929: }
                   5930: 
1.423     albertel 5931: =pod
                   5932: 
                   5933: =item reset_skipping_status
                   5934: 
1.424     albertel 5935:    Forgets the current set of remember skipped scanlines (and thus
                   5936:    reverts back to considering all lines in the
                   5937:    scantron_skipped_<filename> file)
                   5938: 
1.423     albertel 5939: =cut
                   5940: 
1.200     albertel 5941: sub reset_skipping_status {
                   5942:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5943:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5944:     &scantron_putfile(undef,$scan_data);
                   5945: }
                   5946: 
1.423     albertel 5947: =pod
                   5948: 
                   5949: =item start_skipping
                   5950: 
1.424     albertel 5951:    Marks a scanline to be skipped. 
                   5952: 
1.423     albertel 5953: =cut
                   5954: 
1.376     albertel 5955: sub start_skipping {
1.200     albertel 5956:     my ($scan_data,$i)=@_;
                   5957:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5958:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5959: 	$remembered{$i}=2;
                   5960:     } else {
                   5961: 	$remembered{$i}=1;
                   5962:     }
1.200     albertel 5963:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5964: }
                   5965: 
1.423     albertel 5966: =pod
                   5967: 
                   5968: =item should_be_skipped
                   5969: 
1.424     albertel 5970:    Checks whether a scanline should be skipped.
                   5971: 
1.423     albertel 5972: =cut
                   5973: 
1.200     albertel 5974: sub should_be_skipped {
1.376     albertel 5975:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5976:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5977: 	# not redoing old skips
1.376     albertel 5978: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5979: 	return 0;
                   5980:     }
                   5981:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5982: 
                   5983:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5984: 	return 0;
                   5985:     }
1.200     albertel 5986:     return 1;
                   5987: }
                   5988: 
1.423     albertel 5989: =pod
                   5990: 
                   5991: =item remember_current_skipped
                   5992: 
1.424     albertel 5993:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5994:    file and remembers them into scan_data for later use.
                   5995: 
1.423     albertel 5996: =cut
                   5997: 
1.200     albertel 5998: sub remember_current_skipped {
                   5999:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6000:     my %to_remember;
                   6001:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6002: 	if ($scanlines->{'skipped'}[$i]) {
                   6003: 	    $to_remember{$i}=1;
                   6004: 	}
                   6005:     }
1.376     albertel 6006: 
1.200     albertel 6007:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6008:     &scantron_putfile(undef,$scan_data);
                   6009: }
                   6010: 
1.423     albertel 6011: =pod
                   6012: 
                   6013: =item check_for_error
                   6014: 
1.424     albertel 6015:     Checks if there was an error when attempting to remove a specific
                   6016:     scantron_.. bubble sheet data file. Prints out an error if
                   6017:     something went wrong.
                   6018: 
1.423     albertel 6019: =cut
                   6020: 
1.200     albertel 6021: sub check_for_error {
                   6022:     my ($r,$result)=@_;
                   6023:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6024: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6025:     }
                   6026: }
1.157     albertel 6027: 
1.423     albertel 6028: =pod
                   6029: 
                   6030: =item scantron_warning_screen
                   6031: 
1.424     albertel 6032:    Interstitial screen to make sure the operator has selected the
                   6033:    correct options before we start the validation phase.
                   6034: 
1.423     albertel 6035: =cut
                   6036: 
1.203     albertel 6037: sub scantron_warning_screen {
                   6038:     my ($button_text)=@_;
1.257     albertel 6039:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6040:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6041:     my $CODElist;
1.284     albertel 6042:     if ($scantron_config{'CODElocation'} &&
                   6043: 	$scantron_config{'CODEstart'} &&
                   6044: 	$scantron_config{'CODElength'}) {
                   6045: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6046: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6047: 	$CODElist=
1.492     albertel 6048: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6049: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6050:     }
1.492     albertel 6051:     return ('
1.203     albertel 6052: <p>
1.492     albertel 6053: <span class="LC_warning">
                   6054: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6055: </p>
                   6056: <table>
1.492     albertel 6057: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6058: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6059: '.$CODElist.'
1.203     albertel 6060: </table>
                   6061: <br />
1.492     albertel 6062: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6063: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6064: 
                   6065: <br />
1.492     albertel 6066: ');
1.203     albertel 6067: }
                   6068: 
1.423     albertel 6069: =pod
                   6070: 
                   6071: =item scantron_do_warning
                   6072: 
1.424     albertel 6073:    Check if the operator has picked something for all required
                   6074:    fields. Error out if something is missing.
                   6075: 
1.423     albertel 6076: =cut
                   6077: 
1.203     albertel 6078: sub scantron_do_warning {
                   6079:     my ($r)=@_;
1.324     albertel 6080:     my ($symb)=&get_symb($r);
1.203     albertel 6081:     if (!$symb) {return '';}
1.324     albertel 6082:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6083:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6084:     if ( $env{'form.selectpage'} eq '' ||
                   6085: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6086: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6087: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6088: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6089: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6090: 	} 
1.257     albertel 6091: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6092: 	    $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 6093: 	} 
1.257     albertel 6094: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6095: 	    $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 6096: 	} 
                   6097:     } else {
1.265     www      6098: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6099: 	$r->print('
                   6100: '.$warning.'
                   6101: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6102: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6103: ');
1.237     albertel 6104:     }
1.352     albertel 6105:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6106:     return '';
                   6107: }
                   6108: 
1.423     albertel 6109: =pod
                   6110: 
                   6111: =item scantron_form_start
                   6112: 
1.424     albertel 6113:     html hidden input for remembering all selected grading options
                   6114: 
1.423     albertel 6115: =cut
                   6116: 
1.203     albertel 6117: sub scantron_form_start {
                   6118:     my ($max_bubble)=@_;
                   6119:     my $result= <<SCANTRONFORM;
                   6120: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6121:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6122:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6123:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6124:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6125:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6126:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6127:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6128:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6129:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6130: SCANTRONFORM
1.447     foxr     6131: 
                   6132:   my $line = 0;
                   6133:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6134:        my $chunk =
                   6135: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6136:        $chunk .=
                   6137: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6138:        $chunk .= 
                   6139:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6140:        $chunk .=
                   6141:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6142:        $result .= $chunk;
                   6143:        $line++;
                   6144:    }
1.203     albertel 6145:     return $result;
                   6146: }
                   6147: 
1.423     albertel 6148: =pod
                   6149: 
                   6150: =item scantron_validate_file
                   6151: 
1.424     albertel 6152:     Dispatch routine for doing validation of a bubble sheet data file.
                   6153: 
                   6154:     Also processes any necessary information resets that need to
                   6155:     occur before validation begins (ignore previous corrections,
                   6156:     restarting the skipped records processing)
                   6157: 
1.423     albertel 6158: =cut
                   6159: 
1.157     albertel 6160: sub scantron_validate_file {
                   6161:     my ($r) = @_;
1.324     albertel 6162:     my ($symb)=&get_symb($r);
1.157     albertel 6163:     if (!$symb) {return '';}
1.324     albertel 6164:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6165:     
                   6166:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6167:     # them when doing the corrections reset
1.257     albertel 6168:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6169: 	&reset_skipping_status();
                   6170:     }
1.257     albertel 6171:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6172: 	&remember_current_skipped();
1.257     albertel 6173: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6174:     }
                   6175: 
1.257     albertel 6176:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6177: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6178: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6179: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6180: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6181:     }
1.200     albertel 6182: 
1.257     albertel 6183:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6184: 	&scantron_process_corrections($r);
                   6185:     }
1.503     raeburn  6186:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6187:     #get the student pick code ready
                   6188:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6189:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6190:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6191:     $r->print($result);
                   6192:     
1.334     albertel 6193:     my @validate_phases=( 'sequence',
                   6194: 			  'ID',
1.157     albertel 6195: 			  'CODE',
                   6196: 			  'doublebubble',
                   6197: 			  'missingbubbles');
1.257     albertel 6198:     if (!$env{'form.validatepass'}) {
                   6199: 	$env{'form.validatepass'} = 0;
1.157     albertel 6200:     }
1.257     albertel 6201:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6202: 
1.448     foxr     6203: 
1.157     albertel 6204:     my $stop=0;
                   6205:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6206: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6207: 	$r->rflush();
                   6208: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6209: 	{
                   6210: 	    no strict 'refs';
                   6211: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6212: 	}
                   6213:     }
                   6214:     if (!$stop) {
1.203     albertel 6215: 	my $warning=&scantron_warning_screen('Start Grading');
1.512     www      6216: 	$r->print(&mt('Validation process complete.').'<br />
1.492     albertel 6217: '.$warning.'
                   6218: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6219: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6220: ');
1.203     albertel 6221: 
1.157     albertel 6222:     } else {
                   6223: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6224: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6225:     }
                   6226:     if ($stop) {
1.334     albertel 6227: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6228: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6229: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6230: 
1.492     albertel 6231: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6232: 	} else {
1.503     raeburn  6233:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
                   6234: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
                   6235:             } else {
                   6236:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6237:             }
1.492     albertel 6238: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6239: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6240: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6241: 	}
1.157     albertel 6242:     }
1.352     albertel 6243:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6244:     return '';
                   6245: }
                   6246: 
1.423     albertel 6247: 
                   6248: =pod
                   6249: 
                   6250: =item scantron_remove_file
                   6251: 
1.424     albertel 6252:    Removes the requested bubble sheet data file, makes sure that
                   6253:    scantron_original_<filename> is never removed
                   6254: 
                   6255: 
1.423     albertel 6256: =cut
                   6257: 
1.200     albertel 6258: sub scantron_remove_file {
1.192     albertel 6259:     my ($which)=@_;
1.257     albertel 6260:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6261:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6262:     my $file='scantron_';
1.200     albertel 6263:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6264: 	$file.=$which.'_';
1.192     albertel 6265:     } else {
                   6266: 	return 'refused';
                   6267:     }
1.257     albertel 6268:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6269:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6270: }
                   6271: 
1.423     albertel 6272: 
                   6273: =pod
                   6274: 
                   6275: =item scantron_remove_scan_data
                   6276: 
1.424     albertel 6277:    Removes all scan_data correction for the requested bubble sheet
                   6278:    data file.  (In the case that both the are doing skipped records we need
                   6279:    to remember the old skipped lines for the time being so that element
                   6280:    persists for a while.)
                   6281: 
1.423     albertel 6282: =cut
                   6283: 
1.200     albertel 6284: sub scantron_remove_scan_data {
1.257     albertel 6285:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6286:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6287:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6288:     my @todelete;
1.257     albertel 6289:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6290:     foreach my $key (@keys) {
                   6291: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6292: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6293: 		$key=~/remember_skipping/) {
                   6294: 		next;
                   6295: 	    }
1.192     albertel 6296: 	    push(@todelete,$key);
                   6297: 	}
                   6298:     }
1.200     albertel 6299:     my $result;
1.192     albertel 6300:     if (@todelete) {
1.491     albertel 6301: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6302: 				       \@todelete,$cdom,$cname);
                   6303:     } else {
                   6304: 	$result = 'ok';
1.192     albertel 6305:     }
                   6306:     return $result;
                   6307: }
                   6308: 
1.423     albertel 6309: 
                   6310: =pod
                   6311: 
                   6312: =item scantron_getfile
                   6313: 
1.424     albertel 6314:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6315:     the scan_data hash
                   6316:   
                   6317:   Arguments:
                   6318:     None
                   6319: 
                   6320:   Returns:
                   6321:     2 hash references
                   6322: 
                   6323:      - first one has 
                   6324:          orig      -
                   6325:          corrected -
                   6326:          skipped   -  each of which points to an array ref of the specified
                   6327:                       file broken up into individual lines
                   6328:          count     - number of scanlines
                   6329:  
                   6330:      - second is the scan_data hash possible keys are
1.425     albertel 6331:        ($number refers to scanline numbered $number and thus the key affects
                   6332:         only that scanline
                   6333:         $bubline refers to the specific bubble line element and the aspects
                   6334:         refers to that specific bubble line element)
                   6335: 
                   6336:        $number.user - username:domain to use
                   6337:        $number.CODE_ignore_dup 
                   6338:                     - ignore the duplicate CODE error 
                   6339:        $number.useCODE
                   6340:                     - use the CODE in the scanline as is
                   6341:        $number.no_bubble.$bubline
                   6342:                     - it is valid that there is no bubbled in bubble
                   6343:                       at $number $bubline
                   6344:        remember_skipping
                   6345:                     - a frozen hash containing keys of $number and values
                   6346:                       of either 
                   6347:                         1 - we are on a 'do skipped records pass' and plan
                   6348:                             on processing this line
                   6349:                         2 - we are on a 'do skipped records pass' and this
                   6350:                             scanline has been marked to skip yet again
1.424     albertel 6351: 
1.423     albertel 6352: =cut
                   6353: 
1.157     albertel 6354: sub scantron_getfile {
1.200     albertel 6355:     #FIXME really would prefer a scantron directory
1.257     albertel 6356:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6357:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6358:     my $lines;
                   6359:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6360: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6361:     my %scanlines;
                   6362:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6363:     my $temp=$scanlines{'orig'};
                   6364:     $scanlines{'count'}=$#$temp;
                   6365: 
                   6366:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6367: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6368:     if ($lines eq '-1') {
                   6369: 	$scanlines{'corrected'}=[];
                   6370:     } else {
                   6371: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6372:     }
                   6373:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6374: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6375:     if ($lines eq '-1') {
                   6376: 	$scanlines{'skipped'}=[];
                   6377:     } else {
                   6378: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6379:     }
1.175     albertel 6380:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6381:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6382:     my %scan_data = @tmp;
                   6383:     return (\%scanlines,\%scan_data);
                   6384: }
                   6385: 
1.423     albertel 6386: =pod
                   6387: 
                   6388: =item lonnet_putfile
                   6389: 
1.424     albertel 6390:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6391: 
                   6392:  Arguments:
                   6393:    $contents - data to store
                   6394:    $filename - filename to store $contents into
                   6395: 
                   6396:  Returns:
                   6397:    result value from &Apache::lonnet::finishuserfileupload
                   6398: 
1.423     albertel 6399: =cut
                   6400: 
1.157     albertel 6401: sub lonnet_putfile {
                   6402:     my ($contents,$filename)=@_;
1.257     albertel 6403:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6404:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6405:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6406:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6407: 
                   6408: }
                   6409: 
1.423     albertel 6410: =pod
                   6411: 
                   6412: =item scantron_putfile
                   6413: 
1.424     albertel 6414:     Stores the current version of the bubble sheet data files, and the
                   6415:     scan_data hash. (Does not modify the original version only the
                   6416:     corrected and skipped versions.
                   6417: 
                   6418:  Arguments:
                   6419:     $scanlines - hash ref that looks like the first return value from
                   6420:                  &scantron_getfile()
                   6421:     $scan_data - hash ref that looks like the second return value from
                   6422:                  &scantron_getfile()
                   6423: 
1.423     albertel 6424: =cut
                   6425: 
1.157     albertel 6426: sub scantron_putfile {
                   6427:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6428:     #FIXME really would prefer a scantron directory
1.257     albertel 6429:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6430:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6431:     if ($scanlines) {
                   6432: 	my $prefix='scantron_';
1.157     albertel 6433: # no need to update orig, shouldn't change
                   6434: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6435: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6436: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6437: 			$prefix.'corrected_'.
1.257     albertel 6438: 			$env{'form.scantron_selectfile'});
1.200     albertel 6439: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6440: 			$prefix.'skipped_'.
1.257     albertel 6441: 			$env{'form.scantron_selectfile'});
1.200     albertel 6442:     }
1.175     albertel 6443:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6444: }
                   6445: 
1.423     albertel 6446: =pod
                   6447: 
                   6448: =item scantron_get_line
                   6449: 
1.424     albertel 6450:    Returns the correct version of the scanline
                   6451: 
                   6452:  Arguments:
                   6453:     $scanlines - hash ref that looks like the first return value from
                   6454:                  &scantron_getfile()
                   6455:     $scan_data - hash ref that looks like the second return value from
                   6456:                  &scantron_getfile()
                   6457:     $i         - number of the requested line (starts at 0)
                   6458: 
                   6459:  Returns:
                   6460:    A scanline, (either the original or the corrected one if it
                   6461:    exists), or undef if the requested scanline should be
                   6462:    skipped. (Either because it's an skipped scanline, or it's an
                   6463:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6464:    pass.
                   6465: 
1.423     albertel 6466: =cut
                   6467: 
1.157     albertel 6468: sub scantron_get_line {
1.200     albertel 6469:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6470:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6471:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6472:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6473:     return $scanlines->{'orig'}[$i]; 
                   6474: }
                   6475: 
1.423     albertel 6476: =pod
                   6477: 
                   6478: =item scantron_todo_count
                   6479: 
1.424     albertel 6480:     Counts the number of scanlines that need processing.
                   6481: 
                   6482:  Arguments:
                   6483:     $scanlines - hash ref that looks like the first return value from
                   6484:                  &scantron_getfile()
                   6485:     $scan_data - hash ref that looks like the second return value from
                   6486:                  &scantron_getfile()
                   6487: 
                   6488:  Returns:
                   6489:     $count - number of scanlines to process
                   6490: 
1.423     albertel 6491: =cut
                   6492: 
1.200     albertel 6493: sub get_todo_count {
                   6494:     my ($scanlines,$scan_data)=@_;
                   6495:     my $count=0;
                   6496:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6497: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6498: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6499: 	$count++;
                   6500:     }
                   6501:     return $count;
                   6502: }
                   6503: 
1.423     albertel 6504: =pod
                   6505: 
                   6506: =item scantron_put_line
                   6507: 
1.424     albertel 6508:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6509:     data file.
                   6510: 
                   6511:  Arguments:
                   6512:     $scanlines - hash ref that looks like the first return value from
                   6513:                  &scantron_getfile()
                   6514:     $scan_data - hash ref that looks like the second return value from
                   6515:                  &scantron_getfile()
                   6516:     $i         - line number to update
                   6517:     $newline   - contents of the updated scanline
                   6518:     $skip      - if true make the line for skipping and update the
                   6519:                  'skipped' file
                   6520: 
1.423     albertel 6521: =cut
                   6522: 
1.157     albertel 6523: sub scantron_put_line {
1.200     albertel 6524:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6525:     if ($skip) {
                   6526: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6527: 	&start_skipping($scan_data,$i);
1.157     albertel 6528: 	return;
                   6529:     }
                   6530:     $scanlines->{'corrected'}[$i]=$newline;
                   6531: }
                   6532: 
1.423     albertel 6533: =pod
                   6534: 
                   6535: =item scantron_clear_skip
                   6536: 
1.424     albertel 6537:    Remove a line from the 'skipped' file
                   6538: 
                   6539:  Arguments:
                   6540:     $scanlines - hash ref that looks like the first return value from
                   6541:                  &scantron_getfile()
                   6542:     $scan_data - hash ref that looks like the second return value from
                   6543:                  &scantron_getfile()
                   6544:     $i         - line number to update
                   6545: 
1.423     albertel 6546: =cut
                   6547: 
1.376     albertel 6548: sub scantron_clear_skip {
                   6549:     my ($scanlines,$scan_data,$i)=@_;
                   6550:     if (exists($scanlines->{'skipped'}[$i])) {
                   6551: 	undef($scanlines->{'skipped'}[$i]);
                   6552: 	return 1;
                   6553:     }
                   6554:     return 0;
                   6555: }
                   6556: 
1.423     albertel 6557: =pod
                   6558: 
                   6559: =item scantron_filter_not_exam
                   6560: 
1.424     albertel 6561:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6562:    filter out resources that are not marked as 'exam' mode
                   6563: 
1.423     albertel 6564: =cut
                   6565: 
1.334     albertel 6566: sub scantron_filter_not_exam {
                   6567:     my ($curres)=@_;
                   6568:     
                   6569:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6570: 	# if the user has asked to not have either hidden
                   6571: 	# or 'randomout' controlled resources to be graded
                   6572: 	# don't include them
                   6573: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6574: 	    && $curres->randomout) {
                   6575: 	    return 0;
                   6576: 	}
                   6577: 	return 1;
                   6578:     }
                   6579:     return 0;
                   6580: }
                   6581: 
1.423     albertel 6582: =pod
                   6583: 
                   6584: =item scantron_validate_sequence
                   6585: 
1.424     albertel 6586:     Validates the selected sequence, checking for resource that are
                   6587:     not set to exam mode.
                   6588: 
1.423     albertel 6589: =cut
                   6590: 
1.334     albertel 6591: sub scantron_validate_sequence {
                   6592:     my ($r,$currentphase) = @_;
                   6593: 
                   6594:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6595:     my (undef,undef,$sequence)=
                   6596: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6597: 
                   6598:     my $map=$navmap->getResourceByUrl($sequence);
                   6599: 
                   6600:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6601:                                     value="ignore" />');
                   6602:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6603: 	my @resources=
                   6604: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6605: 	if (@resources) {
1.357     banghart 6606: 	    $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 6607: 	    return (1,$currentphase);
                   6608: 	}
                   6609:     }
                   6610: 
                   6611:     return (0,$currentphase+1);
                   6612: }
                   6613: 
1.423     albertel 6614: =pod
                   6615: 
                   6616: =item scantron_validate_ID
                   6617: 
1.424     albertel 6618:    Validates all scanlines in the selected file to not have any
                   6619:    invalid or underspecified student IDs
                   6620: 
1.423     albertel 6621: =cut
                   6622: 
1.157     albertel 6623: sub scantron_validate_ID {
                   6624:     my ($r,$currentphase) = @_;
                   6625:     
                   6626:     #get student info
                   6627:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6628:     my %idmap=&username_to_idmap($classlist);
                   6629: 
                   6630:     #get scantron line setup
1.257     albertel 6631:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6632:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6633:     
                   6634:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6635: 
                   6636:     my %found=('ids'=>{},'usernames'=>{});
                   6637:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6638: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6639: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6640: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6641: 						 $scan_data);
                   6642: 	my $id=$$scan_record{'scantron.ID'};
                   6643: 	my $found;
                   6644: 	foreach my $checkid (keys(%idmap)) {
                   6645: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6646: 	}
                   6647: 	if ($found) {
                   6648: 	    my $username=$idmap{$found};
                   6649: 	    if ($found{'ids'}{$found}) {
                   6650: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6651: 					 $line,'duplicateID',$found);
1.194     albertel 6652: 		return(1,$currentphase);
1.157     albertel 6653: 	    } elsif ($found{'usernames'}{$username}) {
                   6654: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6655: 					 $line,'duplicateID',$username);
1.194     albertel 6656: 		return(1,$currentphase);
1.157     albertel 6657: 	    }
1.186     albertel 6658: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6659: 	    $found{'ids'}{$found}++;
                   6660: 	    $found{'usernames'}{$username}++;
                   6661: 	} else {
                   6662: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6663: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6664: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6665: 		    &scantron_get_correction($r,$i,$scan_record,
                   6666: 					     \%scantron_config,
                   6667: 					     $line,'duplicateID',$username);
1.194     albertel 6668: 		    return(1,$currentphase);
1.157     albertel 6669: 		} elsif (!defined($username)) {
                   6670: 		    &scantron_get_correction($r,$i,$scan_record,
                   6671: 					     \%scantron_config,
                   6672: 					     $line,'incorrectID');
1.194     albertel 6673: 		    return(1,$currentphase);
1.157     albertel 6674: 		}
                   6675: 		$found{'usernames'}{$username}++;
                   6676: 	    } else {
                   6677: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6678: 					 $line,'incorrectID');
1.194     albertel 6679: 		return(1,$currentphase);
1.157     albertel 6680: 	    }
                   6681: 	}
                   6682:     }
                   6683: 
                   6684:     return (0,$currentphase+1);
                   6685: }
                   6686: 
1.423     albertel 6687: =pod
                   6688: 
                   6689: =item scantron_get_correction
                   6690: 
1.424     albertel 6691:    Builds the interface screen to interact with the operator to fix a
                   6692:    specific error condition in a specific scanline
                   6693: 
                   6694:  Arguments:
                   6695:     $r           - Apache request object
                   6696:     $i           - number of the current scanline
                   6697:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6698:     $scan_config - hash ref as returned from &get_scantron_config()
                   6699:     $line        - full contents of the current scanline
                   6700:     $error       - error condition, valid values are
                   6701:                    'incorrectCODE', 'duplicateCODE',
                   6702:                    'doublebubble', 'missingbubble',
                   6703:                    'duplicateID', 'incorrectID'
                   6704:     $arg         - extra information needed
                   6705:        For errors:
                   6706:          - duplicateID   - paper number that this studentID was seen before on
                   6707:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6708:                            seen on before
                   6709:          - incorrectCODE - current incorrect CODE 
                   6710:          - doublebubble  - array ref of the bubble lines that have double
                   6711:                            bubble errors
                   6712:          - missingbubble - array ref of the bubble lines that have missing
                   6713:                            bubble errors
                   6714: 
1.423     albertel 6715: =cut
                   6716: 
1.157     albertel 6717: sub scantron_get_correction {
                   6718:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6719: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6720: #to show both the current line and the previous one and allow skipping
                   6721: #the previous one or the current one
                   6722: 
1.333     albertel 6723:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6724: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6725: 			    " for PaperID <tt>[_1]</tt>",
                   6726: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6727:     } else {
1.492     albertel 6728: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6729: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6730: 			    $i,$line)."</p> \n");
                   6731:     }
                   6732:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6733: 			  "The name on the paper is [_2],[_3]",
                   6734: 			  $$scan_record{'scantron.ID'},
                   6735: 			  $$scan_record{'scantron.LastName'},
                   6736: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6737: 
1.157     albertel 6738:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6739:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6740:                            # Array populated for doublebubble or
                   6741:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6742:                            # to validate radio button checking   
                   6743: 
1.157     albertel 6744:     if ($error =~ /ID$/) {
1.186     albertel 6745: 	if ($error eq 'incorrectID') {
1.492     albertel 6746: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6747: 		      "</p>\n");
1.157     albertel 6748: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6749: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6750: 	}
1.242     albertel 6751: 	$r->print($message);
1.492     albertel 6752: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6753: 	$r->print("\n<ul><li> ");
                   6754: 	#FIXME it would be nice if this sent back the user ID and
                   6755: 	#could do partial userID matches
                   6756: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6757: 				       'scantron_username','scantron_domain'));
                   6758: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6759: 	$r->print("\n@".
1.257     albertel 6760: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6761: 
                   6762: 	$r->print('</li>');
1.186     albertel 6763:     } elsif ($error =~ /CODE$/) {
                   6764: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6765: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6766: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6767: 	    $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 6768: 	}
1.492     albertel 6769: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6770: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6771: 	$r->print($message);
1.492     albertel 6772: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6773: 	$r->print("\n<br /> ");
1.194     albertel 6774: 	my $i=0;
1.273     albertel 6775: 	if ($error eq 'incorrectCODE' 
                   6776: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6777: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6778: 	    if ($closest > 0) {
                   6779: 		foreach my $testcode (@{$closest}) {
                   6780: 		    my $checked='';
1.401     albertel 6781: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6782: 		    $r->print("
                   6783:    <label>
                   6784:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6785:        ".&mt("Use the similar CODE [_1] instead.",
                   6786: 	    "<b><tt>".$testcode."</tt></b>")."
                   6787:     </label>
                   6788:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6789: 		    $r->print("\n<br />");
                   6790: 		    $i++;
                   6791: 		}
1.194     albertel 6792: 	    }
                   6793: 	}
1.273     albertel 6794: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6795: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6796: 	    $r->print("
                   6797:     <label>
                   6798:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6799:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6800: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6801:     </label>");
1.273     albertel 6802: 	    $r->print("\n<br />");
                   6803: 	}
1.194     albertel 6804: 
1.188     albertel 6805: 	$r->print(<<ENDSCRIPT);
                   6806: <script type="text/javascript">
                   6807: function change_radio(field) {
1.190     albertel 6808:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6809:     var i;
                   6810:     for (i=0;i<slct.length;i++) {
                   6811:         if (slct[i].value==field) { slct[i].checked=true; }
                   6812:     }
                   6813: }
                   6814: </script>
                   6815: ENDSCRIPT
1.187     albertel 6816: 	my $href="/adm/pickcode?".
1.359     www      6817: 	   "form=".&escape("scantronupload").
                   6818: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6819: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6820: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6821: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6822: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6823: 	    $r->print("
                   6824:     <label>
                   6825:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6826:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6827: 	     "<a target='_blank' href='$href'>","</a>")."
                   6828:     </label> 
                   6829:     ".&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 6830: 	    $r->print("\n<br />");
                   6831: 	}
1.492     albertel 6832: 	$r->print("
                   6833:     <label>
                   6834:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6835:        ".&mt("Use [_1] as the CODE.",
                   6836: 	     "</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 6837: 	$r->print("\n<br /><br />");
1.157     albertel 6838:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6839: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6840: 
                   6841: 	# The form field scantron_questions is acutally a list of line numbers.
                   6842: 	# represented by this form so:
                   6843: 
                   6844: 	my $line_list = &questions_to_line_list($arg);
                   6845: 
1.157     albertel 6846: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6847: 		  $line_list.'" />');
1.242     albertel 6848: 	$r->print($message);
1.492     albertel 6849: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6850: 	foreach my $question (@{$arg}) {
1.503     raeburn  6851: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6852:                                                    $scan_record, $error);
1.524     raeburn  6853:             push(@lines_to_correct,@linenums);
1.157     albertel 6854: 	}
1.503     raeburn  6855:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6856:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6857: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6858: 	$r->print($message);
1.492     albertel 6859: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6860: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6861: 
1.503     raeburn  6862: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6863: 	# a list of question numbers. Therefore:
                   6864: 	#
                   6865: 	
                   6866: 	my $line_list = &questions_to_line_list($arg);
                   6867: 
1.157     albertel 6868: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6869: 		  $line_list.'" />');
1.157     albertel 6870: 	foreach my $question (@{$arg}) {
1.503     raeburn  6871: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6872:                                                    $scan_record, $error);
1.524     raeburn  6873:             push(@lines_to_correct,@linenums);
1.157     albertel 6874: 	}
1.503     raeburn  6875:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6876:     } else {
                   6877: 	$r->print("\n<ul>");
                   6878:     }
                   6879:     $r->print("\n</li></ul>");
1.497     foxr     6880: }
                   6881: 
1.503     raeburn  6882: sub verify_bubbles_checked {
                   6883:     my (@ansnums) = @_;
                   6884:     my $ansnumstr = join('","',@ansnums);
                   6885:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6886:     my $output = (<<ENDSCRIPT);
                   6887: <script type="text/javascript">
                   6888: function verify_bubble_radio(form) {
                   6889:     var ansnumArray = new Array ("$ansnumstr");
                   6890:     var need_bubble_count = 0;
                   6891:     for (var i=0; i<ansnumArray.length; i++) {
                   6892:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6893:             var bubble_picked = 0; 
                   6894:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6895:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6896:                     bubble_picked = 1;
                   6897:                 }
                   6898:             }
                   6899:             if (bubble_picked == 0) {
                   6900:                 need_bubble_count ++;
                   6901:             }
                   6902:         }
                   6903:     }
                   6904:     if (need_bubble_count) {
                   6905:         alert("$warning");
                   6906:         return;
                   6907:     }
                   6908:     form.submit(); 
                   6909: }
                   6910: </script>
                   6911: ENDSCRIPT
                   6912:     return $output;
                   6913: }
                   6914: 
1.497     foxr     6915: =pod
                   6916: 
                   6917: =item  questions_to_line_list
1.157     albertel 6918: 
1.497     foxr     6919: Converts a list of questions into a string of comma separated
                   6920: line numbers in the answer sheet used by the questions.  This is
                   6921: used to fill in the scantron_questions form field.
                   6922: 
                   6923:   Arguments:
                   6924:      questions    - Reference to an array of questions.
                   6925: 
                   6926: =cut
                   6927: 
                   6928: 
                   6929: sub questions_to_line_list {
                   6930:     my ($questions) = @_;
                   6931:     my @lines;
                   6932: 
1.503     raeburn  6933:     foreach my $item (@{$questions}) {
                   6934:         my $question = $item;
                   6935:         my ($first,$count,$last);
                   6936:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6937:             $question = $1;
                   6938:             my $subquestion = $2;
                   6939:             $first = $first_bubble_line{$question-1} + 1;
                   6940:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6941:             my $subcount = 1;
                   6942:             while ($subcount<$subquestion) {
                   6943:                 $first += $subans[$subcount-1];
                   6944:                 $subcount ++;
                   6945:             }
                   6946:             $count = $subans[$subquestion-1];
                   6947:         } else {
                   6948: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6949: 	    $count   = $bubble_lines_per_response{$question-1};
                   6950:         }
1.506     raeburn  6951:         $last = $first+$count-1;
1.503     raeburn  6952:         push(@lines, ($first..$last));
1.497     foxr     6953:     }
                   6954:     return join(',', @lines);
                   6955: }
                   6956: 
                   6957: =pod 
                   6958: 
                   6959: =item prompt_for_corrections
                   6960: 
                   6961: Prompts for a potentially multiline correction to the
                   6962: user's bubbling (factors out common code from scantron_get_correction
                   6963: for multi and missing bubble cases).
                   6964: 
                   6965:  Arguments:
                   6966:    $r           - Apache request object.
                   6967:    $question    - The question number to prompt for.
                   6968:    $scan_config - The scantron file configuration hash.
                   6969:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6970:    $error       - Type of error
1.497     foxr     6971: 
                   6972:  Implicit inputs:
                   6973:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6974:                                   Numbered from 0 (but question numbers are from
                   6975:                                   1.
                   6976:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6977:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6978:                                   type problems render as separate sub-questions, 
1.503     raeburn  6979:                                   in exam mode. This hash contains a 
                   6980:                                   comma-separated list of the lines per 
                   6981:                                   sub-question.
1.510     raeburn  6982:    %responsetype_per_response   - essayresponse, formularesponse,
                   6983:                                   stringresponse, imageresponse, reactionresponse,
                   6984:                                   and organicresponse type problem parts can have
1.503     raeburn  6985:                                   multiple lines per response if the weight
                   6986:                                   assigned exceeds 10.  In this case, only
                   6987:                                   one bubble per line is permitted, but more 
                   6988:                                   than one line might contain bubbles, e.g.
                   6989:                                   bubbling of: line 1 - J, line 2 - J, 
                   6990:                                   line 3 - B would assign 22 points.  
1.497     foxr     6991: 
                   6992: =cut
                   6993: 
                   6994: sub prompt_for_corrections {
1.503     raeburn  6995:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6996:     my ($current_line,$lines);
                   6997:     my @linenums;
                   6998:     my $questionnum = $question;
                   6999:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7000:         $question = $1;
                   7001:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7002:         my $subquestion = $2;
                   7003:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7004:         my $subcount = 1;
                   7005:         while ($subcount<$subquestion) {
                   7006:             $current_line += $subans[$subcount-1];
                   7007:             $subcount ++;
                   7008:         }
                   7009:         $lines = $subans[$subquestion-1];
                   7010:     } else {
                   7011:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7012:         $lines        = $bubble_lines_per_response{$question-1};
                   7013:     }
1.497     foxr     7014:     if ($lines > 1) {
1.503     raeburn  7015:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7016:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7017:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7018:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7019:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7020:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7021:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7022:             $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 />');
                   7023:         } else {
                   7024:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7025:         }
1.497     foxr     7026:     }
                   7027:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7028:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7029: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7030: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7031:         push(@linenums,$current_line);
1.497     foxr     7032: 	$current_line++;
                   7033:     }
                   7034:     if ($lines > 1) {
                   7035: 	$r->print("<hr /><br />");
                   7036:     }
1.503     raeburn  7037:     return @linenums;
1.157     albertel 7038: }
1.423     albertel 7039: 
                   7040: =pod
                   7041: 
                   7042: =item scantron_bubble_selector
                   7043:   
                   7044:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7045:    possibly showing the existing the selected bubbles if known
1.423     albertel 7046: 
                   7047:  Arguments:
                   7048:     $r           - Apache request object
                   7049:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7050:     $line        - Number of the line being displayed.
1.503     raeburn  7051:     $questionnum - Question number (may include subquestion)
                   7052:     $error       - Type of error.
1.497     foxr     7053:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7054: 
                   7055: =cut
                   7056: 
1.157     albertel 7057: sub scantron_bubble_selector {
1.503     raeburn  7058:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7059:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7060: 
                   7061:     my $scmode=$$scan_config{'Qon'};
                   7062:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7063: 
1.157     albertel 7064:     my @alphabet=('A'..'Z');
1.503     raeburn  7065:     $r->print(&Apache::loncommon::start_data_table().
                   7066:               &Apache::loncommon::start_data_table_row());
                   7067:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7068:     for (my $i=0;$i<$max+1;$i++) {
                   7069: 	$r->print("\n".'<td align="center">');
                   7070: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7071: 	else { $r->print('&nbsp;'); }
                   7072: 	$r->print('</td>');
                   7073:     }
1.503     raeburn  7074:     $r->print(&Apache::loncommon::end_data_table_row().
                   7075:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7076:     for (my $i=0;$i<$max;$i++) {
                   7077: 	$r->print("\n".
                   7078: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7079: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7080:     }
1.503     raeburn  7081:     my $nobub_checked = ' ';
                   7082:     if ($error eq 'missingbubble') {
                   7083:         $nobub_checked = ' checked = "checked" ';
                   7084:     }
                   7085:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7086: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7087:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7088:               $line.'" value="'.$questionnum.'" /></td>');
                   7089:     $r->print(&Apache::loncommon::end_data_table_row().
                   7090:               &Apache::loncommon::end_data_table());
1.157     albertel 7091: }
                   7092: 
1.423     albertel 7093: =pod
                   7094: 
                   7095: =item num_matches
                   7096: 
1.424     albertel 7097:    Counts the number of characters that are the same between the two arguments.
                   7098: 
                   7099:  Arguments:
                   7100:    $orig - CODE from the scanline
                   7101:    $code - CODE to match against
                   7102: 
                   7103:  Returns:
                   7104:    $count - integer count of the number of same characters between the
                   7105:             two arguments
                   7106: 
1.423     albertel 7107: =cut
                   7108: 
1.194     albertel 7109: sub num_matches {
                   7110:     my ($orig,$code) = @_;
                   7111:     my @code=split(//,$code);
                   7112:     my @orig=split(//,$orig);
                   7113:     my $same=0;
                   7114:     for (my $i=0;$i<scalar(@code);$i++) {
                   7115: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7116:     }
                   7117:     return $same;
                   7118: }
                   7119: 
1.423     albertel 7120: =pod
                   7121: 
                   7122: =item scantron_get_closely_matching_CODEs
                   7123: 
1.424     albertel 7124:    Cycles through all CODEs and finds the set that has the greatest
                   7125:    number of same characters as the provided CODE
                   7126: 
                   7127:  Arguments:
                   7128:    $allcodes - hash ref returned by &get_codes()
                   7129:    $CODE     - CODE from the current scanline
                   7130: 
                   7131:  Returns:
                   7132:    2 element list
                   7133:     - first elements is number of how closely matching the best fit is 
                   7134:       (5 means best set has 5 matching characters)
                   7135:     - second element is an arrary ref containing the set of valid CODEs
                   7136:       that best fit the passed in CODE
                   7137: 
1.423     albertel 7138: =cut
                   7139: 
1.194     albertel 7140: sub scantron_get_closely_matching_CODEs {
                   7141:     my ($allcodes,$CODE)=@_;
                   7142:     my @CODEs;
                   7143:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7144: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7145:     }
                   7146: 
                   7147:     return ($#CODEs,$CODEs[-1]);
                   7148: }
                   7149: 
1.423     albertel 7150: =pod
                   7151: 
                   7152: =item get_codes
                   7153: 
1.424     albertel 7154:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7155:    set of remembered CODEs.
                   7156: 
                   7157:  Arguments:
                   7158:   $old_name - name of the set of remembered CODEs
                   7159:   $cdom     - domain of the course
                   7160:   $cnum     - internal course name
                   7161: 
                   7162:  Returns:
                   7163:   %allcodes - keys are the valid CODEs, values are all 1
                   7164: 
1.423     albertel 7165: =cut
                   7166: 
1.194     albertel 7167: sub get_codes {
1.280     foxr     7168:     my ($old_name, $cdom, $cnum) = @_;
                   7169:     if (!$old_name) {
                   7170: 	$old_name=$env{'form.scantron_CODElist'};
                   7171:     }
                   7172:     if (!$cdom) {
                   7173: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7174:     }
                   7175:     if (!$cnum) {
                   7176: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7177:     }
1.278     albertel 7178:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7179: 				    $cdom,$cnum);
                   7180:     my %allcodes;
                   7181:     if ($result{"type\0$old_name"} eq 'number') {
                   7182: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7183:     } else {
                   7184: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7185:     }
1.194     albertel 7186:     return %allcodes;
                   7187: }
                   7188: 
1.423     albertel 7189: =pod
                   7190: 
                   7191: =item scantron_validate_CODE
                   7192: 
1.424     albertel 7193:    Validates all scanlines in the selected file to not have any
                   7194:    invalid or underspecified CODEs and that none of the codes are
                   7195:    duplicated if this was requested.
                   7196: 
1.423     albertel 7197: =cut
                   7198: 
1.157     albertel 7199: sub scantron_validate_CODE {
                   7200:     my ($r,$currentphase) = @_;
1.257     albertel 7201:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7202:     if ($scantron_config{'CODElocation'} &&
                   7203: 	$scantron_config{'CODEstart'} &&
                   7204: 	$scantron_config{'CODElength'}) {
1.257     albertel 7205: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7206: 	    &FIXME_blow_up()
                   7207: 	}
                   7208:     } else {
                   7209: 	return (0,$currentphase+1);
                   7210:     }
                   7211:     
                   7212:     my %usedCODEs;
                   7213: 
1.194     albertel 7214:     my %allcodes=&get_codes();
1.186     albertel 7215: 
1.447     foxr     7216:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7217: 
1.186     albertel 7218:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7219:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7220: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7221: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7222: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7223: 						 $scan_data);
                   7224: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7225: 	my $error=0;
1.224     albertel 7226: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7227: 	    &scantron_get_correction($r,$i,$scan_record,
                   7228: 				     \%scantron_config,
                   7229: 				     $line,'incorrectCODE',\%allcodes);
                   7230: 	    return(1,$currentphase);
                   7231: 	}
1.221     albertel 7232: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7233: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7234: 	    &scantron_get_correction($r,$i,$scan_record,
                   7235: 				     \%scantron_config,
1.194     albertel 7236: 				     $line,'incorrectCODE',\%allcodes);
                   7237: 	    return(1,$currentphase);
1.186     albertel 7238: 	}
1.214     albertel 7239: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7240: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7241: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7242: 	    &scantron_get_correction($r,$i,$scan_record,
                   7243: 				     \%scantron_config,
1.194     albertel 7244: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7245: 	    return(1,$currentphase);
1.186     albertel 7246: 	}
1.524     raeburn  7247: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7248:     }
1.157     albertel 7249:     return (0,$currentphase+1);
                   7250: }
                   7251: 
1.423     albertel 7252: =pod
                   7253: 
                   7254: =item scantron_validate_doublebubble
                   7255: 
1.424     albertel 7256:    Validates all scanlines in the selected file to not have any
                   7257:    bubble lines with multiple bubbles marked.
                   7258: 
1.423     albertel 7259: =cut
                   7260: 
1.157     albertel 7261: sub scantron_validate_doublebubble {
                   7262:     my ($r,$currentphase) = @_;
                   7263:     #get student info
                   7264:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7265:     my %idmap=&username_to_idmap($classlist);
                   7266: 
                   7267:     #get scantron line setup
1.257     albertel 7268:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7269:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7270:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7271: 
1.157     albertel 7272:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7273: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7274: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7275: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7276: 						 $scan_data);
                   7277: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7278: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7279: 				 'doublebubble',
                   7280: 				 $$scan_record{'scantron.doubleerror'});
                   7281:     	return (1,$currentphase);
                   7282:     }
                   7283:     return (0,$currentphase+1);
                   7284: }
                   7285: 
1.423     albertel 7286: =pod
                   7287: 
                   7288: =item scantron_get_maxbubble
                   7289: 
1.424     albertel 7290:    Returns the maximum number of bubble lines that are expected to
                   7291:    occur. Does this by walking the selected sequence rendering the
                   7292:    resource and then checking &Apache::lonxml::get_problem_counter()
                   7293:    for what the current value of the problem counter is.
                   7294: 
1.447     foxr     7295:    Caches the results to $env{'form.scantron_maxbubble'},
1.503     raeburn  7296:    $env{'form.scantron.bubble_lines.n'}, 
                   7297:    $env{'form.scantron.first_bubble_line.n'} and
                   7298:    $env{"form.scantron.sub_bubblelines.n"}
1.447     foxr     7299:    which are the total number of bubble, lines, the number of bubble
1.503     raeburn  7300:    lines for response n and number of the first bubble line for response n,
                   7301:    and a comma separated list of numbers of bubble lines for sub-questions
1.509     raeburn  7302:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
1.424     albertel 7303: 
1.423     albertel 7304: =cut
                   7305: 
1.503     raeburn  7306: sub scantron_get_maxbubble {
1.257     albertel 7307:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7308: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7309: 	&restore_bubble_lines();
1.257     albertel 7310: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7311:     }
1.330     albertel 7312: 
1.447     foxr     7313:     my (undef, undef, $sequence) =
1.257     albertel 7314: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7315: 
1.447     foxr     7316:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7317:     my $map=$navmap->getResourceByUrl($sequence);
                   7318:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7319: 
                   7320:     &Apache::lonxml::clear_problem_counter();
                   7321: 
1.435     foxr     7322:     my $uname       = $env{'form.student'};
                   7323:     my $udom        = $env{'form.userdom'};
                   7324:     my $cid         = $env{'request.course.id'};
                   7325:     my $total_lines = 0;
                   7326:     %bubble_lines_per_response = ();
1.447     foxr     7327:     %first_bubble_line         = ();
1.503     raeburn  7328:     %subdivided_bubble_lines   = ();
                   7329:     %responsetype_per_response = ();
1.447     foxr     7330:   
                   7331:     my $response_number = 0;
                   7332:     my $bubble_line     = 0;
1.191     albertel 7333:     foreach my $resource (@resources) {
1.515     raeburn  7334:         my $symb = $resource->symb();
1.523     raeburn  7335: 
                   7336:         my (@parts,@allparts,@possible_parts);
                   7337: 
1.510     raeburn  7338:         # Need to retrieve part IDs and response IDs because essayresponse,
                   7339:         # reactionresponse and organicresponse items are not included in 
                   7340:         # $analysis{'parts'} from lonnet::ssi.  
1.523     raeburn  7341:         if (ref($resource->parts()) eq 'ARRAY') {
1.503     raeburn  7342:             foreach my $part (@{$resource->parts()}) {
1.515     raeburn  7343:                 if (!&Apache::loncommon::check_if_partid_hidden($part,$symb,$udom,$uname)) {
                   7344:                     my @resp_ids = $resource->responseIds($part);
                   7345:                     foreach my $id (@resp_ids) {
1.523     raeburn  7346:                         my $part_id = $part.'.'.$id;
                   7347:                         push(@possible_parts,$part_id);
1.515     raeburn  7348:                     }
1.503     raeburn  7349:                 }
                   7350:             }
                   7351:         }
1.435     foxr     7352: 
1.523     raeburn  7353:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
                   7354:                                         ('symb' => $symb,
                   7355:                                          'grade_target' => 'analyze',
                   7356:                                          'grade_courseid' => $cid,
                   7357:                                          'grade_domain' => $udom,
                   7358:                                          'grade_username' => $uname));
                   7359:         my (undef, $an) =
                   7360:             split(/_HASH_REF__/,$result, 2);
1.503     raeburn  7361: 
1.435     foxr     7362: 	my %analysis = &Apache::lonnet::str2hash($an);
                   7363: 
1.503     raeburn  7364:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.515     raeburn  7365:             foreach my $part (@{$analysis{'parts'}}) {
                   7366:                 my ($id,$respid) = split(/\./,$part);
                   7367:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7368:                     push(@parts,$part);
                   7369:                 }
                   7370:             }
1.503     raeburn  7371:         }
1.523     raeburn  7372:         # Add part_ids for any essayresponse, reactionresponse or 
                   7373:         # organicresponse items. 
                   7374:         foreach my $part_id (@possible_parts) {
                   7375:             if (grep(/^\Q$part_id\E$/,@parts)) {
                   7376:                 push(@allparts,$part_id);
                   7377:             } else {
                   7378:                 if (($analysis{$part_id.'.type'} eq 'essayresponse') ||
                   7379:                     ($analysis{$part_id.'.type'} eq 'reactionresponse') ||
                   7380:                     ($analysis{$part_id.'.type'} eq 'organicresponse')) {
1.524     raeburn  7381:                     push(@allparts,$part_id);
1.503     raeburn  7382:                 }
                   7383:             }
                   7384:         }
1.435     foxr     7385: 
1.523     raeburn  7386: 	foreach my $part_id (@allparts) {
                   7387:             my $lines;
1.447     foxr     7388: 
                   7389: 	    # TODO - make this a persistent hash not an array.
                   7390: 
1.509     raeburn  7391:             # optionresponse, matchresponse and rankresponse type items 
                   7392:             # render as separate sub-questions in exam mode.
1.503     raeburn  7393:             if (($analysis{$part_id.'.type'} eq 'optionresponse') ||
1.509     raeburn  7394:                 ($analysis{$part_id.'.type'} eq 'matchresponse') ||
                   7395:                 ($analysis{$part_id.'.type'} eq 'rankresponse')) {
1.503     raeburn  7396:                 my ($numbub,$numshown);
                   7397:                 if ($analysis{$part_id.'.type'} eq 'optionresponse') {
                   7398:                     if (ref($analysis{$part_id.'.options'}) eq 'ARRAY') {
                   7399:                         $numbub = scalar(@{$analysis{$part_id.'.options'}});
                   7400:                     }
                   7401:                 } elsif ($analysis{$part_id.'.type'} eq 'matchresponse') {
                   7402:                     if (ref($analysis{$part_id.'.items'}) eq 'ARRAY') {
                   7403:                         $numbub = scalar(@{$analysis{$part_id.'.items'}});
                   7404:                     }
1.509     raeburn  7405:                 } elsif ($analysis{$part_id.'.type'} eq 'rankresponse') {
                   7406:                     if (ref($analysis{$part_id.'.foils'}) eq 'ARRAY') {
                   7407:                         $numbub = scalar(@{$analysis{$part_id.'.foils'}});
                   7408:                     }
1.503     raeburn  7409:                 }
                   7410:                 if (ref($analysis{$part_id.'.shown'}) eq 'ARRAY') {
                   7411:                     $numshown = scalar(@{$analysis{$part_id.'.shown'}});
                   7412:                 }
                   7413:                 my $bubbles_per_line = 10;
1.523     raeburn  7414:                 my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7415:                 if (($numbub % $bubbles_per_line) != 0) {
1.503     raeburn  7416:                     $inner_bubble_lines++;
                   7417:                 }
                   7418:                 for (my $i=0; $i<$numshown; $i++) {
                   7419:                     $subdivided_bubble_lines{$response_number} .= 
                   7420:                         $inner_bubble_lines.',';
                   7421:                 }
                   7422:                 $subdivided_bubble_lines{$response_number} =~ s/,$//;
1.523     raeburn  7423:                 $lines = $numshown * $inner_bubble_lines;
                   7424:             } else {
                   7425:                 $lines = $analysis{"$part_id.bubble_lines"};
1.503     raeburn  7426:             } 
1.447     foxr     7427: 
1.503     raeburn  7428:             $first_bubble_line{$response_number} = $bubble_line;
                   7429: 	    $bubble_lines_per_response{$response_number} = $lines;
                   7430:             $responsetype_per_response{$response_number} = 
                   7431:                 $analysis{$part_id.'.type'};
1.447     foxr     7432: 	    $response_number++;
                   7433: 
                   7434: 	    $bubble_line +=  $lines;
                   7435: 	    $total_lines +=  $lines;
1.435     foxr     7436: 	}
                   7437: 
1.191     albertel 7438:     }
                   7439:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     7440: 
                   7441:     &save_bubble_lines();
1.330     albertel 7442:     $env{'form.scantron_maxbubble'} =
1.435     foxr     7443: 	$total_lines;
1.257     albertel 7444:     return $env{'form.scantron_maxbubble'};
1.191     albertel 7445: }
                   7446: 
1.423     albertel 7447: =pod
                   7448: 
                   7449: =item scantron_validate_missingbubbles
                   7450: 
1.424     albertel 7451:    Validates all scanlines in the selected file to not have any
1.447     foxr     7452:     answers that don't have bubbles that have not been verified
                   7453:     to be bubble free.
1.424     albertel 7454: 
1.423     albertel 7455: =cut
                   7456: 
1.157     albertel 7457: sub scantron_validate_missingbubbles {
                   7458:     my ($r,$currentphase) = @_;
                   7459:     #get student info
                   7460:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7461:     my %idmap=&username_to_idmap($classlist);
                   7462: 
                   7463:     #get scantron line setup
1.257     albertel 7464:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7465:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7466:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7467:     if (!$max_bubble) { $max_bubble=2**31; }
                   7468:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7469: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7470: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7471: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7472: 						 $scan_data);
                   7473: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7474: 	my @to_correct;
1.470     foxr     7475: 	
                   7476: 	# Probably here's where the error is...
                   7477: 
1.157     albertel 7478: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7479:             my $lastbubble;
                   7480:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7481:                my $question = $1;
                   7482:                my $subquestion = $2;
                   7483:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7484:                my $first = $first_bubble_line{$question-1};
                   7485:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7486:                my $subcount = 1;
                   7487:                while ($subcount<$subquestion) {
                   7488:                    $first += $subans[$subcount-1];
                   7489:                    $subcount ++;
                   7490:                }
                   7491:                my $count = $subans[$subquestion-1];
                   7492:                $lastbubble = $first + $count;
                   7493:             } else {
                   7494:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7495:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7496:             }
                   7497:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7498: 	    push(@to_correct,$missing);
                   7499: 	}
                   7500: 	if (@to_correct) {
                   7501: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7502: 				     $line,'missingbubble',\@to_correct);
                   7503: 	    return (1,$currentphase);
                   7504: 	}
                   7505: 
                   7506:     }
                   7507:     return (0,$currentphase+1);
                   7508: }
                   7509: 
1.423     albertel 7510: =pod
                   7511: 
                   7512: =item scantron_process_students
                   7513: 
                   7514:    Routine that does the actual grading of the bubble sheet information.
                   7515: 
                   7516:    The parsed scanline hash is added to %env 
                   7517: 
                   7518:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7519:    foreach resource , with the form data of
                   7520: 
                   7521: 	'submitted'     =>'scantron' 
                   7522: 	'grade_target'  =>'grade',
                   7523: 	'grade_username'=> username of student
                   7524: 	'grade_domain'  => domain of student
                   7525: 	'grade_courseid'=> of course
                   7526: 	'grade_symb'    => symb of resource to grade
                   7527: 
                   7528:     This triggers a grading pass. The problem grading code takes care
                   7529:     of converting the bubbled letter information (now in %env) into a
                   7530:     valid submission.
                   7531: 
                   7532: =cut
                   7533: 
1.82      albertel 7534: sub scantron_process_students {
1.75      albertel 7535:     my ($r) = @_;
1.513     foxr     7536: 
1.257     albertel 7537:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7538:     my ($symb)=&get_symb($r);
1.513     foxr     7539:     if (!$symb) {
                   7540: 	return '';
                   7541:     }
1.324     albertel 7542:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7543: 
1.257     albertel 7544:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7545:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7546:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7547:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7548:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7549:     my $map=$navmap->getResourceByUrl($sequence);
                   7550:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7551: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7552:     my $result= <<SCANTRONFORM;
1.81      albertel 7553: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7554:   <input type="hidden" name="command" value="scantron_configphase" />
                   7555:   $default_form_data
                   7556: SCANTRONFORM
1.82      albertel 7557:     $r->print($result);
                   7558: 
                   7559:     my @delayqueue;
1.140     albertel 7560:     my %completedstudents;
                   7561:     
1.520     www      7562:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7563:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7564:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7565:  				    'Scantron Progress',$count,
1.195     albertel 7566: 				    'inline',undef,'scantronupload');
1.140     albertel 7567:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7568: 					  'Processing first student');
                   7569:     my $start=&Time::HiRes::time();
1.158     albertel 7570:     my $i=-1;
1.200     albertel 7571:     my ($uname,$udom,$started);
1.447     foxr     7572: 
                   7573:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7574:     
                   7575: 
                   7576:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7577:     # the user and return.
                   7578: 
                   7579:     if ($ssi_error) {
                   7580: 	$r->print("</form>");
                   7581: 	&ssi_print_error($r);
                   7582: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7583:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7584: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7585:     }
1.447     foxr     7586: 
1.157     albertel 7587:     while ($i<$scanlines->{'count'}) {
                   7588:  	($uname,$udom)=('','');
                   7589:  	$i++;
1.200     albertel 7590:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7591:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7592: 	if ($started) {
                   7593: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7594: 						     'last student');
                   7595: 	}
                   7596: 	$started=1;
1.157     albertel 7597:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7598:  						 $scan_data);
                   7599:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7600:  					      \%idmap,$i)) {
                   7601:   	    &scantron_add_delay(\@delayqueue,$line,
                   7602:  				'Unable to find a student that matches',1);
                   7603:  	    next;
                   7604:   	}
                   7605:  	if (exists $completedstudents{$uname}) {
                   7606:  	    &scantron_add_delay(\@delayqueue,$line,
                   7607:  				'Student '.$uname.' has multiple sheets',2);
                   7608:  	    next;
                   7609:  	}
                   7610:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7611: 
                   7612: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7613:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7614: 
                   7615: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7616: 	    &scantron_putfile($scanlines,$scan_data);
                   7617: 	}
1.161     albertel 7618: 	
                   7619: 	my $i=0;
1.83      albertel 7620: 	foreach my $resource (@resources) {
1.85      albertel 7621: 	    $i++;
1.193     albertel 7622: 	    my %form=('submitted'     =>'scantron',
                   7623: 		      'grade_target'  =>'grade',
                   7624: 		      'grade_username'=>$uname,
                   7625: 		      'grade_domain'  =>$udom,
1.257     albertel 7626: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7627: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7628: 	    if (exists($scan_record->{'scantron.CODE'})
                   7629: 		&& 
                   7630: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7631: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7632: 	    } else {
                   7633: 		$form{'CODE'}='';
1.513     foxr     7634: 	    } 
                   7635: 	    my $result=&ssi_with_retries($resource->src(), $ssi_retries, %form);
                   7636: 	    if ($ssi_error) {
                   7637: 		$ssi_error = 0;	# So end of handler error message does not trigger.
                   7638: 		$r->print("</form>");
                   7639: 		&ssi_print_error($r);
                   7640: 		$r->print(&show_grading_menu_form($symb));
1.520     www      7641:                 &Apache::lonnet::remove_lock($lock);
1.513     foxr     7642: 		return '';	# Why return ''?  Beats me.
1.193     albertel 7643: 	    }
1.513     foxr     7644: 
1.213     albertel 7645: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7646: 	}
1.140     albertel 7647: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7648: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7649:     } continue {
1.330     albertel 7650: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7651: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7652:     }
1.140     albertel 7653:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7654:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7655: #    my $lasttime = &Time::HiRes::time()-$start;
                   7656: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7657: 
1.200     albertel 7658:     $r->print("</form>");
1.324     albertel 7659:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7660:     return '';
1.75      albertel 7661: }
1.157     albertel 7662: 
1.423     albertel 7663: =pod
                   7664: 
                   7665: =item scantron_upload_scantron_data
                   7666: 
                   7667:     Creates the screen for adding a new bubble sheet data file to a course.
                   7668: 
                   7669: =cut
                   7670: 
1.157     albertel 7671: sub scantron_upload_scantron_data {
                   7672:     my ($r)=@_;
1.257     albertel 7673:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7674:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7675: 							  'domainid',
                   7676: 							  'coursename');
1.257     albertel 7677:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7678: 						   'domainid');
1.324     albertel 7679:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7680:     $r->print('
1.157     albertel 7681: <script type="text/javascript" language="javascript">
                   7682:     function checkUpload(formname) {
                   7683: 	if (formname.upfile.value == "") {
                   7684: 	    alert("Please use the browse button to select a file from your local directory.");
                   7685: 	    return false;
                   7686: 	}
                   7687: 	formname.submit();
                   7688:     }
                   7689: </script>
                   7690: 
1.492     albertel 7691: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7692: '.$default_form_data.'
1.181     albertel 7693: <table>
1.492     albertel 7694: <tr><td>'.$select_link.'                             </td></tr>
                   7695: <tr><td>'.&mt('Course ID:').'     </td>
                   7696:     <td><input name="courseid"   type="text" />      </td></tr>
                   7697: <tr><td>'.&mt('Course Name:').'   </td>
                   7698:     <td><input name="coursename" type="text" />      </td></tr>
                   7699: <tr><td>'.&mt('Domain:').'        </td>
                   7700:     <td>'.$domsel.'                                  </td></tr>
                   7701: <tr><td>'.&mt('File to upload:').'</td>
                   7702:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7703: </table>
1.492     albertel 7704: <input name="command" value="scantronupload_save" type="hidden" />
                   7705: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7706: </form>
1.492     albertel 7707: ');
1.157     albertel 7708:     return '';
                   7709: }
                   7710: 
1.423     albertel 7711: =pod
                   7712: 
                   7713: =item scantron_upload_scantron_data_save
                   7714: 
                   7715:    Adds a provided bubble information data file to the course if user
                   7716:    has the correct privileges to do so.  
                   7717: 
                   7718: =cut
                   7719: 
1.157     albertel 7720: sub scantron_upload_scantron_data_save {
                   7721:     my($r)=@_;
1.324     albertel 7722:     my ($symb)=&get_symb($r,1);
1.182     albertel 7723:     my $doanotherupload=
                   7724: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7725: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7726: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7727: 	'</form>'."\n";
1.257     albertel 7728:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7729: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7730: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7731: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7732: 	if ($symb) {
1.324     albertel 7733: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7734: 	} else {
                   7735: 	    $r->print($doanotherupload);
                   7736: 	}
1.162     albertel 7737: 	return '';
                   7738:     }
1.257     albertel 7739:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7740:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7741:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7742:     #FIXME
                   7743:     #copied from lonnet::userfileupload()
                   7744:     #make that function able to target a specified course
                   7745:     # Replace Windows backslashes by forward slashes
                   7746:     $fname=~s/\\/\//g;
                   7747:     # Get rid of everything but the actual filename
                   7748:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7749:     # Replace spaces by underscores
                   7750:     $fname=~s/\s+/\_/g;
                   7751:     # Replace all other weird characters by nothing
                   7752:     $fname=~s/[^\w\.\-]//g;
                   7753:     # See if there is anything left
                   7754:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7755:     my $uploadedfile=$fname;
1.157     albertel 7756:     $fname='scantron_orig_'.$fname;
1.257     albertel 7757:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7758: 	$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 7759:     } else {
1.275     albertel 7760: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7761: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7762: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7763: 			  (length($env{'form.upfile'})-1),
                   7764: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7765: 	} else {
1.492     albertel 7766: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7767: 			  $result,
                   7768: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7769: 
1.183     albertel 7770: 	}
                   7771:     }
1.174     albertel 7772:     if ($symb) {
1.209     ng       7773: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7774:     } else {
1.182     albertel 7775: 	$r->print($doanotherupload);
1.174     albertel 7776:     }
1.157     albertel 7777:     return '';
                   7778: }
                   7779: 
1.423     albertel 7780: =pod
                   7781: 
                   7782: =item valid_file
                   7783: 
1.424     albertel 7784:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7785: 
                   7786: =cut
                   7787: 
1.202     albertel 7788: sub valid_file {
                   7789:     my ($requested_file)=@_;
                   7790:     foreach my $filename (sort(&scantron_filenames())) {
                   7791: 	if ($requested_file eq $filename) { return 1; }
                   7792:     }
                   7793:     return 0;
                   7794: }
                   7795: 
1.423     albertel 7796: =pod
                   7797: 
                   7798: =item scantron_download_scantron_data
                   7799: 
                   7800:    Shows a list of the three internal files (original, corrected,
                   7801:    skipped) for a specific bubble sheet data file that exists in the
                   7802:    course.
                   7803: 
                   7804: =cut
                   7805: 
1.202     albertel 7806: sub scantron_download_scantron_data {
                   7807:     my ($r)=@_;
1.324     albertel 7808:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7809:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7810:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7811:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7812:     if (! &valid_file($file)) {
1.492     albertel 7813: 	$r->print('
1.202     albertel 7814: 	<p>
1.492     albertel 7815: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7816:         </p>
1.492     albertel 7817: ');
1.324     albertel 7818: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7819: 	return;
                   7820:     }
                   7821:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7822:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7823:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7824:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7825:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7826:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7827:     $r->print('
1.202     albertel 7828:     <p>
1.492     albertel 7829: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7830: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7831:     </p>
                   7832:     <p>
1.492     albertel 7833: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7834: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7835:     </p>
                   7836:     <p>
1.492     albertel 7837: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7838: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7839:     </p>
1.492     albertel 7840: ');
1.324     albertel 7841:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7842:     return '';
                   7843: }
1.157     albertel 7844: 
1.523     raeburn  7845: sub checkscantron_results {
                   7846:     my ($r) = @_;
                   7847:     my ($symb)=&get_symb($r);
                   7848:     if (!$symb) {return '';}
                   7849:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7850:     my $cid = $env{'request.course.id'};
                   7851:     my %lettdig = (
                   7852:                     A => 1,
                   7853:                     B => 2,
                   7854:                     C => 3,
                   7855:                     D => 4,
                   7856:                     E => 5,
                   7857:                     F => 6,
                   7858:                     G => 7,
                   7859:                     H => 8,
                   7860:                     I => 9,
                   7861:                     J => 0,
                   7862:                   );
                   7863:     my $numletts = scalar(keys(%lettdig));
                   7864:     my $cnum = $env{'course.'.$cid.'.num'};
                   7865:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7866:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7867:     my %record;
                   7868:     my %scantron_config =
                   7869:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7870:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7871:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7872:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7873:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7874:     my $map=$navmap->getResourceByUrl($sequence);
                   7875:     my @resources=$navmap->retrieveResources($map,undef,1,0);
                   7876:     my (%scandata,%lastname,%bylast);
                   7877:     $r->print('
                   7878: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7879: 
                   7880:     my @delayqueue;
                   7881:     my %completedstudents;
                   7882: 
                   7883:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7884:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7885:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7886:                                     'inline',undef,'checkscantron');
                   7887:     my ($username,$domain,$uname,$started);
                   7888: 
                   7889:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
                   7890: 
                   7891:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7892:                                           'Processing first student');
                   7893:     my $start=&Time::HiRes::time();
                   7894:     my $i=-1;
                   7895: 
                   7896:     while ($i<$scanlines->{'count'}) {
                   7897:         ($username,$domain,$uname)=('','','');
                   7898:         $i++;
                   7899:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7900:         if ($line=~/^[\s\cz]*$/) { next; }
                   7901:         if ($started) {
                   7902:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7903:                                                      'last student');
                   7904:         }
                   7905:         $started=1;
                   7906:         my $scan_record=
                   7907:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7908:                                                      $scan_data);
                   7909:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7910:                                                               \%idmap,$i)) {
                   7911:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7912:                                 'Unable to find a student that matches',1);
                   7913:             next;
                   7914:         }
                   7915:         if (exists $completedstudents{$uname}) {
                   7916:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7917:                                 'Student '.$uname.' has multiple sheets',2);
                   7918:             next;
                   7919:         }
                   7920:         my $pid = $scan_record->{'scantron.ID'};
                   7921:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7922:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7923:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7924:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7925:         chomp($scandata{$pid});
                   7926:         $scandata{$pid} =~ s/\r$//;
                   7927:         ($username,$domain)=split(/:/,$uname);
                   7928:         my $counter = -1;
                   7929:         my (%expected,%startpos);
                   7930:         foreach my $resource (@resources) {
                   7931:             next if (!$resource->is_problem());
                   7932:             my $symb = $resource->symb();
                   7933:             my $partsref = $resource->parts();
                   7934:             my @parts;
                   7935:             my @part_ids = ();
                   7936:             if (ref($partsref) eq 'ARRAY') {
                   7937:                @parts = @{$partsref};
                   7938:                foreach my $part (@parts) {
                   7939:                    my @resp_ids = $resource->responseIds($part);
                   7940:                    foreach my $resp (@resp_ids) {
                   7941:                        $counter ++;
                   7942:                        my $part_id = $part.'.'.$resp;
                   7943:                        $expected{$part_id} = 0;
                   7944:                        push(@part_ids,$part_id);
                   7945:                        if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   7946:                            my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   7947:                            foreach my $item (@sub_lines) {
                   7948:                                $expected{$part_id} += $item;
                   7949:                            }
                   7950:                        } else {
                   7951:                            $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   7952:                        }
                   7953:                        $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   7954:                    }
                   7955:                 }
                   7956:             }
                   7957:             if ($symb) {
                   7958:                 my %recorded;
                   7959:                 my (%returnhash) =
                   7960:                     &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   7961:                 if ($returnhash{'version'}) {
                   7962:                     my %lasthash=();
                   7963:                     my $version;
                   7964:                     for ($version=1;$version<=$returnhash{'version'};$version++) {
                   7965:                         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   7966:                             $lasthash{$key}=$returnhash{$version.':'.$key};
                   7967:                         }
                   7968:                     }
                   7969:                     foreach my $key (keys(%lasthash)) {
                   7970:                         if ($key =~ /\.scantron$/) {
                   7971:                             my $value = &unescape($lasthash{$key});
                   7972:                             my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   7973:                             if ($value eq '') {
                   7974:                                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   7975:                                     for (my $j=0; $j<$scantron_config{'length'}; $j++) {
                   7976:                                         $recorded{$part_id} .= $;
                   7977:                                     }
                   7978:                                 }
                   7979:                             } else {
                   7980:                                 my @tocheck;
                   7981:                                 my @items = split(//,$value);
                   7982:                                 if (($scantron_config{'Qon'} eq 'letter') ||
                   7983:                                     ($scantron_config{'Qon'} eq 'number')) {
                   7984:                                     if (@items < $expected{$part_id}) {
                   7985:                                         my $fragment = substr($scandata{$pid},$startpos{$part_id},$expected{$part_id});
                   7986:                                         my @singles = split(//,$fragment);
                   7987:                                         foreach my $pos (@singles) {
                   7988:                                             if ($pos eq ' ') {
                   7989:                                                 push(@tocheck,$pos);
                   7990:                                             } else {
                   7991:                                                 my $next = shift(@items);
                   7992:                                                 push(@tocheck,$next);
                   7993:                                             }
                   7994:                                         }
                   7995:                                     } else {
                   7996:                                         @tocheck = @items;
                   7997:                                     }
                   7998:                                     foreach my $letter (@tocheck) {
                   7999:                                         if ($scantron_config{'Qon'} eq 'letter') {
                   8000:                                             if ($letter !~ /^[A-J]$/) {
                   8001:                                                 $letter = $scantron_config{'Qoff'};
                   8002:                                             }
                   8003:                                             $recorded{$part_id} .= $letter;
                   8004:                                         } elsif ($scantron_config{'Qon'} eq 'number') {
                   8005:                                             my $digit;
                   8006:                                             if ($letter !~ /^[A-J]$/) {
                   8007:                                                 $digit = $scantron_config{'Qoff'};
                   8008:                                             } else {
                   8009:                                                 $digit = $lettdig{$letter};
                   8010:                                             }
                   8011:                                             $recorded{$part_id} .= $digit;
                   8012:                                         }
                   8013:                                     }
                   8014:                                 } else {
                   8015:                                     @tocheck = @items;
                   8016:                                     for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8017:                                         my $curr_sub = shift(@tocheck);
                   8018:                                         my $digit;
                   8019:                                         if ($curr_sub =~ /^[A-J]$/) {
                   8020:                                             $digit = $lettdig{$curr_sub}-1;
                   8021:                                         }
                   8022:                                         if ($curr_sub eq 'J') {
                   8023:                                             $digit += scalar($numletts);
                   8024:                                         }
                   8025:                                         for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8026:                                             if ($j == $digit) {
                   8027:                                                 $recorded{$part_id} .= $scantron_config{'Qon'};
                   8028:                                             } else {
                   8029:                                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8030:                                             }
                   8031:                                         }
                   8032:                                     }
                   8033:                                 }
                   8034:                             }
                   8035:                         }
                   8036:                     }
                   8037:                 }
                   8038:                 foreach my $part_id (@part_ids) {
                   8039:                     if ($recorded{$part_id} eq '') {
                   8040:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8041:                             for (my $j=0; $j<$scantron_config{'Qlength'}; $j++) {
                   8042:                                 $recorded{$part_id} .= $scantron_config{'Qoff'};
                   8043:                             }
                   8044:                         }
                   8045:                     }
                   8046:                     $record{$pid} .= $recorded{$part_id};
                   8047:                 }
                   8048:             }
                   8049:         }
                   8050:     }
                   8051:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   8052:     $r->print('<br />');
                   8053:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   8054:     $passed = 0;
                   8055:     $failed = 0;
                   8056:     $numstudents = 0;
                   8057:     foreach my $last (sort(keys(%bylast))) {
                   8058:         if (ref($bylast{$last}) eq 'ARRAY') {
                   8059:             foreach my $pid (sort(@{$bylast{$last}})) {
                   8060:                 my $showscandata = $scandata{$pid};
                   8061:                 my $showrecord = $record{$pid};
                   8062:                 $showscandata =~ s/\s/&nbsp;/g;
                   8063:                 $showrecord =~ s/\s/&nbsp;/g;
                   8064:                 if ($scandata{$pid} eq $record{$pid}) {
                   8065:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8066:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8067: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8068: '</tr>'."\n".
                   8069: '<tr class="'.$css_class.'">'."\n".
                   8070: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8071:                     $passed ++;
                   8072:                 } else {
                   8073:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8074:                     $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".
                   8075: '</tr>'."\n".
                   8076: '<tr class="'.$css_class.'">'."\n".
                   8077: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8078: '</tr>'."\n";
                   8079:                     $failed ++;
                   8080:                 }
                   8081:                 $numstudents ++;
                   8082:             }
                   8083:         }
                   8084:     }
                   8085:     $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>');
                   8086:     $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>');
                   8087:     if ($passed) {
                   8088:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8089:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8090:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8091:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8092:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8093:                  $okstudents."\n".
                   8094:                  &Apache::loncommon::end_data_table().'<br />');
                   8095:     }
                   8096:     if ($failed) {
                   8097:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8098:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8099:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8100:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8101:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8102:                  $badstudents."\n".
                   8103:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8104:                  &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.');  
                   8105:     }
                   8106:     $r->print('</form><br />'.$grading_menu_button);
                   8107:     return;
                   8108: }
                   8109: 
1.423     albertel 8110: =pod
                   8111: 
                   8112: =back
                   8113: 
                   8114: =cut
                   8115: 
1.75      albertel 8116: #-------- end of section for handling grading scantron forms -------
                   8117: #
                   8118: #-------------------------------------------------------------------
                   8119: 
1.72      ng       8120: #-------------------------- Menu interface -------------------------
                   8121: #
                   8122: #--- Show a Grading Menu button - Calls the next routine ---
                   8123: sub show_grading_menu_form {
1.324     albertel 8124:     my ($symb)=@_;
1.125     ng       8125:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8126: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8127: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8128: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8129: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8130: 	'</form>'."\n";
                   8131:     return $result;
                   8132: }
                   8133: 
1.77      ng       8134: # -- Retrieve choices for grading form
                   8135: sub savedState {
                   8136:     my %savedState = ();
1.257     albertel 8137:     if ($env{'form.saveState'}) {
                   8138: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8139: 	    my ($key,$value) = split(/=/,$_,2);
                   8140: 	    $savedState{$key} = $value;
                   8141: 	}
                   8142:     }
                   8143:     return \%savedState;
                   8144: }
1.76      ng       8145: 
1.443     banghart 8146: sub grading_menu {
                   8147:     my ($request) = @_;
                   8148:     my ($symb)=&get_symb($request);
                   8149:     if (!$symb) {return '';}
                   8150:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8151:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8152: 
1.444     banghart 8153:     $request->print($table);
1.443     banghart 8154:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8155:                   'handgrade'=>$hdgrade,
                   8156:                   'probTitle'=>$probTitle,
                   8157:                   'command'=>'submit_options',
                   8158:                   'saveState'=>"",
                   8159:                   'gradingMenu'=>1,
                   8160:                   'showgrading'=>"yes");
                   8161:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8162:     my @menu = ({ url => $url,
                   8163:                      name => &mt('Manual Grading/View Submissions'),
                   8164:                      short_description => 
                   8165:     &mt('Start the process of hand grading submissions.'),
                   8166:                  });
                   8167:     $fields{'command'} = 'csvform';
                   8168:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8169:     push(@menu, { url => $url,
1.443     banghart 8170:                    name => &mt('Upload Scores'),
                   8171:                    short_description => 
                   8172:             &mt('Specify a file containing the class scores for current resource.')});
                   8173:     $fields{'command'} = 'processclicker';
                   8174:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8175:     push(@menu, { url => $url,
1.443     banghart 8176:                    name => &mt('Process Clicker'),
                   8177:                    short_description => 
                   8178:             &mt('Specify a file containing the clicker information for this resource.')});
                   8179:     $fields{'command'} = 'scantron_selectphase';
                   8180:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8181:     push(@menu, { url => $url,
1.523     raeburn  8182:                    name => &mt('Grade/Manage/Review Scantron Forms'),
1.454     banghart 8183:                    short_description => 
1.523     raeburn  8184:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
1.443     banghart 8185:     $fields{'command'} = 'verify';
                   8186:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8187:     push(@menu, { url => "",
1.443     banghart 8188:                    name => &mt('Verify Receipt'),
                   8189:                    short_description => 
                   8190:             &mt('')});
                   8191:     #
                   8192:     # Create the menu
                   8193:     my $Str;
1.444     banghart 8194:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8195:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8196:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8197:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8198: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8199: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8200: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8201: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8202: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8203: 
1.443     banghart 8204:     foreach my $menudata (@menu) {
1.445     banghart 8205:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   8206:             $Str .='    <h3><a '.
                   8207:                 $menudata->{'jscript'}.
                   8208:                 ' href="'.
                   8209:                 $menudata->{'url'}.'" >'.
                   8210:                 $menudata->{'name'}."</a></h3>\n";
                   8211:         } else {
1.511     www      8212:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 8213:                 $menudata->{'jscript'}.
1.458     banghart 8214:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      8215:                 ' /> '.
                   8216: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   8217:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 8218:         }
1.443     banghart 8219:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8220:             "\n";
                   8221:     }
1.444     banghart 8222:     $Str .="</form>\n";
1.443     banghart 8223:     $request->print(<<GRADINGMENUJS);
                   8224: <script type="text/javascript" language="javascript">
                   8225:     function checkChoice(formname,val,cmdx) {
                   8226: 	if (val <= 2) {
                   8227: 	    var cmd = radioSelection(formname.radioChoice);
                   8228: 	    var cmdsave = cmd;
                   8229: 	} else {
                   8230: 	    cmd = cmdx;
                   8231: 	    cmdsave = 'submission';
                   8232: 	}
                   8233: 	formname.command.value = cmd;
                   8234: 	if (val < 5) formname.submit();
                   8235: 	if (val == 5) {
1.458     banghart 8236: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8237: 	        return false;
                   8238: 	    } else {
                   8239: 	        formname.submit();
                   8240: 	    }
1.445     banghart 8241: 	}
                   8242:     }
1.443     banghart 8243: 
                   8244:     function checkReceiptNo(formname,nospace) {
                   8245: 	var receiptNo = formname.receipt.value;
                   8246: 	var checkOpt = false;
                   8247: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8248: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8249: 	if (checkOpt) {
                   8250: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8251: 	    formname.receipt.value = "";
                   8252: 	    formname.receipt.focus();
                   8253: 	    return false;
                   8254: 	}
                   8255: 	return true;
                   8256:     }
                   8257: </script>
                   8258: GRADINGMENUJS
                   8259:     &commonJSfunctions($request);
                   8260:     return $Str;    
                   8261: }
                   8262: 
                   8263: 
                   8264: #--- Displays the submissions first page -------
                   8265: sub submit_options {
1.72      ng       8266:     my ($request) = @_;
1.324     albertel 8267:     my ($symb)=&get_symb($request);
1.72      ng       8268:     if (!$symb) {return '';}
1.76      ng       8269:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8270: 
                   8271:     $request->print(<<GRADINGMENUJS);
                   8272: <script type="text/javascript" language="javascript">
1.116     ng       8273:     function checkChoice(formname,val,cmdx) {
                   8274: 	if (val <= 2) {
                   8275: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8276: 	    var cmdsave = cmd;
1.116     ng       8277: 	} else {
                   8278: 	    cmd = cmdx;
1.118     ng       8279: 	    cmdsave = 'submission';
1.116     ng       8280: 	}
                   8281: 	formname.command.value = cmd;
1.118     ng       8282: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8283: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8284: 	if (val < 5) formname.submit();
                   8285: 	if (val == 5) {
1.72      ng       8286: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8287: 	    formname.submit();
                   8288: 	}
1.238     albertel 8289: 	if (val < 7) formname.submit();
1.72      ng       8290:     }
                   8291: 
                   8292:     function checkReceiptNo(formname,nospace) {
                   8293: 	var receiptNo = formname.receipt.value;
                   8294: 	var checkOpt = false;
                   8295: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8296: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8297: 	if (checkOpt) {
                   8298: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8299: 	    formname.receipt.value = "";
                   8300: 	    formname.receipt.focus();
                   8301: 	    return false;
                   8302: 	}
                   8303: 	return true;
                   8304:     }
                   8305: </script>
                   8306: GRADINGMENUJS
1.118     ng       8307:     &commonJSfunctions($request);
1.324     albertel 8308:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8309:     my $result;
1.76      ng       8310:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8311:     my $savedState = &savedState();
1.118     ng       8312:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8313:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8314:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8315:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8316: 
                   8317:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8318: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8319: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8320: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8321: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8322: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8323: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8324: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8325: 
1.472     albertel 8326:     $result.='
                   8327:     <div class="LC_grade_select_mode">
1.473     albertel 8328:       <div class="LC_grade_select_mode_current">
                   8329:         <h2>
                   8330:           '.&mt('Grade Current Resource').'
                   8331:         </h2>
                   8332:         <div class="LC_grade_select_mode_body">
                   8333:           <div class="LC_grades_resource_info">
                   8334:            '.$table.'
                   8335:           </div>
                   8336:           <div class="LC_grade_select_mode_selector">
                   8337:              <div class="LC_grade_select_mode_selector_header">
                   8338:                 '.&mt('Sections').'
                   8339:              </div>
                   8340:              <div class="LC_grade_select_mode_selector_body">
                   8341: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       8342:     if (ref($sections)) {
1.524     raeburn  8343: 	foreach my $section (sort(@$sections)) {
1.472     albertel 8344: 	    $result.='<option value="'.$section.'" '.
                   8345: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 8346: 	}
1.116     ng       8347:     }
1.401     albertel 8348:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8349:     $result.='
1.473     albertel 8350:              </div>
                   8351:           </div>
                   8352:           <div class="LC_grade_select_mode_selector">
                   8353:              <div class="LC_grade_select_mode_selector_header">
                   8354:                 '.&mt('Groups').'
                   8355:              </div>
                   8356:              <div class="LC_grade_select_mode_selector_body">
                   8357:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   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('Access Status').'
                   8363:              </div>
                   8364:              <div class="LC_grade_select_mode_selector_body">
                   8365:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8366:              </div>
1.472     albertel 8367:           </div>
1.473     albertel 8368:           <div class="LC_grade_select_mode_selector">
                   8369:              <div class="LC_grade_select_mode_selector_header">
                   8370:                 '.&mt('Submission Status').'
                   8371:              </div>
                   8372:              <div class="LC_grade_select_mode_selector_body">
                   8373:                <select name="submitonly" size="5">
                   8374: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8375: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8376: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8377: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8378:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8379:                </select>
                   8380:              </div>
1.472     albertel 8381:           </div>
1.473     albertel 8382:           <div class="LC_grade_select_mode_type_body">
                   8383:             <div class="LC_grade_select_mode_type">
                   8384:               <label>
                   8385:                 <input type="radio" name="radioChoice" value="submission" '.
                   8386:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8387:              &mt('Select individual students to grade and view submissions.').'
                   8388: 	      </label> 
                   8389:             </div>
                   8390:             <div class="LC_grade_select_mode_type">
                   8391: 	      <label>
                   8392:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8393:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8394:                     &mt('Grade all selected students in a grading table.').'
                   8395:               </label>
                   8396:             </div>
                   8397:             <div class="LC_grade_select_mode_type">
                   8398: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8399:             </div>
1.472     albertel 8400:           </div>
1.473     albertel 8401:         </div>
                   8402:       </div>
                   8403:       <div class="LC_grade_select_mode_page">
                   8404:         <h2>
                   8405:          '.&mt('Grade Complete Folder for One Student').'
                   8406:         </h2>
                   8407:         <div class="LC_grades_select_mode_body">
                   8408:           <div class="LC_grade_select_mode_type_body">
                   8409:             <div class="LC_grade_select_mode_type">
                   8410:               <label>
                   8411:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8412: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8413:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8414:               </label>
                   8415:             </div>
                   8416:             <div class="LC_grade_select_mode_type">
                   8417: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8418:             </div>
1.472     albertel 8419:           </div>
                   8420:         </div>
                   8421:       </div>
                   8422:     </div>
                   8423:   </form>';
1.499     albertel 8424:     $result .= &show_grading_menu_form($symb);
1.44      ng       8425:     return $result;
1.2       albertel 8426: }
                   8427: 
1.285     albertel 8428: sub reset_perm {
                   8429:     undef(%perm);
                   8430: }
                   8431: 
                   8432: sub init_perm {
                   8433:     &reset_perm();
1.300     albertel 8434:     foreach my $test_perm ('vgr','mgr','opa') {
                   8435: 
                   8436: 	my $scope = $env{'request.course.id'};
                   8437: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8438: 
                   8439: 	    $scope .= '/'.$env{'request.course.sec'};
                   8440: 	    if ( $perm{$test_perm}=
                   8441: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8442: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8443: 	    } else {
                   8444: 		delete($perm{$test_perm});
                   8445: 	    }
1.285     albertel 8446: 	}
                   8447:     }
                   8448: }
                   8449: 
1.400     www      8450: sub gather_clicker_ids {
1.408     albertel 8451:     my %clicker_ids;
1.400     www      8452: 
                   8453:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8454: 
                   8455:     # Set up a couple variables.
1.407     albertel 8456:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8457:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8458:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8459: 
1.407     albertel 8460:     foreach my $student (keys(%$classlist)) {
1.438     www      8461:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8462:         my $username = $classlist->{$student}->[$username_idx];
                   8463:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8464:         my $clickers =
1.408     albertel 8465: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8466:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8467:             $id=~s/^[\#0]+//;
1.421     www      8468:             $id=~s/[\-\:]//g;
1.407     albertel 8469:             if (exists($clicker_ids{$id})) {
1.408     albertel 8470: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8471:             } else {
1.408     albertel 8472: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8473:             }
                   8474:         }
                   8475:     }
1.407     albertel 8476:     return %clicker_ids;
1.400     www      8477: }
                   8478: 
1.402     www      8479: sub gather_adv_clicker_ids {
1.408     albertel 8480:     my %clicker_ids;
1.402     www      8481:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8482:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8483:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8484:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8485:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8486:             my ($puname,$pudom)=split(/\:/,$person);
                   8487:             my $clickers =
1.408     albertel 8488: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8489:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8490: 		$id=~s/^[\#0]+//;
1.421     www      8491:                 $id=~s/[\-\:]//g;
1.408     albertel 8492: 		if (exists($clicker_ids{$id})) {
                   8493: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8494: 		} else {
                   8495: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8496: 		}
1.405     www      8497:             }
1.402     www      8498:         }
                   8499:     }
1.407     albertel 8500:     return %clicker_ids;
1.402     www      8501: }
                   8502: 
1.413     www      8503: sub clicker_grading_parameters {
                   8504:     return ('gradingmechanism' => 'scalar',
                   8505:             'upfiletype' => 'scalar',
                   8506:             'specificid' => 'scalar',
                   8507:             'pcorrect' => 'scalar',
                   8508:             'pincorrect' => 'scalar');
                   8509: }
                   8510: 
1.400     www      8511: sub process_clicker {
                   8512:     my ($r)=@_;
                   8513:     my ($symb)=&get_symb($r);
                   8514:     if (!$symb) {return '';}
                   8515:     my $result=&checkforfile_js();
                   8516:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8517:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8518:     $result.=$table;
                   8519:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8520:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   8521:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   8522:         '.</b></td></tr>'."\n";
                   8523:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8524: # Attempt to restore parameters from last session, set defaults if not present
                   8525:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8526:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8527:                                                  \%Saveable_Parameters);
                   8528:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8529:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8530:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8531:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8532: 
                   8533:     my %checked;
1.521     www      8534:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8535:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8536:           $checked{$gradingmechanism}="checked='checked'";
                   8537:        }
                   8538:     }
                   8539: 
1.400     www      8540:     my $upload=&mt("Upload File");
                   8541:     my $type=&mt("Type");
1.402     www      8542:     my $attendance=&mt("Award points just for participation");
                   8543:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8544:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8545:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8546:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8547:     my $pcorrect=&mt("Percentage points for correct solution");
                   8548:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8549:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8550: 						   ('iclicker' => 'i>clicker',
                   8551:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8552:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8553:     $result.=<<ENDUPFORM;
1.402     www      8554: <script type="text/javascript">
                   8555: function sanitycheck() {
                   8556: // Accept only integer percentages
                   8557:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8558:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8559: // Find out grading choice
                   8560:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8561:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8562:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8563:       }
                   8564:    }
                   8565: // By default, new choice equals user selection
                   8566:    newgradingchoice=gradingchoice;
                   8567: // Not good to give more points for false answers than correct ones
                   8568:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8569:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8570:    }
                   8571: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8572:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8573:       document.forms.gradesupload.pcorrect.value=100;
                   8574:       document.forms.gradesupload.pincorrect.value=100;
                   8575:    }
                   8576: // If the values are different, cannot be attendance only
                   8577:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8578:        (gradingchoice=='attendance')) {
                   8579:        newgradingchoice='personnel';
                   8580:    }
                   8581: // Change grading choice to new one
                   8582:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8583:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8584:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8585:       } else {
                   8586:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8587:       }
                   8588:    }
                   8589: // Remember the old state
                   8590:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8591: }
                   8592: </script>
1.400     www      8593: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8594: <input type="hidden" name="symb" value="$symb" />
                   8595: <input type="hidden" name="command" value="processclickerfile" />
                   8596: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8597: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8598: <input type="file" name="upfile" size="50" />
                   8599: <br /><label>$type: $selectform</label>
1.451     albertel 8600: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8601: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8602: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8603: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8604: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8605: <br />&nbsp;&nbsp;&nbsp;
                   8606: <input type="text" name="givenanswer" size="50" />
1.413     www      8607: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8608: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8609: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8610: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8611: </form>
                   8612: ENDUPFORM
                   8613:     $result.='</td></tr></table>'."\n".
                   8614:              '</td></tr></table><br /><br />'."\n";
                   8615:     $result.=&show_grading_menu_form($symb);
                   8616:     return $result;
                   8617: }
                   8618: 
                   8619: sub process_clicker_file {
                   8620:     my ($r)=@_;
                   8621:     my ($symb)=&get_symb($r);
                   8622:     if (!$symb) {return '';}
1.413     www      8623: 
                   8624:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8625:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8626:                                               \%Saveable_Parameters);
                   8627: 
1.400     www      8628:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8629:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8630: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8631: 	return $result.&show_grading_menu_form($symb);
1.404     www      8632:     }
1.522     www      8633:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8634:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8635:         return $result.&show_grading_menu_form($symb);
                   8636:     }
1.522     www      8637:     my $foundgiven=0;
1.521     www      8638:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8639:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8640:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8641:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8642:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8643:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8644:         $foundgiven=$#answers+1;
1.521     www      8645:     }
1.407     albertel 8646:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8647:     my %correct_ids;
1.404     www      8648:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8649: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8650:     }
                   8651:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8652: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8653: 	   $correct_id=~tr/a-z/A-Z/;
                   8654: 	   $correct_id=~s/\s//gs;
                   8655: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8656:            $correct_id=~s/[\-\:]//g;
1.414     www      8657:            if ($correct_id) {
                   8658: 	      $correct_ids{$correct_id}='specified';
                   8659:            }
                   8660:         }
1.400     www      8661:     }
1.404     www      8662:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8663: 	$result.=&mt('Score based on attendance only');
1.521     www      8664:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8665:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8666:     } else {
1.408     albertel 8667: 	my $number=0;
1.411     www      8668: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8669: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8670: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8671: 	    if ($correct_ids{$id} eq 'specified') {
                   8672: 		$result.=&mt('specified');
                   8673: 	    } else {
                   8674: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8675: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8676: 	    }
                   8677: 	    $number++;
                   8678: 	}
1.411     www      8679:         $result.="</p>\n";
1.408     albertel 8680: 	if ($number==0) {
                   8681: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8682: 	    return $result.&show_grading_menu_form($symb);
                   8683: 	}
1.404     www      8684:     }
1.405     www      8685:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8686:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8687: 		     '<span class="LC_error">',
                   8688: 		     '</span>',
                   8689: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8690:         return $result.&show_grading_menu_form($symb);
                   8691:     }
1.410     www      8692: 
                   8693: # Were able to get all the info needed, now analyze the file
                   8694: 
1.411     www      8695:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8696:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8697:     my $heading=&mt('Scanning clicker file');
                   8698:     $result.=(<<ENDHEADER);
                   8699: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8700: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8701: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8702: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8703: <input type="hidden" name="symb" value="$symb" />
                   8704: <input type="hidden" name="command" value="assignclickergrades" />
                   8705: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8706: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8707: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8708: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8709: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8710: ENDHEADER
1.522     www      8711:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8712:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8713:     } 
1.408     albertel 8714:     my %responses;
                   8715:     my @questiontitles;
1.405     www      8716:     my $errormsg='';
                   8717:     my $number=0;
                   8718:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8719: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8720:     }
1.419     www      8721:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8722:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8723:     }
1.411     www      8724:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8725:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8726:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8727:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8728:              '<br />';
1.522     www      8729:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8730:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8731:        return $result.&show_grading_menu_form($symb);
                   8732:     } 
1.414     www      8733: # Remember Question Titles
                   8734: # FIXME: Possibly need delimiter other than ":"
                   8735:     for (my $i=0;$i<$number;$i++) {
                   8736:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8737:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8738:     }
1.411     www      8739:     my $correct_count=0;
                   8740:     my $student_count=0;
                   8741:     my $unknown_count=0;
1.414     www      8742: # Match answers with usernames
                   8743: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8744:     foreach my $id (keys(%responses)) {
1.410     www      8745:        if ($correct_ids{$id}) {
1.414     www      8746:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8747:           $correct_count++;
1.410     www      8748:        } elsif ($clicker_ids{$id}) {
1.437     www      8749:           if ($clicker_ids{$id}=~/\,/) {
                   8750: # More than one user with the same clicker!
                   8751:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8752:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8753:                            "<select name='multi".$id."'>";
                   8754:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8755:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8756:              }
                   8757:              $result.='</select>';
                   8758:              $unknown_count++;
                   8759:           } else {
                   8760: # Good: found one and only one user with the right clicker
                   8761:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8762:              $student_count++;
                   8763:           }
1.410     www      8764:        } else {
1.411     www      8765:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8766:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8767:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8768:                    "\n".&mt("Domain").": ".
                   8769:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8770:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8771:           $unknown_count++;
1.410     www      8772:        }
1.405     www      8773:     }
1.412     www      8774:     $result.='<hr />'.
                   8775:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8776:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8777:        if ($correct_count==0) {
                   8778:           $errormsg.="Found no correct answers answers for grading!";
                   8779:        } elsif ($correct_count>1) {
1.414     www      8780:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8781:        }
                   8782:     }
1.428     www      8783:     if ($number<1) {
                   8784:        $errormsg.="Found no questions.";
                   8785:     }
1.412     www      8786:     if ($errormsg) {
                   8787:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8788:     } else {
                   8789:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8790:     }
                   8791:     $result.='</form></td></tr></table>'."\n".
1.410     www      8792:              '</td></tr></table><br /><br />'."\n";
1.404     www      8793:     return $result.&show_grading_menu_form($symb);
1.400     www      8794: }
                   8795: 
1.405     www      8796: sub iclicker_eval {
1.406     www      8797:     my ($questiontitles,$responses)=@_;
1.405     www      8798:     my $number=0;
                   8799:     my $errormsg='';
                   8800:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8801:         my %components=&Apache::loncommon::record_sep($line);
                   8802:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8803: 	if ($entries[0] eq 'Question') {
                   8804: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8805: 		$$questiontitles[$number]=$entries[$i];
                   8806: 		$number++;
                   8807: 	    }
                   8808: 	}
                   8809: 	if ($entries[0]=~/^\#/) {
                   8810: 	    my $id=$entries[0];
                   8811: 	    my @idresponses;
                   8812: 	    $id=~s/^[\#0]+//;
                   8813: 	    for (my $i=0;$i<$number;$i++) {
                   8814: 		my $idx=3+$i*6;
                   8815: 		push(@idresponses,$entries[$idx]);
                   8816: 	    }
                   8817: 	    $$responses{$id}=join(',',@idresponses);
                   8818: 	}
1.405     www      8819:     }
                   8820:     return ($errormsg,$number);
                   8821: }
                   8822: 
1.419     www      8823: sub interwrite_eval {
                   8824:     my ($questiontitles,$responses)=@_;
                   8825:     my $number=0;
                   8826:     my $errormsg='';
1.420     www      8827:     my $skipline=1;
                   8828:     my $questionnumber=0;
                   8829:     my %idresponses=();
1.419     www      8830:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8831:         my %components=&Apache::loncommon::record_sep($line);
                   8832:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8833:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8834:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8835:         next if $skipline;
                   8836:         if ($entries[0]!=$questionnumber) {
                   8837:            $questionnumber=$entries[0];
                   8838:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8839:            $number++;
1.419     www      8840:         }
1.420     www      8841:         my $id=$entries[4];
                   8842:         $id=~s/^[\#0]+//;
1.421     www      8843:         $id=~s/^v\d*\://i;
                   8844:         $id=~s/[\-\:]//g;
1.420     www      8845:         $idresponses{$id}[$number]=$entries[6];
                   8846:     }
1.524     raeburn  8847:     foreach my $id (keys(%idresponses)) {
1.420     www      8848:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8849:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8850:     }
                   8851:     return ($errormsg,$number);
                   8852: }
                   8853: 
1.414     www      8854: sub assign_clicker_grades {
                   8855:     my ($r)=@_;
                   8856:     my ($symb)=&get_symb($r);
                   8857:     if (!$symb) {return '';}
1.416     www      8858: # See which part we are saving to
                   8859:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8860: # FIXME: This should probably look for the first handgradeable part
                   8861:     my $part=$$partlist[0];
                   8862: # Start screen output
1.414     www      8863:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8864: 
1.414     www      8865:     my $heading=&mt('Assigning grades based on clicker file');
                   8866:     $result.=(<<ENDHEADER);
                   8867: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8868: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8869: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8870: ENDHEADER
                   8871: # Get correct result
                   8872: # FIXME: Possibly need delimiter other than ":"
                   8873:     my @correct=();
1.415     www      8874:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8875:     my $number=$env{'form.number'};
                   8876:     if ($gradingmechanism ne 'attendance') {
1.414     www      8877:        foreach my $key (keys(%env)) {
                   8878:           if ($key=~/^form\.correct\:/) {
                   8879:              my @input=split(/\,/,$env{$key});
                   8880:              for (my $i=0;$i<=$#input;$i++) {
                   8881:                  if (($correct[$i]) && ($input[$i]) &&
                   8882:                      ($correct[$i] ne $input[$i])) {
                   8883:                     $result.='<br /><span class="LC_warning">'.
                   8884:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8885:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8886:                  } elsif ($input[$i]) {
                   8887:                     $correct[$i]=$input[$i];
                   8888:                  }
                   8889:              }
                   8890:           }
                   8891:        }
1.415     www      8892:        for (my $i=0;$i<$number;$i++) {
1.414     www      8893:           if (!$correct[$i]) {
                   8894:              $result.='<br /><span class="LC_error">'.
                   8895:                       &mt('No correct result given for question "[_1]"!',
                   8896:                           $env{'form.question:'.$i}).'</span>';
                   8897:           }
                   8898:        }
                   8899:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8900:     }
                   8901: # Start grading
1.415     www      8902:     my $pcorrect=$env{'form.pcorrect'};
                   8903:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8904:     my $storecount=0;
1.415     www      8905:     foreach my $key (keys(%env)) {
1.420     www      8906:        my $user='';
1.415     www      8907:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8908:           $user=$1;
                   8909:        }
                   8910:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8911:           my $id=$1;
                   8912:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8913:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8914:           } elsif ($env{'form.multi'.$id}) {
                   8915:              $user=$env{'form.multi'.$id};
1.420     www      8916:           }
                   8917:        }
                   8918:        if ($user) { 
1.415     www      8919:           my @answer=split(/\,/,$env{$key});
                   8920:           my $sum=0;
1.522     www      8921:           my $realnumber=$number;
1.415     www      8922:           for (my $i=0;$i<$number;$i++) {
                   8923:              if ($answer[$i]) {
                   8924:                 if ($gradingmechanism eq 'attendance') {
                   8925:                    $sum+=$pcorrect;
1.522     www      8926:                 } elsif ($answer[$i] eq '*') {
                   8927:                    $sum+=$pcorrect;
                   8928:                 } elsif ($answer[$i] eq '-') {
                   8929:                    $realnumber--;
1.415     www      8930:                 } else {
                   8931:                    if ($answer[$i] eq $correct[$i]) {
                   8932:                       $sum+=$pcorrect;
                   8933:                    } else {
                   8934:                       $sum+=$pincorrect;
                   8935:                    }
                   8936:                 }
                   8937:              }
                   8938:           }
1.522     www      8939:           my $ave=$sum/(100*$realnumber);
1.416     www      8940: # Store
                   8941:           my ($username,$domain)=split(/\:/,$user);
                   8942:           my %grades=();
                   8943:           $grades{"resource.$part.solved"}='correct_by_override';
                   8944:           $grades{"resource.$part.awarded"}=$ave;
                   8945:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8946:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8947:                                                  $env{'request.course.id'},
                   8948:                                                  $domain,$username);
                   8949:           if ($returncode ne 'ok') {
                   8950:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8951:           } else {
                   8952:              $storecount++;
                   8953:           }
1.415     www      8954:        }
                   8955:     }
                   8956: # We are done
1.416     www      8957:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8958:              '</td></tr></table>'."\n".
1.414     www      8959:              '</td></tr></table><br /><br />'."\n";
                   8960:     return $result.&show_grading_menu_form($symb);
                   8961: }
                   8962: 
1.1       albertel 8963: sub handler {
1.41      ng       8964:     my $request=$_[0];
1.434     albertel 8965:     &reset_caches();
1.257     albertel 8966:     if ($env{'browser.mathml'}) {
1.141     www      8967: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8968:     } else {
1.141     www      8969: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8970:     }
                   8971:     $request->send_http_header;
1.44      ng       8972:     return '' if $request->header_only;
1.41      ng       8973:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8974:     my $symb=&get_symb($request,1);
1.160     albertel 8975:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8976:     my $command=$commands[0];
1.447     foxr     8977: 
1.160     albertel 8978:     if ($#commands > 0) {
                   8979: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8980:     }
1.447     foxr     8981: 
1.513     foxr     8982:     $ssi_error = 0;
1.353     albertel 8983:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8984:     if ($symb eq '' && $command eq '') {
1.257     albertel 8985: 	if ($env{'user.adv'}) {
                   8986: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8987: 		($env{'form.codethree'})) {
                   8988: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8989: 		    $env{'form.codethree'};
1.41      ng       8990: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8991: 		    &Apache::lonnet::checkin($token);
                   8992: 		if ($tsymb) {
1.137     albertel 8993: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8994: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     8995: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 8996: 					  ('grade_username' => $tuname,
                   8997: 					   'grade_domain' => $tudom,
                   8998: 					   'grade_courseid' => $tcrsid,
                   8999: 					   'grade_symb' => $tsymb)));
1.41      ng       9000: 		    } else {
1.45      ng       9001: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9002: 		    }
1.41      ng       9003: 		} else {
1.45      ng       9004: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9005: 		}
1.14      www      9006: 	    } else {
1.41      ng       9007: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9008: 	    }
                   9009: 	}
                   9010:     } else {
1.285     albertel 9011: 	&init_perm();
1.104     albertel 9012: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9013: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9014: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9015: 	    &pickStudentPage($request);
1.103     albertel 9016: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9017: 	    &displayPage($request);
1.104     albertel 9018: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9019: 	    &updateGradeByPage($request);
1.104     albertel 9020: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9021: 	    &processGroup($request);
1.104     albertel 9022: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9023: 	    $request->print(&grading_menu($request));
                   9024: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9025: 	    $request->print(&submit_options($request));
1.104     albertel 9026: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9027: 	    $request->print(&viewgrades($request));
1.104     albertel 9028: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9029: 	    $request->print(&processHandGrade($request));
1.106     albertel 9030: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9031: 	    $request->print(&editgrades($request));
1.106     albertel 9032: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9033: 	    $request->print(&verifyreceipt($request));
1.400     www      9034:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9035:             $request->print(&process_clicker($request));
                   9036:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9037:             $request->print(&process_clicker_file($request));
1.414     www      9038:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9039:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9040: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9041: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9042: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9043: 	    $request->print(&csvupload($request));
1.106     albertel 9044: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9045: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9046: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9047: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9048: 		$request->print(&csvuploadoptions($request));
1.41      ng       9049: 	    } else {
1.257     albertel 9050: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9051: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9052: 		} else {
1.257     albertel 9053: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9054: 		}
                   9055: 		$request->print(&csvuploadmap($request));
                   9056: 	    }
1.246     albertel 9057: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9058: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9059: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9060: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9061:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9062:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9063: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9064: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9065: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9066: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9067:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9068:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9069: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9070:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9071:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9072:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9073: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9074:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9075:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9076: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9077:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9078:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9079:             $request->print(&checkscantron_results($request));     
1.106     albertel 9080: 	} elsif ($command) {
1.157     albertel 9081: 	    $request->print("Access Denied ($command)");
1.26      albertel 9082: 	}
1.2       albertel 9083:     }
1.513     foxr     9084:     if ($ssi_error) {
                   9085: 	&ssi_print_error($request);
                   9086:     }
1.353     albertel 9087:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9088:     &reset_caches();
1.44      ng       9089:     return '';
                   9090: }
                   9091: 
1.1       albertel 9092: 1;
                   9093: 
1.13      albertel 9094: __END__;

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