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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.528.2.8! raeburn     4: # $Id: grades.pm,v 1.528.2.7 2008/12/31 21:10:29 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.528.2.1  raeburn  1684: 	$radio.= '<td><span class="LC_nobreak"><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.528.2.7  raeburn  2138: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain viruses').'</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 = 
1.528.2.6  raeburn  2361: 		    &Apache::lonlocal::locallocaltime($$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.528.2.2  raeburn  2799:                         $request->print('<br /><span class="LC_error">'.
                   2800:                             &mt('An error occurred ([_1]) while trying to upload [_2].',
                   2801:                                 $result,$newflg.'_'.$part_resp.'_returndoc'.$file_counter).
                   2802:                                         '</span>');
1.356     banghart 2803:                     } else {
1.360     banghart 2804:                         # mark the file as read only
                   2805:                         my @files = ($save_file_name);
1.372     albertel 2806:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2807:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2808: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2809: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2810: 			}
                   2811:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2812: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2813: 
1.337     banghart 2814:                     }
                   2815:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2816:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2817:                     $file_counter++;
                   2818:                 }
1.367     albertel 2819: 		my $subject = "File Handed Back by Instructor ";
                   2820: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2821: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2822: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2823: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2824: 		my ($feedurl,$showsymb) = 
                   2825: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2826:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2827: 		my $msgstatus = 
                   2828:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2829: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2830:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2831:             }
                   2832:         }
1.338     banghart 2833:     return;
1.337     banghart 2834: }
                   2835: 
1.418     albertel 2836: sub get_feedurl_and_symb {
                   2837:     my ($symb,$uname,$udom) = @_;
                   2838:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2839:     $url = &Apache::lonnet::clutter($url);
                   2840:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2841: 					$symb,$udom,$uname);
                   2842:     if ($encrypturl =~ /^yes$/i) {
                   2843: 	&Apache::lonenc::encrypted(\$url,1);
                   2844: 	&Apache::lonenc::encrypted(\$symb,1);
                   2845:     }
                   2846:     return ($url,$symb);
                   2847: }
                   2848: 
1.313     banghart 2849: sub get_submitted_files {
                   2850:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2851:     my @files;
                   2852:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2853:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2854:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2855:     	    push(@files,$file_url.$file);
                   2856:         }
                   2857:     }
                   2858:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2859:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2860:     }
                   2861:     return (\@files);
                   2862: }
1.322     albertel 2863: 
1.269     raeburn  2864: # ----------- Provides number of tries since last reset.
                   2865: sub get_num_tries {
                   2866:     my ($record,$last_reset,$part) = @_;
                   2867:     my $timestamp = '';
                   2868:     my $num_tries = 0;
                   2869:     if ($$record{'version'}) {
                   2870:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2871:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2872:                 $timestamp = $$record{$version.':timestamp'};
                   2873:                 if ($timestamp > $last_reset) {
                   2874:                     $num_tries ++;
                   2875:                 } else {
                   2876:                     last;
                   2877:                 }
                   2878:             }
                   2879:         }
                   2880:     }
                   2881:     return $num_tries;
                   2882: }
                   2883: 
                   2884: # ----------- Determine decrements required in aggregate totals 
                   2885: sub decrement_aggs {
                   2886:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2887:     my %decrement = (
                   2888:                         attempts => 0,
                   2889:                         users => 0,
                   2890:                         correct => 0
                   2891:                     );
                   2892:     $decrement{'attempts'} = $aggtries;
                   2893:     if ($solvedstatus =~ /^correct/) {
                   2894:         $decrement{'correct'} = 1;
                   2895:     }
                   2896:     if ($aggtries == $totaltries) {
                   2897:         $decrement{'users'} = 1;
                   2898:     }
1.524     raeburn  2899:     foreach my $type (keys(%decrement)) {
1.269     raeburn  2900:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2901:     }
                   2902:     return;
                   2903: }
                   2904: 
                   2905: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2906: sub get_last_resets {
1.270     albertel 2907:     my ($symb,$courseid,$partids) =@_;
                   2908:     my %last_resets;
1.269     raeburn  2909:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2910:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2911:     my @keys;
                   2912:     foreach my $part (@{$partids}) {
                   2913: 	push(@keys,"$symb\0$part\0resettime");
                   2914:     }
                   2915:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2916: 				     $cdom,$cname);
                   2917:     foreach my $part (@{$partids}) {
                   2918: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2919:     }
1.270     albertel 2920:     return %last_resets;
1.269     raeburn  2921: }
                   2922: 
1.251     banghart 2923: # ----------- Handles creating versions for portfolio files as answers
                   2924: sub version_portfiles {
1.343     banghart 2925:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2926:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2927:     my @returned_keys;
1.255     banghart 2928:     my $parts = join('|', @$parts_graded);
1.517     raeburn  2929:     my $portfolio_root = '/userfiles/portfolio';
1.277     albertel 2930:     foreach my $key (keys(%$record)) {
1.259     banghart 2931:         my $new_portfiles;
1.263     banghart 2932:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2933:             my @versioned_portfiles;
1.367     albertel 2934:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2935:             foreach my $file (@portfiles) {
1.306     banghart 2936:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2937:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2938: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2939: 		    &file_name_version_ext($answer_file);
1.517     raeburn  2940:                 my $getpropath = 1;    
                   2941:                 my @dir_list = &Apache::lonnet::dirlist($portfolio_root.$directory,$domain,$stu_name,$getpropath);
1.342     banghart 2942:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2943:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2944:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2945:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2946:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2947:                         [$directory.$new_answer],
1.306     banghart 2948:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2949:                 }
1.252     banghart 2950:             }
1.343     banghart 2951:             $$record{$key} = join(',',@versioned_portfiles);
                   2952:             push(@returned_keys,$key);
1.251     banghart 2953:         }
                   2954:     } 
1.343     banghart 2955:     return (@returned_keys);   
1.305     banghart 2956: }
                   2957: 
1.307     banghart 2958: sub get_next_version {
1.341     banghart 2959:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2960:     my $version;
                   2961:     foreach my $row (@$dir_list) {
                   2962:         my ($file) = split(/\&/,$row,2);
                   2963:         my ($file_name,$file_version,$file_ext) =
                   2964: 	    &file_name_version_ext($file);
                   2965:         if (($file_name eq $answer_name) && 
                   2966: 	    ($file_ext eq $answer_ext)) {
                   2967:                 # gets here if filename and extension match, regardless of version
                   2968:                 if ($file_version ne '') {
                   2969:                 # a versioned file is found  so save it for later
                   2970:                 if ($file_version > $version) {
                   2971: 		    $version = $file_version;
                   2972: 	        }
                   2973:             }
                   2974:         }
                   2975:     } 
                   2976:     $version ++;
                   2977:     return($version);
                   2978: }
                   2979: 
1.305     banghart 2980: sub version_selected_portfile {
1.306     banghart 2981:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2982:     my ($answer_name,$answer_ver,$answer_ext) =
                   2983:         &file_name_version_ext($file_name);
                   2984:     my $new_answer;
                   2985:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2986:     if($env{'form.copy'} eq '-1') {
                   2987:         $new_answer = 'problem getting file';
                   2988:     } else {
                   2989:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2990:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2991:                             $stu_name,$domain,'copy',
                   2992: 		        '/portfolio'.$directory.$new_answer);
                   2993:     }    
                   2994:     return ($new_answer);
1.251     banghart 2995: }
                   2996: 
1.304     albertel 2997: sub file_name_version_ext {
                   2998:     my ($file)=@_;
                   2999:     my @file_parts = split(/\./, $file);
                   3000:     my ($name,$version,$ext);
                   3001:     if (@file_parts > 1) {
                   3002: 	$ext=pop(@file_parts);
                   3003: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   3004: 	    $version=pop(@file_parts);
                   3005: 	}
                   3006: 	$name=join('.',@file_parts);
                   3007:     } else {
                   3008: 	$name=join('.',@file_parts);
                   3009:     }
                   3010:     return($name,$version,$ext);
                   3011: }
                   3012: 
1.44      ng       3013: #--------------------------------------------------------------------------------------
                   3014: #
                   3015: #-------------------------- Next few routines handles grading by section or whole class
                   3016: #
                   3017: #--- Javascript to handle grading by section or whole class
1.42      ng       3018: sub viewgrades_js {
                   3019:     my ($request) = shift;
                   3020: 
1.41      ng       3021:     $request->print(<<VIEWJAVASCRIPT);
                   3022: <script type="text/javascript" language="javascript">
1.45      ng       3023:    function writePoint(partid,weight,point) {
1.125     ng       3024: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3025: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3026: 	if (point == "textval") {
1.125     ng       3027: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3028: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3029: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3030: 		var resetbox = false;
                   3031: 		for (var i=0; i<radioButton.length; i++) {
                   3032: 		    if (radioButton[i].checked) {
                   3033: 			textbox.value = i;
                   3034: 			resetbox = true;
                   3035: 		    }
                   3036: 		}
                   3037: 		if (!resetbox) {
                   3038: 		    textbox.value = "";
                   3039: 		}
                   3040: 		return;
                   3041: 	    }
1.109     matthew  3042: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3043: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3044: 				   ") greater than the weight for the part. Accept?");
                   3045: 		if (resp == false) {
                   3046: 		    textbox.value = "";
                   3047: 		    return;
                   3048: 		}
                   3049: 	    }
1.42      ng       3050: 	    for (var i=0; i<radioButton.length; i++) {
                   3051: 		radioButton[i].checked=false;
1.109     matthew  3052: 		if (parseFloat(point) == i) {
1.42      ng       3053: 		    radioButton[i].checked=true;
                   3054: 		}
                   3055: 	    }
1.41      ng       3056: 
1.42      ng       3057: 	} else {
1.125     ng       3058: 	    textbox.value = parseFloat(point);
1.42      ng       3059: 	}
1.41      ng       3060: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3061: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3062: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3063: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3064: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3065: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3066: 	    if (saveval != "correct") {
                   3067: 		scorename.value = point;
1.43      ng       3068: 		if (selname[0].selected != true) {
                   3069: 		    selname[0].selected = true;
                   3070: 		}
1.42      ng       3071: 	    }
                   3072: 	}
1.125     ng       3073: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3074:     }
                   3075: 
                   3076:     function writeRadText(partid,weight) {
1.125     ng       3077: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3078: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3079:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3080: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3081: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3082: 	    for (var i=0; i<radioButton.length; i++) {
                   3083: 		radioButton[i].checked=false;
                   3084: 
                   3085: 	    }
                   3086: 	    textbox.value = "";
                   3087: 
                   3088: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3089: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3090: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3091: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3092: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3093: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3094: 		if ((saveval != "correct") || override) {
1.42      ng       3095: 		    scorename.value = "";
1.125     ng       3096: 		    if (selval[1].selected) {
                   3097: 			selname[1].selected = true;
                   3098: 		    } else {
                   3099: 			selname[2].selected = true;
                   3100: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3101: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3102: 		    }
1.42      ng       3103: 		}
                   3104: 	    }
1.43      ng       3105: 	} else {
                   3106: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3107: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3108: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3109: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3110: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3111: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3112: 		if ((saveval != "correct") || override) {
1.125     ng       3113: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3114: 		    selname[0].selected = true;
                   3115: 		}
                   3116: 	    }
                   3117: 	}	    
1.42      ng       3118:     }
                   3119: 
                   3120:     function changeSelect(partid,user) {
1.125     ng       3121: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3122: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3123: 	var point  = textbox.value;
1.125     ng       3124: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3125: 
1.109     matthew  3126: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3127: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3128: 	    textbox.value = "";
                   3129: 	    return;
                   3130: 	}
1.109     matthew  3131: 	if (parseFloat(point) > parseFloat(weight)) {
                   3132: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3133: 			       ") greater than the weight of the part. Accept?");
                   3134: 	    if (resp == false) {
                   3135: 		textbox.value = "";
                   3136: 		return;
                   3137: 	    }
                   3138: 	}
1.42      ng       3139: 	selval[0].selected = true;
                   3140:     }
                   3141: 
                   3142:     function changeOneScore(partid,user) {
1.125     ng       3143: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3144: 	if (selval[1].selected || selval[2].selected) {
                   3145: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3146: 	    if (selval[2].selected) {
                   3147: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3148: 	    }
1.269     raeburn  3149:         }
1.42      ng       3150:     }
                   3151: 
                   3152:     function resetEntry(numpart) {
                   3153: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3154: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3155: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3156: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3157: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3158: 	    for (var i=0; i<radioButton.length; i++) {
                   3159: 		radioButton[i].checked=false;
                   3160: 
                   3161: 	    }
                   3162: 	    textbox.value = "";
                   3163: 	    selval[0].selected = true;
                   3164: 
                   3165: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3166: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3167: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3168: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3169: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3170: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3171: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3172: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3173: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3174: 		if (saveselval == "excused") {
1.43      ng       3175: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3176: 		} else {
1.43      ng       3177: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3178: 		}
                   3179: 	    }
1.41      ng       3180: 	}
1.42      ng       3181:     }
                   3182: 
1.41      ng       3183: </script>
                   3184: VIEWJAVASCRIPT
1.42      ng       3185: }
                   3186: 
1.44      ng       3187: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3188: sub viewgrades {
                   3189:     my ($request) = shift;
                   3190:     &viewgrades_js($request);
1.41      ng       3191: 
1.324     albertel 3192:     my ($symb) = &get_symb($request);
1.168     albertel 3193:     #need to make sure we have the correct data for later EXT calls, 
                   3194:     #thus invalidate the cache
                   3195:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3196:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3197:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3198:     &Apache::lonnet::clear_EXT_cache_status();
                   3199: 
1.398     albertel 3200:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3201:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3202: 
                   3203:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3204:     $result.=&jscriptNform($symb);
1.41      ng       3205: 
1.44      ng       3206:     #beginning of class grading form
1.442     banghart 3207:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3208:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3209: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3210: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3211: 	&build_section_inputs().
1.257     albertel 3212: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3213: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3214: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3215: 
1.126     ng       3216:     my $sectionClass;
1.430     banghart 3217:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3218:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3219: 	$sectionClass='Class';
1.257     albertel 3220:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3221: 	$sectionClass='Students in no Section';
1.52      albertel 3222:     } else {
1.485     albertel 3223: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3224:     }
1.485     albertel 3225:     $result.=
                   3226: 	'<h3>'.
                   3227: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3228:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3229:     #radio buttons/text box for assigning points for a section or class.
                   3230:     #handles different parts of a problem
1.375     albertel 3231:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3232:     my %weight = ();
                   3233:     my $ctsparts = 0;
1.45      ng       3234:     my %seen = ();
1.375     albertel 3235:     my @part_response_id = &flatten_responseType($responseType);
                   3236:     foreach my $part_response_id (@part_response_id) {
                   3237:     	my ($partid,$respid) = @{ $part_response_id };
                   3238: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3239: 	next if $seen{$partid};
                   3240: 	$seen{$partid}++;
1.375     albertel 3241: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3242: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3243: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3244: 
1.324     albertel 3245: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3246: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3247: 	my $ctr = 0;
1.42      ng       3248: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3249: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3250: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3251: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3252: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3253: 	    $ctr++;
                   3254: 	}
1.485     albertel 3255: 	$radio.='</tr></table>';
                   3256: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3257: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3258: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3259: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3260: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3261: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3262: 		$weight{$partid}.')"> '.
1.401     albertel 3263: 	    '<option selected="selected"> </option>'.
1.485     albertel 3264: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3265: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3266: 	    '</select></td>'.
                   3267:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3268: 	$line.='<input type="hidden" name="partid_'.
                   3269: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3270: 	$line.='<input type="hidden" name="weight_'.
                   3271: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3272: 
                   3273: 	$result.=
                   3274: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3275: 	    &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).
                   3276: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3277: 	$ctsparts++;
1.41      ng       3278:     }
1.474     albertel 3279:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3280: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3281:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3282: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3283: 
1.44      ng       3284:     #table listing all the students in a section/class
                   3285:     #header of table
1.485     albertel 3286:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3287: 			 $section_display).'</h3>';
1.474     albertel 3288:     $result.= &Apache::loncommon::start_data_table().
                   3289: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3290: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3291: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3292:     my (@parts) = sort(&getpartlist($symb));
                   3293:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3294:     my @partids = ();
1.41      ng       3295:     foreach my $part (@parts) {
                   3296: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3297: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3298: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3299: 	my ($partid) = &split_part_type($part);
1.524     raeburn  3300:         push(@partids,$partid);
1.324     albertel 3301: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3302: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3303: 	    $result.='<th>'.
                   3304: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3305: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3306: 	    next;
1.485     albertel 3307: 	    
1.207     albertel 3308: 	} else {
1.485     albertel 3309: 	    if ($display =~ /Problem Status/) {
                   3310: 		my $grade_status_mt = &mt('Grade Status');
                   3311: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3312: 	    }
                   3313: 	    my $part_mt = &mt('Part:');
                   3314: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3315: 	}
1.485     albertel 3316: 
1.474     albertel 3317: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3318:     }
1.474     albertel 3319:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3320: 
1.270     albertel 3321:     my %last_resets = 
                   3322: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3323: 
1.41      ng       3324:     #get info for each student
1.44      ng       3325:     #list all the students - with points and grade status
1.257     albertel 3326:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3327:     my $ctr = 0;
1.294     albertel 3328:     foreach (sort 
                   3329: 	     {
                   3330: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3331: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3332: 		 }
                   3333: 		 return $a cmp $b;
                   3334: 	     } (keys(%$fullname))) {
1.126     ng       3335: 	$ctr++;
1.324     albertel 3336: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3337: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3338:     }
1.474     albertel 3339:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3340:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3341:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3342: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3343:     if (scalar(%$fullname) eq 0) {
                   3344: 	my $colspan=3+scalar(@parts);
1.433     banghart 3345: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3346:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3347: 	$result='<span class="LC_warning">'.
1.485     albertel 3348: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3349: 	        $section_display, $stu_status).
1.433     banghart 3350: 	    '</span>';
1.96      albertel 3351:     }
1.324     albertel 3352:     $result.=&show_grading_menu_form($symb);
1.41      ng       3353:     return $result;
                   3354: }
                   3355: 
1.44      ng       3356: #--- call by previous routine to display each student
1.41      ng       3357: sub viewstudentgrade {
1.324     albertel 3358:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3359:     my ($uname,$udom) = split(/:/,$student);
                   3360:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3361:     my %aggregates = (); 
1.474     albertel 3362:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3363: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3364: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3365: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3366: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3367: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3368:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3369:     foreach my $apart (@$parts) {
                   3370: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3371: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3372:         $result.='<td align="center">';
1.269     raeburn  3373:         my ($aggtries,$totaltries);
                   3374:         unless (exists($aggregates{$part})) {
1.270     albertel 3375: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3376: 
                   3377: 	    $aggtries = $totaltries;
1.269     raeburn  3378:             if ($$last_resets{$part}) {  
1.270     albertel 3379:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3380: 					   $part);
                   3381:             }
1.269     raeburn  3382:             $result.='<input type="hidden" name="'.
                   3383:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3384:             $result.='<input type="hidden" name="'.
                   3385:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3386:             $aggregates{$part} = 1;
                   3387:         }
1.41      ng       3388: 	if ($type eq 'awarded') {
1.320     albertel 3389: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3390: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3391: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3392: 	    $result.='<input type="text" name="'.
1.89      albertel 3393: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3394: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3395: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3396: 	} elsif ($type eq 'solved') {
                   3397: 	    my ($status,$foo)=split(/_/,$score,2);
                   3398: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3399: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3400: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3401: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3402: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3403: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3404: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3405: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3406: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3407: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3408: 	} else {
                   3409: 	    $result.='<input type="hidden" name="'.
                   3410: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3411: 		    "\n";
1.233     albertel 3412: 	    $result.='<input type="text" name="'.
1.122     ng       3413: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3414: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3415: 	}
                   3416:     }
1.474     albertel 3417:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3418:     return $result;
1.38      ng       3419: }
                   3420: 
1.44      ng       3421: #--- change scores for all the students in a section/class
                   3422: #    record does not get update if unchanged
1.38      ng       3423: sub editgrades {
1.41      ng       3424:     my ($request) = @_;
                   3425: 
1.324     albertel 3426:     my $symb=&get_symb($request);
1.433     banghart 3427:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3428:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3429:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3430:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3431: 
1.477     albertel 3432:     my $result= &Apache::loncommon::start_data_table().
                   3433: 	&Apache::loncommon::start_data_table_header_row().
                   3434: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3435: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3436:     my %scoreptr = (
                   3437: 		    'correct'  =>'correct_by_override',
                   3438: 		    'incorrect'=>'incorrect_by_override',
                   3439: 		    'excused'  =>'excused',
                   3440: 		    'ungraded' =>'ungraded_attempted',
                   3441: 		    'nothing'  => '',
                   3442: 		    );
1.257     albertel 3443:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3444: 
1.44      ng       3445:     my (@partid);
                   3446:     my %weight = ();
1.54      albertel 3447:     my %columns = ();
1.44      ng       3448:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3449: 
1.324     albertel 3450:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3451:     my $header;
1.257     albertel 3452:     while ($ctr < $env{'form.totalparts'}) {
                   3453: 	my $partid = $env{'form.partid_'.$ctr};
1.524     raeburn  3454: 	push(@partid,$partid);
1.257     albertel 3455: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3456: 	$ctr++;
1.54      albertel 3457:     }
1.324     albertel 3458:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3459:     foreach my $partid (@partid) {
1.478     albertel 3460: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3461: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3462: 	$columns{$partid}=2;
                   3463: 	foreach my $stores (@parts) {
                   3464: 	    my ($part,$type) = &split_part_type($stores);
                   3465: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3466: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3467: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3468: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3469: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3470: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3471: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3472: 	    $columns{$partid}+=2;
                   3473: 	}
                   3474:     }
                   3475:     foreach my $partid (@partid) {
1.324     albertel 3476: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3477: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3478: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3479: 	    '</th>';
1.54      albertel 3480: 
1.44      ng       3481:     }
1.477     albertel 3482:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3483: 	&Apache::loncommon::start_data_table_header_row().
                   3484: 	$header.
                   3485: 	&Apache::loncommon::end_data_table_header_row();
                   3486:     my @noupdate;
1.126     ng       3487:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3488:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3489: 	my $line;
1.257     albertel 3490: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3491: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3492: 	my %newrecord;
                   3493: 	my $updateflag = 0;
1.281     albertel 3494: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3495: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3496: 	if (!&canmodify($usec)) {
1.126     ng       3497: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3498: 	    push(@noupdate,
1.478     albertel 3499: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3500: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3501: 	    next;
                   3502: 	}
1.269     raeburn  3503:         my %aggregate = ();
                   3504:         my $aggregateflag = 0;
1.281     albertel 3505: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3506: 	foreach (@partid) {
1.257     albertel 3507: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3508: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3509: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3510: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3511: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3512: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3513: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3514: 	    my $score;
                   3515: 	    if ($partial eq '') {
1.257     albertel 3516: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3517: 	    } elsif ($partial > 0) {
                   3518: 		$score = 'correct_by_override';
                   3519: 	    } elsif ($partial == 0) {
                   3520: 		$score = 'incorrect_by_override';
                   3521: 	    }
1.257     albertel 3522: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3523: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3524: 
1.292     albertel 3525: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3526: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3527: 	    if ($dropMenu eq 'reset status' &&
                   3528: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3529: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3530: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3531: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3532: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3533: 		$updateflag = 1;
1.269     raeburn  3534:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3535:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3536:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3537:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3538:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3539:                     $aggregateflag = 1;
                   3540:                 }
1.139     albertel 3541: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3542: 		$updateflag = 1;
                   3543: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3544: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3545: 		$rec_update++;
1.125     ng       3546: 	    }
                   3547: 
1.93      albertel 3548: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3549: 		'<td align="center">'.$awarded.
                   3550: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3551: 
1.54      albertel 3552: 
                   3553: 	    my $partid=$_;
                   3554: 	    foreach my $stores (@parts) {
                   3555: 		my ($part,$type) = &split_part_type($stores);
                   3556: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3557: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3558: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3559: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3560: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3561: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3562: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3563: 		    $updateflag=1;
                   3564: 		}
1.93      albertel 3565: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3566: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3567: 	    }
1.44      ng       3568: 	}
1.477     albertel 3569: 	$line.="\n";
1.301     albertel 3570: 
                   3571: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3572: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3573: 
1.44      ng       3574: 	if ($updateflag) {
                   3575: 	    $count++;
1.257     albertel 3576: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3577: 				    $udom,$uname);
1.301     albertel 3578: 
                   3579: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3580: 					      $cnum,$udom,$uname)) {
                   3581: 		# need to figure out if should be in queue.
                   3582: 		my %record =  
                   3583: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3584: 					     $udom,$uname);
                   3585: 		my $all_graded = 1;
                   3586: 		my $none_graded = 1;
                   3587: 		foreach my $part (@parts) {
                   3588: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3589: 			$all_graded = 0;
                   3590: 		    } else {
                   3591: 			$none_graded = 0;
                   3592: 		    }
                   3593: 		}
                   3594: 
                   3595: 		if ($all_graded || $none_graded) {
                   3596: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3597: 							   $symb,$cdom,$cnum,
                   3598: 							   $udom,$uname);
                   3599: 		}
                   3600: 	    }
                   3601: 
1.477     albertel 3602: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3603: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3604: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3605: 	    $updateCtr++;
1.93      albertel 3606: 	} else {
1.477     albertel 3607: 	    push(@noupdate,
                   3608: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3609: 	    $noupdateCtr++;
1.44      ng       3610: 	}
1.269     raeburn  3611:         if ($aggregateflag) {
                   3612:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3613: 				  $cdom,$cnum);
1.269     raeburn  3614:         }
1.93      albertel 3615:     }
1.477     albertel 3616:     if (@noupdate) {
1.126     ng       3617: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3618: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3619: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3620: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3621: 	    &mt('No Changes Occurred For the Students Below').
                   3622: 	    '</td>'.
1.477     albertel 3623: 	    &Apache::loncommon::end_data_table_row();
                   3624: 	foreach my $line (@noupdate) {
                   3625: 	    $result.=
                   3626: 		&Apache::loncommon::start_data_table_row().
                   3627: 		$line.
                   3628: 		&Apache::loncommon::end_data_table_row();
                   3629: 	}
1.44      ng       3630:     }
1.477     albertel 3631:     $result .= &Apache::loncommon::end_data_table().
                   3632: 	&show_grading_menu_form($symb);
1.478     albertel 3633:     my $msg = '<p><b>'.
                   3634: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3635: 	    $rec_update,$count).'</b><br />'.
                   3636: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3637: 	'</b></p>';
1.44      ng       3638:     return $title.$msg.$result;
1.5       albertel 3639: }
1.54      albertel 3640: 
                   3641: sub split_part_type {
                   3642:     my ($partstr) = @_;
                   3643:     my ($temp,@allparts)=split(/_/,$partstr);
                   3644:     my $type=pop(@allparts);
1.439     albertel 3645:     my $part=join('_',@allparts);
1.54      albertel 3646:     return ($part,$type);
                   3647: }
                   3648: 
1.44      ng       3649: #------------- end of section for handling grading by section/class ---------
                   3650: #
                   3651: #----------------------------------------------------------------------------
                   3652: 
1.5       albertel 3653: 
1.44      ng       3654: #----------------------------------------------------------------------------
                   3655: #
                   3656: #-------------------------- Next few routines handles grading by csv upload
                   3657: #
                   3658: #--- Javascript to handle csv upload
1.27      albertel 3659: sub csvupload_javascript_reverse_associate {
1.246     albertel 3660:     my $error1=&mt('You need to specify the username or ID');
                   3661:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3662:   return(<<ENDPICK);
                   3663:   function verify(vf) {
                   3664:     var foundsomething=0;
                   3665:     var founduname=0;
1.243     albertel 3666:     var foundID=0;
1.27      albertel 3667:     for (i=0;i<=vf.nfields.value;i++) {
                   3668:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3669:       if (i==0 && tw!=0) { foundID=1; }
                   3670:       if (i==1 && tw!=0) { founduname=1; }
                   3671:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3672:     }
1.246     albertel 3673:     if (founduname==0 && foundID==0) {
                   3674: 	alert('$error1');
                   3675: 	return;
1.27      albertel 3676:     }
                   3677:     if (foundsomething==0) {
1.246     albertel 3678: 	alert('$error2');
                   3679: 	return;
1.27      albertel 3680:     }
                   3681:     vf.submit();
                   3682:   }
                   3683:   function flip(vf,tf) {
                   3684:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3685:     var i;
                   3686:     for (i=0;i<=vf.nfields.value;i++) {
                   3687:       //can not pick the same destination field for both name and domain
                   3688:       if (((i ==0)||(i ==1)) && 
                   3689:           ((tf==0)||(tf==1)) && 
                   3690:           (i!=tf) &&
                   3691:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3692:         eval('vf.f'+i+'.selectedIndex=0;')
                   3693:       }
                   3694:     }
                   3695:   }
                   3696: ENDPICK
                   3697: }
                   3698: 
                   3699: sub csvupload_javascript_forward_associate {
1.246     albertel 3700:     my $error1=&mt('You need to specify the username or ID');
                   3701:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3702:   return(<<ENDPICK);
                   3703:   function verify(vf) {
                   3704:     var foundsomething=0;
                   3705:     var founduname=0;
1.243     albertel 3706:     var foundID=0;
1.27      albertel 3707:     for (i=0;i<=vf.nfields.value;i++) {
                   3708:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3709:       if (tw==1) { foundID=1; }
                   3710:       if (tw==2) { founduname=1; }
                   3711:       if (tw>3) { foundsomething=1; }
1.27      albertel 3712:     }
1.246     albertel 3713:     if (founduname==0 && foundID==0) {
                   3714: 	alert('$error1');
                   3715: 	return;
1.27      albertel 3716:     }
                   3717:     if (foundsomething==0) {
1.246     albertel 3718: 	alert('$error2');
                   3719: 	return;
1.27      albertel 3720:     }
                   3721:     vf.submit();
                   3722:   }
                   3723:   function flip(vf,tf) {
                   3724:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3725:     var i;
                   3726:     //can not pick the same destination field twice
                   3727:     for (i=0;i<=vf.nfields.value;i++) {
                   3728:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3729:         eval('vf.f'+i+'.selectedIndex=0;')
                   3730:       }
                   3731:     }
                   3732:   }
                   3733: ENDPICK
                   3734: }
                   3735: 
1.26      albertel 3736: sub csvuploadmap_header {
1.324     albertel 3737:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3738:     my $javascript;
1.257     albertel 3739:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3740: 	$javascript=&csvupload_javascript_reverse_associate();
                   3741:     } else {
                   3742: 	$javascript=&csvupload_javascript_forward_associate();
                   3743:     }
1.45      ng       3744: 
1.324     albertel 3745:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3746:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3747:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3748:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3749:     $request->print(<<ENDPICK);
1.26      albertel 3750: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3751: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3752: $result
1.326     albertel 3753: <hr />
1.26      albertel 3754: <h3>Identify fields</h3>
                   3755: Total number of records found in file: $distotal <hr />
                   3756: Enter as many fields as you can. The system will inform you and bring you back
                   3757: to this page if the data selected is insufficient to run your class.<hr />
                   3758: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3759: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3760: <input type="hidden" name="associate"  value="" />
                   3761: <input type="hidden" name="phase"      value="three" />
                   3762: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3763: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3764: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3765: <input type="hidden" name="upfile_associate" 
1.257     albertel 3766:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3767: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3768: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3769: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3770: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3771: <hr />
                   3772: <script type="text/javascript" language="Javascript">
                   3773: $javascript
                   3774: </script>
                   3775: ENDPICK
1.118     ng       3776:     return '';
1.26      albertel 3777: 
                   3778: }
                   3779: 
                   3780: sub csvupload_fields {
1.324     albertel 3781:     my ($symb) = @_;
                   3782:     my (@parts) = &getpartlist($symb);
1.243     albertel 3783:     my @fields=(['ID','Student ID'],
                   3784: 		['username','Student Username'],
                   3785: 		['domain','Student Domain']);
1.324     albertel 3786:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3787:     foreach my $part (sort(@parts)) {
                   3788: 	my @datum;
                   3789: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3790: 	my $name=$part;
                   3791: 	if  (!$display) { $display = $name; }
                   3792: 	@datum=($name,$display);
1.244     albertel 3793: 	if ($name=~/^stores_(.*)_awarded/) {
                   3794: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3795: 	}
1.41      ng       3796: 	push(@fields,\@datum);
                   3797:     }
                   3798:     return (@fields);
1.26      albertel 3799: }
                   3800: 
                   3801: sub csvuploadmap_footer {
1.41      ng       3802:     my ($request,$i,$keyfields) =@_;
                   3803:     $request->print(<<ENDPICK);
1.26      albertel 3804: </table>
                   3805: <input type="hidden" name="nfields" value="$i" />
                   3806: <input type="hidden" name="keyfields" value="$keyfields" />
                   3807: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3808: </form>
                   3809: ENDPICK
                   3810: }
                   3811: 
1.283     albertel 3812: sub checkforfile_js {
1.86      ng       3813:     my $result =<<CSVFORMJS;
                   3814: <script type="text/javascript" language="javascript">
                   3815:     function checkUpload(formname) {
                   3816: 	if (formname.upfile.value == "") {
                   3817: 	    alert("Please use the browse button to select a file from your local directory.");
                   3818: 	    return false;
                   3819: 	}
                   3820: 	formname.submit();
                   3821:     }
                   3822:     </script>
                   3823: CSVFORMJS
1.283     albertel 3824:     return $result;
                   3825: }
                   3826: 
                   3827: sub upcsvScores_form {
                   3828:     my ($request) = shift;
1.324     albertel 3829:     my ($symb)=&get_symb($request);
1.283     albertel 3830:     if (!$symb) {return '';}
                   3831:     my $result=&checkforfile_js();
1.257     albertel 3832:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3833:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3834:     $result.=$table;
1.326     albertel 3835:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3836:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3837:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3838: 	'.</b></td></tr>'."\n";
                   3839:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3840:     my $upload=&mt("Upload Scores");
1.86      ng       3841:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3842:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3843:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3844:     $result.=<<ENDUPFORM;
1.106     albertel 3845: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3846: <input type="hidden" name="symb" value="$symb" />
                   3847: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3848: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3849: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3850: $upfile_select
1.370     www      3851: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3852: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3853: </form>
                   3854: ENDUPFORM
1.370     www      3855:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3856:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3857:     .'</td></tr></table>'."\n";
1.86      ng       3858:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3859:     $result.=&show_grading_menu_form($symb);
1.86      ng       3860:     return $result;
                   3861: }
                   3862: 
                   3863: 
1.26      albertel 3864: sub csvuploadmap {
1.41      ng       3865:     my ($request)= @_;
1.324     albertel 3866:     my ($symb)=&get_symb($request);
1.41      ng       3867:     if (!$symb) {return '';}
1.72      ng       3868: 
1.41      ng       3869:     my $datatoken;
1.257     albertel 3870:     if (!$env{'form.datatoken'}) {
1.41      ng       3871: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3872:     } else {
1.257     albertel 3873: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3874: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3875:     }
1.41      ng       3876:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3877:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3878:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3879:     my ($i,$keyfields);
                   3880:     if (@records) {
1.324     albertel 3881: 	my @fields=&csvupload_fields($symb);
1.45      ng       3882: 
1.257     albertel 3883: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3884: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3885: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3886: 							  \@fields);
                   3887: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3888: 	    chop($keyfields);
                   3889: 	} else {
                   3890: 	    unshift(@fields,['none','']);
                   3891: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3892: 							    \@fields);
1.311     banghart 3893:             foreach my $rec (@records) {
                   3894:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3895:                 if (%temp) {
                   3896:                     $keyfields=join(',',sort(keys(%temp)));
                   3897:                     last;
                   3898:                 }
                   3899:             }
1.41      ng       3900: 	}
                   3901:     }
                   3902:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3903:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3904: 
1.41      ng       3905:     return '';
1.27      albertel 3906: }
                   3907: 
1.246     albertel 3908: sub csvuploadoptions {
1.41      ng       3909:     my ($request)= @_;
1.324     albertel 3910:     my ($symb)=&get_symb($request);
1.257     albertel 3911:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3912:     my $ignore=&mt('Ignore First Line');
                   3913:     $request->print(<<ENDPICK);
                   3914: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3915: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3916: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3917: <!--
1.246     albertel 3918: <p>
                   3919: <label>
                   3920:    <input type="checkbox" name="show_full_results" />
                   3921:    Show a table of all changes
                   3922: </label>
                   3923: </p>
1.302     albertel 3924: -->
1.246     albertel 3925: <p>
                   3926: <label>
                   3927:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3928:    Overwrite any existing score
                   3929: </label>
                   3930: </p>
                   3931: ENDPICK
                   3932:     my %fields=&get_fields();
                   3933:     if (!defined($fields{'domain'})) {
1.257     albertel 3934: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3935: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3936:     }
1.257     albertel 3937:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3938: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3939: 	my $cleankey=$1;
                   3940: 	if ($cleankey eq 'command') { next; }
                   3941: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3942: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3943:     }
                   3944:     # FIXME do a check for any duplicated user ids...
                   3945:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3946:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3947: <hr /></form>'."\n");
1.324     albertel 3948:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3949:     return '';
                   3950: }
                   3951: 
                   3952: sub get_fields {
                   3953:     my %fields;
1.257     albertel 3954:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3955:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3956: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3957: 	    if ($env{'form.f'.$i} ne 'none') {
                   3958: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3959: 	    }
                   3960: 	} else {
1.257     albertel 3961: 	    if ($env{'form.f'.$i} ne 'none') {
                   3962: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3963: 	    }
                   3964: 	}
1.27      albertel 3965:     }
1.246     albertel 3966:     return %fields;
                   3967: }
                   3968: 
                   3969: sub csvuploadassign {
                   3970:     my ($request)= @_;
1.324     albertel 3971:     my ($symb)=&get_symb($request);
1.246     albertel 3972:     if (!$symb) {return '';}
1.345     bowersj2 3973:     my $error_msg = '';
1.246     albertel 3974:     &Apache::loncommon::load_tmp_file($request);
                   3975:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3976:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3977:     my %fields=&get_fields();
1.41      ng       3978:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3979:     my $courseid=$env{'request.course.id'};
1.97      albertel 3980:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3981:     my @notallowed;
1.41      ng       3982:     my @skipped;
                   3983:     my $countdone=0;
                   3984:     foreach my $grade (@gradedata) {
                   3985: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3986: 	my $domain;
                   3987: 	if ($entries{$fields{'domain'}}) {
                   3988: 	    $domain=$entries{$fields{'domain'}};
                   3989: 	} else {
1.257     albertel 3990: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3991: 	}
1.243     albertel 3992: 	$domain=~s/\s//g;
1.41      ng       3993: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3994: 	$username=~s/\s//g;
1.243     albertel 3995: 	if (!$username) {
                   3996: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3997: 	    $id=~s/\s//g;
1.243     albertel 3998: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3999: 	    $username=$ids{$id};
                   4000: 	}
1.41      ng       4001: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 4002: 	    my $id=$entries{$fields{'ID'}};
                   4003: 	    $id=~s/\s//g;
                   4004: 	    if ($id) {
                   4005: 		push(@skipped,"$id:$domain");
                   4006: 	    } else {
                   4007: 		push(@skipped,"$username:$domain");
                   4008: 	    }
1.41      ng       4009: 	    next;
                   4010: 	}
1.108     albertel 4011: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4012: 	if (!&canmodify($usec)) {
                   4013: 	    push(@notallowed,"$username:$domain");
                   4014: 	    next;
                   4015: 	}
1.244     albertel 4016: 	my %points;
1.41      ng       4017: 	my %grades;
                   4018: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4019: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4020: 		$dest eq 'domain') { next; }
                   4021: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4022: 	    if ($dest=~/stores_(.*)_points/) {
                   4023: 		my $part=$1;
                   4024: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4025: 					      $symb,$domain,$username);
1.345     bowersj2 4026:                 if ($wgt) {
                   4027:                     $entries{$fields{$dest}}=~s/\s//g;
                   4028:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4029:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4030:                                           : 'correct_by_override';
1.345     bowersj2 4031:                     $grades{"resource.$part.awarded"}=$pcr;
                   4032:                     $grades{"resource.$part.solved"}=$award;
                   4033:                     $points{$part}=1;
                   4034:                 } else {
                   4035:                     $error_msg = "<br />" .
                   4036:                         &mt("Some point values were assigned"
                   4037:                             ." for problems with a weight "
                   4038:                             ."of zero. These values were "
                   4039:                             ."ignored.");
                   4040:                 }
1.244     albertel 4041: 	    } else {
                   4042: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4043: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4044: 		my $store_key=$dest;
                   4045: 		$store_key=~s/^stores/resource/;
                   4046: 		$store_key=~s/_/\./g;
                   4047: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4048: 	    }
1.41      ng       4049: 	}
1.508     www      4050: 	if (! %grades) { 
                   4051:            push(@skipped,&mt("[_1]: no data to save","$username:$domain")); 
                   4052:         } else {
                   4053: 	   $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   4054: 	   my $result=&Apache::lonnet::cstore(\%grades,$symb,
1.302     albertel 4055: 					   $env{'request.course.id'},
                   4056: 					   $domain,$username);
1.508     www      4057: 	   if ($result eq 'ok') {
                   4058: 	      $request->print('.');
                   4059: 	   } else {
                   4060: 	      $request->print("<p><span class=\"LC_error\">".
                   4061:                               &mt("Failed to save data for student [_1]. Message when trying to save was: [_2]",
                   4062:                                   "$username:$domain",$result)."</span></p>");
                   4063: 	   }
                   4064: 	   $request->rflush();
                   4065: 	   $countdone++;
                   4066:         }
1.41      ng       4067:     }
1.508     www      4068:     $request->print('<br /><span class="LC_info">'.&mt("Saved [_1] students",$countdone)."</span>\n");
1.41      ng       4069:     if (@skipped) {
1.508     www      4070: 	$request->print('<p><span class="LC_warning">'.&mt('Skipped Students').'</span></p>');
1.106     albertel 4071: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4072:     }
                   4073:     if (@notallowed) {
1.508     www      4074: 	$request->print('<p><span class="LC_error">'.&mt('Students Not Allowed to Modify').'</span></p>');
1.106     albertel 4075: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4076:     }
1.106     albertel 4077:     $request->print("<br />\n");
1.324     albertel 4078:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4079:     return $error_msg;
1.26      albertel 4080: }
1.44      ng       4081: #------------- end of section for handling csv file upload ---------
                   4082: #
                   4083: #-------------------------------------------------------------------
                   4084: #
1.122     ng       4085: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4086: #
                   4087: #--- Select a page/sequence and a student to grade
1.68      ng       4088: sub pickStudentPage {
                   4089:     my ($request) = shift;
                   4090: 
                   4091:     $request->print(<<LISTJAVASCRIPT);
                   4092: <script type="text/javascript" language="javascript">
                   4093: 
                   4094: function checkPickOne(formname) {
1.76      ng       4095:     if (radioSelection(formname.student) == null) {
1.68      ng       4096: 	alert("Please select the student you wish to grade.");
                   4097: 	return;
                   4098:     }
1.125     ng       4099:     ptr = pullDownSelection(formname.selectpage);
                   4100:     formname.page.value = formname["page"+ptr].value;
                   4101:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4102:     formname.submit();
                   4103: }
                   4104: 
                   4105: </script>
                   4106: LISTJAVASCRIPT
1.118     ng       4107:     &commonJSfunctions($request);
1.324     albertel 4108:     my ($symb) = &get_symb($request);
1.257     albertel 4109:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4110:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4111:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4112: 
1.398     albertel 4113:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4114: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4115: 
1.80      ng       4116:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4117:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4118:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4119: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4120: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4121:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4122:     my $ctr=0;
1.68      ng       4123:     foreach (@$titles) {
                   4124: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4125: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4126: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4127: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4128: 	$ctr++;
1.68      ng       4129:     }
1.485     albertel 4130:     $select.= '</select>';
                   4131:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4132: 
1.70      ng       4133:     $ctr=0;
                   4134:     foreach (@$titles) {
                   4135: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4136: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4137: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4138: 	$ctr++;
                   4139:     }
1.72      ng       4140:     $result.='<input type="hidden" name="page" />'."\n".
                   4141: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4142: 
1.485     albertel 4143:     my $options =
                   4144: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4145: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4146:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4147: 
                   4148:     $options =
                   4149: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4150: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4151: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4152:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4153:     
                   4154:     $result.=&build_section_inputs();
1.442     banghart 4155:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4156:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4157: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4158: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4159: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4160: 
1.485     albertel 4161:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4162: 			  '<input type="text" name="CODE" value="" />').
                   4163: 			      '<br />'."\n";
1.382     albertel 4164: 
1.80      ng       4165:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4166: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4167: 
1.68      ng       4168:     $request->print($result);
                   4169: 
1.485     albertel 4170:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4171: 	&Apache::loncommon::start_data_table().
                   4172: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4173: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4174: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4175: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4176: 	'<th>'.&nameUserString('header').'</th>'.
                   4177: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4178:  
1.76      ng       4179:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4180:     my $ptr = 1;
1.294     albertel 4181:     foreach my $student (sort 
                   4182: 			 {
                   4183: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4184: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4185: 			     }
                   4186: 			     return $a cmp $b;
                   4187: 			 } (keys(%$fullname))) {
1.68      ng       4188: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4189: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4190:                                   : '</td>');
1.126     ng       4191: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4192: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4193: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4194: 	$studentTable.=
                   4195: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4196:                          : '');
1.68      ng       4197: 	$ptr++;
                   4198:     }
1.484     albertel 4199:     if ($ptr%2 == 0) {
                   4200: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4201: 	    &Apache::loncommon::end_data_table_row();
                   4202:     }
                   4203:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4204:     $studentTable.='<input type="button" '.
1.485     albertel 4205: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4206: 
1.324     albertel 4207:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4208:     $request->print($studentTable);
                   4209: 
                   4210:     return '';
                   4211: }
                   4212: 
                   4213: sub getSymbMap {
1.132     bowersj2 4214:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4215: 
                   4216:     my %symbx = ();
                   4217:     my @titles = ();
1.117     bowersj2 4218:     my $minder = 0;
                   4219: 
                   4220:     # Gather every sequence that has problems.
1.240     albertel 4221:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4222: 					       1,0,1);
1.117     bowersj2 4223:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4224: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4225: 	    my $title = $minder.'.'.
                   4226: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4227: 	    push(@titles, $title); # minder in case two titles are identical
                   4228: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4229: 	    $minder++;
1.241     albertel 4230: 	}
1.68      ng       4231:     }
                   4232:     return \@titles,\%symbx;
                   4233: }
                   4234: 
1.72      ng       4235: #
                   4236: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4237: sub displayPage {
                   4238:     my ($request) = shift;
                   4239: 
1.324     albertel 4240:     my ($symb) = &get_symb($request);
1.257     albertel 4241:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4242:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4243:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4244:     my $pageTitle = $env{'form.page'};
1.103     albertel 4245:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4246:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4247:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4248: 
                   4249:     #need to make sure we have the correct data for later EXT calls, 
                   4250:     #thus invalidate the cache
                   4251:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4252:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4253:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4254:     &Apache::lonnet::clear_EXT_cache_status();
                   4255: 
1.103     albertel 4256:     if (!&canview($usec)) {
1.485     albertel 4257: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4258: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4259: 	return;
                   4260:     }
1.398     albertel 4261:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4262:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4263: 	'</h3>'."\n";
1.500     albertel 4264:     $env{'form.CODE'} = uc($env{'form.CODE'});
1.501     foxr     4265:     if (&Apache::lonnet::validCODE(uc($env{'form.CODE'}))) {
1.485     albertel 4266: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4267:     } else {
                   4268: 	delete($env{'form.CODE'});
                   4269:     }
1.71      ng       4270:     &sub_page_js($request);
                   4271:     $request->print($result);
                   4272: 
1.132     bowersj2 4273:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4274:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4275:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4276:     if (!$map) {
1.485     albertel 4277: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4278: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4279: 	return; 
                   4280:     }
1.68      ng       4281:     my $iterator = $navmap->getIterator($map->map_start(),
                   4282: 					$map->map_finish());
                   4283: 
1.71      ng       4284:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4285: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4286: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4287: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4288: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4289: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4290: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4291: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4292: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4293: 
1.382     albertel 4294:     if (defined($env{'form.CODE'})) {
                   4295: 	$studentTable.=
                   4296: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4297:     }
1.381     albertel 4298:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4299: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4300: 
1.485     albertel 4301:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4302: 	&Apache::loncommon::start_data_table().
                   4303: 	&Apache::loncommon::start_data_table_header_row().
                   4304: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4305: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4306: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4307: 
1.329     albertel 4308:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4309:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4310:     $iterator->next(); # skip the first BEGIN_MAP
                   4311:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4312:     while ($depth > 0) {
1.68      ng       4313:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4314:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4315: 
1.385     albertel 4316:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4317: 	    my $parts = $curRes->parts();
1.68      ng       4318:             my $title = $curRes->compTitle();
1.71      ng       4319: 	    my $symbx = $curRes->symb();
1.484     albertel 4320: 	    $studentTable.=
                   4321: 		&Apache::loncommon::start_data_table_row().
                   4322: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4323: 		(scalar(@{$parts}) == 1 ? '' 
                   4324: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4325: 							scalar(@{$parts}))
                   4326: 		 ).
                   4327: 		 '</td>';
1.71      ng       4328: 	    $studentTable.='<td valign="top">';
1.382     albertel 4329: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4330: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4331: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4332: 					     undef,'both',\%form);
1.71      ng       4333: 	    } else {
1.382     albertel 4334: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4335: 		$companswer =~ s|<form(.*?)>||g;
                   4336: 		$companswer =~ s|</form>||g;
1.71      ng       4337: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4338: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4339: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4340: #		}
1.116     ng       4341: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4342: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4343: 	    }
                   4344: 
1.257     albertel 4345: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4346: 
1.257     albertel 4347: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4348: 		if ($record{'version'} eq '') {
1.485     albertel 4349: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4350: 		} else {
1.116     ng       4351: 		    my %responseType = ();
                   4352: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4353: 			my @responseIds =$curRes->responseIds($partid);
                   4354: 			my @responseType =$curRes->responseType($partid);
                   4355: 			my %responseIds;
                   4356: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4357: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4358: 			}
                   4359: 			$responseType{$partid} = \%responseIds;
1.116     ng       4360: 		    }
1.148     albertel 4361: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4362: 
1.71      ng       4363: 		}
1.257     albertel 4364: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4365: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4366: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4367: 									$env{'request.course.id'},
1.71      ng       4368: 									'','.submission');
                   4369:  
                   4370: 	    }
1.103     albertel 4371: 	    if (&canmodify($usec)) {
                   4372: 		foreach my $partid (@{$parts}) {
                   4373: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4374: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4375: 		    $question++;
                   4376: 		}
1.196     albertel 4377: 		$prob++;
1.71      ng       4378: 	    }
                   4379: 	    $studentTable.='</td></tr>';
1.68      ng       4380: 
1.103     albertel 4381: 	}
1.68      ng       4382:         $curRes = $iterator->next();
                   4383:     }
                   4384: 
1.485     albertel 4385:     $studentTable.='</table>'."\n".
                   4386: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4387: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4388: 	'</form>'."\n";
1.324     albertel 4389:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4390:     $request->print($studentTable);
                   4391: 
                   4392:     return '';
1.119     ng       4393: }
                   4394: 
                   4395: sub displaySubByDates {
1.148     albertel 4396:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4397:     my $isCODE=0;
1.335     albertel 4398:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4399:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4400:     my $studentTable=&Apache::loncommon::start_data_table().
                   4401: 	&Apache::loncommon::start_data_table_header_row().
                   4402: 	'<th>'.&mt('Date/Time').'</th>'.
                   4403: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4404: 	'<th>'.&mt('Submission').'</th>'.
                   4405: 	'<th>'.&mt('Status').'</th>'.
                   4406: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4407:     my ($version);
                   4408:     my %mark;
1.148     albertel 4409:     my %orders;
1.119     ng       4410:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4411:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4412: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4413:     }
1.335     albertel 4414: 
                   4415:     my $interaction;
1.525     raeburn  4416:     my $no_increment = 1;
1.119     ng       4417:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4418: 	my $timestamp = 
                   4419: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4420: 	if (exists($$record{$version.':resource.0.version'})) {
                   4421: 	    $interaction = $$record{$version.':resource.0.version'};
                   4422: 	}
                   4423: 
                   4424: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4425: 		             : "$version:resource");
1.467     albertel 4426: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4427: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4428: 	if ($isCODE) {
                   4429: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4430: 	}
1.119     ng       4431: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4432: 	my @displaySub = ();
                   4433: 	foreach my $partid (@{$parts}) {
1.335     albertel 4434: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4435: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4436: 	    
                   4437: 
1.122     ng       4438: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4439: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4440: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4441: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4442: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4443: 
                   4444: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4445: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4446: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4447: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4448: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4449: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4450: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4451: 		    } else {
1.467     albertel 4452: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4453: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4454: 		    }
1.335     albertel 4455: 		    my $responseType=($isTask ? 'Task'
                   4456:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4457: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4458: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4459: 			$orders{$partid}->{$responseId}=
1.525     raeburn  4460: 			    &get_order($partid,$responseId,$symb,$uname,$udom,
                   4461:                                        $no_increment);
1.148     albertel 4462: 		    }
1.147     albertel 4463: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4464: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4465: 		}
                   4466: 	    }
1.335     albertel 4467: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4468: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4469: 				    $$record{"$where.$partid.checkedin"},
                   4470: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4471: 					'<br />';
1.335     albertel 4472: 	    }
                   4473: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4474: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4475: 		    lc($$record{"$where.$partid.award"}).' '.
                   4476: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4477: 		    '<br />';
                   4478: 	    }
1.335     albertel 4479: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4480: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4481: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4482: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4483: 		$displaySub[2].=
                   4484: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4485: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4486: 	    }
                   4487: 	}
                   4488: 	# needed because old essay regrader has not parts info
                   4489: 	if (exists $$record{"$version:resource.regrader"}) {
                   4490: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4491: 	}
                   4492: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4493: 	if ($displaySub[2]) {
1.467     albertel 4494: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4495: 	}
1.467     albertel 4496: 	$studentTable.='&nbsp;</td>'.
                   4497: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4498:     }
1.467     albertel 4499:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4500:     return $studentTable;
1.71      ng       4501: }
                   4502: 
                   4503: sub updateGradeByPage {
                   4504:     my ($request) = shift;
                   4505: 
1.257     albertel 4506:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4507:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4508:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4509:     my $pageTitle = $env{'form.page'};
1.103     albertel 4510:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4511:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4512:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4513:     if (!&canmodify($usec)) {
1.526     raeburn  4514: 	$request->print('<span class="LC_warning">'.&mt('Unable to modify requested student ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4515: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4516: 	return;
                   4517:     }
1.398     albertel 4518:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.526     raeburn  4519:     $result.='<h3>&nbsp;'.&mt('Student: ').&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4520: 	'</h3>'."\n";
1.70      ng       4521: 
1.68      ng       4522:     $request->print($result);
                   4523: 
1.132     bowersj2 4524:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4525:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4526:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4527:     if (!$map) {
1.527     raeburn  4528: 	$request->print('<span class="LC_warning">'.&mt('Unable to grade requested sequence ([_1]).',$resUrl).'</span>');
1.324     albertel 4529: 	my ($symb)=&get_symb($request);
                   4530: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4531: 	return; 
                   4532:     }
1.71      ng       4533:     my $iterator = $navmap->getIterator($map->map_start(),
                   4534: 					$map->map_finish());
1.70      ng       4535: 
1.484     albertel 4536:     my $studentTable=
                   4537: 	&Apache::loncommon::start_data_table().
                   4538: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4539: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4540: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4541: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4542: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4543: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4544: 
                   4545:     $iterator->next(); # skip the first BEGIN_MAP
                   4546:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4547:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4548:     while ($depth > 0) {
1.71      ng       4549:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4550:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4551: 
1.385     albertel 4552:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4553: 	    my $parts = $curRes->parts();
1.71      ng       4554:             my $title = $curRes->compTitle();
                   4555: 	    my $symbx = $curRes->symb();
1.484     albertel 4556: 	    $studentTable.=
                   4557: 		&Apache::loncommon::start_data_table_row().
                   4558: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4559: 		(scalar(@{$parts}) == 1 ? '' 
1.526     raeburn  4560:                                         : '<br />('.&mt('[quant,_1,&nbsp;part]',scalar(@{$parts}))
                   4561: 		.')').'</td>';
1.71      ng       4562: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4563: 
                   4564: 	    my %newrecord=();
                   4565: 	    my @displayPts=();
1.269     raeburn  4566:             my %aggregate = ();
                   4567:             my $aggregateflag = 0;
1.71      ng       4568: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4569: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4570: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4571: 
1.257     albertel 4572: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4573: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4574: 		my $partial = $newpts/$wgt;
                   4575: 		my $score;
                   4576: 		if ($partial > 0) {
                   4577: 		    $score = 'correct_by_override';
1.125     ng       4578: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4579: 		    $score = 'incorrect_by_override';
                   4580: 		}
1.257     albertel 4581: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4582: 		if ($dropMenu eq 'excused') {
1.71      ng       4583: 		    $partial = '';
                   4584: 		    $score = 'excused';
1.125     ng       4585: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4586: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4587: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4588: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4589: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4590: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4591: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4592: 		    $changeflag++;
                   4593: 		    $newpts = '';
1.269     raeburn  4594:                     
                   4595:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4596:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4597:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4598:                     if ($aggtries > 0) {
                   4599:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4600:                         $aggregateflag = 1;
                   4601:                     }
1.71      ng       4602: 		}
1.324     albertel 4603: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4604: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.526     raeburn  4605: 		$displayPts[0].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.71      ng       4606: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4607: 		    '&nbsp;<br />';
1.526     raeburn  4608: 		$displayPts[1].='&nbsp;<b>'.&mt('Part').':</b> '.$display_part.' = '.
1.125     ng       4609: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4610: 		    '&nbsp;<br />';
1.71      ng       4611: 		$question++;
1.380     albertel 4612: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4613: 
1.71      ng       4614: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4615: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4616: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4617: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4618: 
                   4619: 		$changeflag++;
                   4620: 	    }
                   4621: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4622: 		my %record = 
                   4623: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4624: 					     $udom,$uname);
                   4625: 
                   4626: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4627: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4628: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4629: 		    $newrecord{'resource.CODE'} = '';
                   4630: 		}
1.257     albertel 4631: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4632: 					$udom,$uname);
1.382     albertel 4633: 		%record = &Apache::lonnet::restore($symbx,
                   4634: 						   $env{'request.course.id'},
                   4635: 						   $udom,$uname);
1.380     albertel 4636: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4637: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4638: 	    }
1.380     albertel 4639: 	    
1.269     raeburn  4640:             if ($aggregateflag) {
                   4641:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4642:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4643:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4644:             }
1.125     ng       4645: 
1.71      ng       4646: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4647: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4648: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4649: 
1.196     albertel 4650: 	    $prob++;
1.68      ng       4651: 	}
1.71      ng       4652:         $curRes = $iterator->next();
1.68      ng       4653:     }
1.98      albertel 4654: 
1.484     albertel 4655:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4656:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.526     raeburn  4657:     my $grademsg=($changeflag == 0 ? &mt('No score was changed or updated.') :
                   4658: 		  &mt('The scores were changed for [quant,_1,problem].',
                   4659: 		  $changeflag));
1.76      ng       4660:     $request->print($grademsg.$studentTable);
1.68      ng       4661: 
1.70      ng       4662:     return '';
                   4663: }
                   4664: 
1.72      ng       4665: #-------- end of section for handling grading by page/sequence ---------
                   4666: #
                   4667: #-------------------------------------------------------------------
                   4668: 
1.75      albertel 4669: #--------------------Scantron Grading-----------------------------------
                   4670: #
                   4671: #------ start of section for handling grading by page/sequence ---------
                   4672: 
1.423     albertel 4673: =pod
                   4674: 
                   4675: =head1 Bubble sheet grading routines
                   4676: 
1.424     albertel 4677:   For this documentation:
                   4678: 
                   4679:    'scanline' refers to the full line of characters
                   4680:    from the file that we are parsing that represents one entire sheet
                   4681: 
                   4682:    'bubble line' refers to the data
                   4683:    representing the line of bubbles that are on the physical bubble sheet
                   4684: 
                   4685: 
                   4686: The overall process is that a scanned in bubble sheet data is uploaded
                   4687: into a course. When a user wants to grade, they select a
                   4688: sequence/folder of resources, a file of bubble sheet info, and pick
                   4689: one of the predefined configurations for what each scanline looks
                   4690: like.
                   4691: 
                   4692: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4693: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4694: because too light bubbling), 'double bubble' (each bubble line should
                   4695: have no more that one letter picked), invalid or duplicated CODE,
                   4696: invalid student ID
                   4697: 
                   4698: If the CODE option is used that determines the randomization of the
                   4699: homework problems, either way the student ID is looked up into a
                   4700: username:domain.
                   4701: 
                   4702: During the validation phase the instructor can choose to skip scanlines. 
                   4703: 
1.435     foxr     4704: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4705: 
                   4706:   scantron_original_filename (unmodified original file)
                   4707:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4708:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4709: 
                   4710: Also there is a separate hash nohist_scantrondata that contains extra
                   4711: correction information that isn't representable in the bubble sheet
                   4712: file (see &scantron_getfile() for more information)
                   4713: 
                   4714: After all scanlines are either valid, marked as valid or skipped, then
                   4715: foreach line foreach problem in the picked sequence, an ssi request is
                   4716: made that simulates a user submitting their selected letter(s) against
                   4717: the homework problem.
1.423     albertel 4718: 
                   4719: =over 4
                   4720: 
                   4721: 
                   4722: 
                   4723: =item defaultFormData
                   4724: 
                   4725:   Returns html hidden inputs used to hold context/default values.
                   4726: 
                   4727:  Arguments:
                   4728:   $symb - $symb of the current resource 
                   4729: 
                   4730: =cut
1.422     foxr     4731: 
1.81      albertel 4732: sub defaultFormData {
1.324     albertel 4733:     my ($symb)=@_;
1.447     foxr     4734:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4735:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4736:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4737: }
                   4738: 
1.447     foxr     4739: 
1.423     albertel 4740: =pod 
                   4741: 
                   4742: =item getSequenceDropDown
                   4743: 
                   4744:    Return html dropdown of possible sequences to grade
                   4745:  
                   4746:  Arguments:
                   4747:    $symb - $symb of the current resource 
                   4748: 
                   4749: =cut
1.422     foxr     4750: 
1.75      albertel 4751: sub getSequenceDropDown {
1.423     albertel 4752:     my ($symb)=@_;
1.75      albertel 4753:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4754:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4755:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4756:     my $ctr=0;
                   4757:     foreach (@$titles) {
                   4758: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4759: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4760: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4761: 	    '>'.$showtitle.'</option>'."\n";
                   4762: 	$ctr++;
                   4763:     }
                   4764:     $result.= '</select>';
                   4765:     return $result;
                   4766: }
                   4767: 
1.495     albertel 4768: my %bubble_lines_per_response;     # no. bubble lines for each response.
                   4769:                                    # index is "symb.part_id"
                   4770: 
                   4771: my %first_bubble_line;             # First bubble line no. for each bubble.
                   4772: 
1.509     raeburn  4773: my %subdivided_bubble_lines;       # no. bubble lines for optionresponse, 
                   4774:                                    # matchresponse or rankresponse, where 
                   4775:                                    # an individual response can have multiple 
                   4776:                                    # lines
1.503     raeburn  4777: 
                   4778: my %responsetype_per_response;     # responsetype for each response
                   4779: 
1.495     albertel 4780: # Save and restore the bubble lines array to the form env.
                   4781: 
                   4782: 
                   4783: sub save_bubble_lines {
                   4784:     foreach my $line (keys(%bubble_lines_per_response)) {
                   4785: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                   4786: 	$env{"form.scantron.first_bubble_line.$line"} =
                   4787: 	    $first_bubble_line{$line};
1.503     raeburn  4788:         $env{"form.scantron.sub_bubblelines.$line"} = 
                   4789:             $subdivided_bubble_lines{$line};
                   4790:         $env{"form.scantron.responsetype.$line"} =
                   4791:             $responsetype_per_response{$line};
1.495     albertel 4792:     }
                   4793: }
                   4794: 
                   4795: 
                   4796: sub restore_bubble_lines {
                   4797:     my $line = 0;
                   4798:     %bubble_lines_per_response = ();
                   4799:     while ($env{"form.scantron.bubblelines.$line"}) {
                   4800: 	my $value = $env{"form.scantron.bubblelines.$line"};
                   4801: 	$bubble_lines_per_response{$line} = $value;
                   4802: 	$first_bubble_line{$line}  =
                   4803: 	    $env{"form.scantron.first_bubble_line.$line"};
1.503     raeburn  4804:         $subdivided_bubble_lines{$line} =
                   4805:             $env{"form.scantron.sub_bubblelines.$line"};
                   4806:         $responsetype_per_response{$line} =
                   4807:             $env{"form.scantron.responsetype.$line"};
1.495     albertel 4808: 	$line++;
                   4809:     }
                   4810: 
                   4811: }
                   4812: 
                   4813: #  Given the parsed scanline, get the response for 
                   4814: #  'answer' number n:
                   4815: 
                   4816: sub get_response_bubbles {
                   4817:     my ($parsed_line, $response)  = @_;
                   4818: 
                   4819: 
                   4820:     my $bubble_line = $first_bubble_line{$response-1} +1;
                   4821:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                   4822:     
                   4823:     my $selected = "";
                   4824: 
                   4825:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                   4826: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
                   4827: 	$bubble_line++;
                   4828:     }
                   4829:     return $selected;
                   4830: }
1.423     albertel 4831: 
                   4832: =pod 
                   4833: 
                   4834: =item scantron_filenames
                   4835: 
                   4836:    Returns a list of the scantron files in the current course 
                   4837: 
                   4838: =cut
1.422     foxr     4839: 
1.202     albertel 4840: sub scantron_filenames {
1.257     albertel 4841:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4842:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.517     raeburn  4843:     my $getpropath = 1;
1.157     albertel 4844:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.517     raeburn  4845:                                        $getpropath);
1.202     albertel 4846:     my @possiblenames;
1.201     albertel 4847:     foreach my $filename (sort(@files)) {
1.157     albertel 4848: 	($filename)=split(/&/,$filename);
                   4849: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4850: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4851: 	push(@possiblenames,$filename);
                   4852:     }
                   4853:     return @possiblenames;
                   4854: }
                   4855: 
1.423     albertel 4856: =pod 
                   4857: 
                   4858: =item scantron_uploads
                   4859: 
                   4860:    Returns  html drop-down list of scantron files in current course.
                   4861: 
                   4862:  Arguments:
                   4863:    $file2grade - filename to set as selected in the dropdown
                   4864: 
                   4865: =cut
1.422     foxr     4866: 
1.202     albertel 4867: sub scantron_uploads {
1.209     ng       4868:     my ($file2grade) = @_;
1.202     albertel 4869:     my $result=	'<select name="scantron_selectfile">';
                   4870:     $result.="<option></option>";
                   4871:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4872: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4873:     }
                   4874:     $result.="</select>";
                   4875:     return $result;
                   4876: }
                   4877: 
1.423     albertel 4878: =pod 
                   4879: 
                   4880: =item scantron_scantab
                   4881: 
                   4882:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4883:   file.
                   4884: 
                   4885: =cut
1.422     foxr     4886: 
1.82      albertel 4887: sub scantron_scantab {
                   4888:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4889:     $result.='<option></option>'."\n";
1.518     raeburn  4890:     my @lines = &get_scantronformat_file();
                   4891:     if (@lines > 0) {
                   4892:         foreach my $line (@lines) {
                   4893:             next if (($line =~ /^\#/) || ($line eq ''));
                   4894: 	    my ($name,$descrip)=split(/:/,$line);
                   4895: 	    $result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4896:         }
1.82      albertel 4897:     }
                   4898:     $result.='</select>'."\n";
1.518     raeburn  4899:     return $result;
                   4900: }
                   4901: 
                   4902: =pod
                   4903: 
                   4904: =item get_scantronformat_file
                   4905: 
                   4906:   Returns an array containing lines from the scantron format file for
                   4907:   the domain of the course.
                   4908: 
                   4909:   If a url for a custom.tab file is listed in domain's configuration.db, 
                   4910:   lines are from this file.
                   4911: 
                   4912:   Otherwise, if a default.tab has been published in RES space by the 
                   4913:   domainconfig user, lines are from this file.
                   4914: 
                   4915:   Otherwise, fall back to getting lines from the legacy file on the
1.519     raeburn  4916:   local server:  /home/httpd/lonTabs/default_scantronformat.tab    
1.82      albertel 4917: 
1.518     raeburn  4918: =cut
                   4919: 
                   4920: sub get_scantronformat_file {
                   4921:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4922:     my %domconfig = &Apache::lonnet::get_dom('configuration',['scantron'],$cdom);
                   4923:     my $gottab = 0;
                   4924:     my @lines;
                   4925:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4926:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4927:             my $formatfile = &Apache::lonnet::getfile($Apache::lonnet::perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4928:             if ($formatfile ne '-1') {
                   4929:                 @lines = split("\n",$formatfile,-1);
                   4930:                 $gottab = 1;
                   4931:             }
                   4932:         }
                   4933:     }
                   4934:     if (!$gottab) {
                   4935:         my $confname = $cdom.'-domainconfig';
                   4936:         my $default = $Apache::lonnet::perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4937:         my $formatfile =  &Apache::lonnet::getfile($default);
                   4938:         if ($formatfile ne '-1') {
                   4939:             @lines = split("\n",$formatfile,-1);
                   4940:             $gottab = 1;
                   4941:         }
                   4942:     }
                   4943:     if (!$gottab) {
1.519     raeburn  4944:         my @domains = &Apache::lonnet::current_machine_domains();
                   4945:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4946:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4947:             @lines = <$fh>;
                   4948:             close($fh);
                   4949:         } else {
                   4950:             my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/default_scantronformat.tab');
                   4951:             @lines = <$fh>;
                   4952:             close($fh);
                   4953:         }
1.518     raeburn  4954:     }
                   4955:     return @lines;
1.82      albertel 4956: }
                   4957: 
1.423     albertel 4958: =pod 
                   4959: 
                   4960: =item scantron_CODElist
                   4961: 
                   4962:   Returns html drop down of the saved CODE lists from current course,
                   4963:   generated from earlier printings.
                   4964: 
                   4965: =cut
1.422     foxr     4966: 
1.186     albertel 4967: sub scantron_CODElist {
1.257     albertel 4968:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4969:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4970:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4971:     my $namechoice='<option></option>';
1.225     albertel 4972:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4973: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4974: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4975: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4976:     }
                   4977:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4978:     return $namechoice;
                   4979: }
                   4980: 
1.423     albertel 4981: =pod 
                   4982: 
                   4983: =item scantron_CODEunique
                   4984: 
                   4985:   Returns the html for "Each CODE to be used once" radio.
                   4986: 
                   4987: =cut
1.422     foxr     4988: 
1.186     albertel 4989: sub scantron_CODEunique {
1.528.2.1  raeburn  4990:     my $result='<span class="LC_nobreak">
1.272     albertel 4991:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4992:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4993:                 </span>
1.528.2.1  raeburn  4994:                 <span class="LC_nobreak">
1.272     albertel 4995:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4996:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4997:                 </span>';
1.186     albertel 4998:     return $result;
                   4999: }
1.423     albertel 5000: 
                   5001: =pod 
                   5002: 
                   5003: =item scantron_selectphase
                   5004: 
                   5005:   Generates the initial screen to start the bubble sheet process.
                   5006:   Allows for - starting a grading run.
1.424     albertel 5007:              - downloading existing scan data (original, corrected
1.423     albertel 5008:                                                 or skipped info)
                   5009: 
                   5010:              - uploading new scan data
                   5011: 
                   5012:  Arguments:
                   5013:   $r          - The Apache request object
                   5014:   $file2grade - name of the file that contain the scanned data to score
                   5015: 
                   5016: =cut
1.186     albertel 5017: 
1.75      albertel 5018: sub scantron_selectphase {
1.209     ng       5019:     my ($r,$file2grade) = @_;
1.324     albertel 5020:     my ($symb)=&get_symb($r);
1.75      albertel 5021:     if (!$symb) {return '';}
1.423     albertel 5022:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 5023:     my $default_form_data=&defaultFormData($symb);
                   5024:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       5025:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 5026:     my $format_selector=&scantron_scantab();
1.186     albertel 5027:     my $CODE_selector=&scantron_CODElist();
                   5028:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 5029:     my $result;
1.422     foxr     5030: 
1.513     foxr     5031:     $ssi_error = 0;
                   5032: 
1.422     foxr     5033:     # Chunk of form to prompt for a file to grade and how:
                   5034: 
1.489     albertel 5035:     $result.= '
                   5036:     <br />
                   5037:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   5038:     <input type="hidden" name="command" value="scantron_warning" />
                   5039:     '.$default_form_data.'
                   5040:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5041:        '.&Apache::loncommon::start_data_table_header_row().'
                   5042:             <th colspan="2">
1.492     albertel 5043:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 5044:             </th>
                   5045:        '.&Apache::loncommon::end_data_table_header_row().'
                   5046:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5047:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 5048:        '.&Apache::loncommon::end_data_table_row().'
                   5049:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5050:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 5051:        '.&Apache::loncommon::end_data_table_row().'
                   5052:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5053:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 5054:        '.&Apache::loncommon::end_data_table_row().'
                   5055:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5056:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 5057:        '.&Apache::loncommon::end_data_table_row().'
                   5058:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5059:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 5060:        '.&Apache::loncommon::end_data_table_row().'
                   5061:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5062: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 5063:             <td>
1.492     albertel 5064: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   5065:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   5066:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 5067: 	    </td>
1.489     albertel 5068:        '.&Apache::loncommon::end_data_table_row().'
                   5069:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 5070:             <td colspan="2">
1.492     albertel 5071:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 5072:             </td>
1.489     albertel 5073:        '.&Apache::loncommon::end_data_table_row().'
                   5074:     '.&Apache::loncommon::end_data_table().'
                   5075:     </form>
                   5076: ';
1.162     albertel 5077:    
                   5078:     $r->print($result);
                   5079: 
1.257     albertel 5080:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   5081:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5082: 
1.422     foxr     5083: 	# Chunk of form to prompt for a scantron file upload.
                   5084: 
1.489     albertel 5085:         $r->print('
                   5086:     <br />
                   5087:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5088:        '.&Apache::loncommon::start_data_table_header_row().'
                   5089:             <th>
1.492     albertel 5090:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 5091:             </th>
                   5092:        '.&Apache::loncommon::end_data_table_header_row().'
                   5093:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 5094:             <td>
1.489     albertel 5095: ');
1.324     albertel 5096:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5097:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5098:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 5099:     $r->print('
1.174     albertel 5100:               <script type="text/javascript" language="javascript">
                   5101:     function checkUpload(formname) {
                   5102: 	if (formname.upfile.value == "") {
1.492     albertel 5103: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 5104: 	    return false;
                   5105: 	}
                   5106: 	formname.submit();
                   5107:     }
                   5108:               </script>
                   5109: 
1.492     albertel 5110:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   5111:                 '.$default_form_data.'
                   5112:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   5113:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   5114:                 <input name="command" value="scantronupload_save" type="hidden" />
                   5115:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 5116:                 <br />
1.492     albertel 5117:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 5118:               </form>
1.492     albertel 5119: ');
1.162     albertel 5120: 
1.489     albertel 5121:         $r->print('
1.162     albertel 5122:             </td>
1.489     albertel 5123:        '.&Apache::loncommon::end_data_table_row().'
                   5124:        '.&Apache::loncommon::end_data_table().'
                   5125: ');
1.162     albertel 5126:     }
1.422     foxr     5127: 
                   5128:     # Chunk of the form that prompts to view a scoring office file,
                   5129:     # corrected file, skipped records in a file.
                   5130: 
1.489     albertel 5131:     $r->print('
                   5132:    <br />
                   5133:    <form action="/adm/grades" name="scantron_download">
                   5134:      '.$default_form_data.'
                   5135:      <input type="hidden" name="command" value="scantron_download" />
                   5136:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5137:        '.&Apache::loncommon::start_data_table_header_row().'
                   5138:               <th>
1.492     albertel 5139:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5140:               </th>
                   5141:        '.&Apache::loncommon::end_data_table_header_row().'
                   5142:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5143:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5144:                 <br />
1.492     albertel 5145:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5146:        '.&Apache::loncommon::end_data_table_row().'
                   5147:      '.&Apache::loncommon::end_data_table().'
                   5148:    </form>
                   5149:    <br />
                   5150: ');
1.162     albertel 5151: 
1.457     banghart 5152:     &Apache::lonpickcode::code_list($r,2);
1.523     raeburn  5153: 
1.528     raeburn  5154:     $r->print('<br /><form method="post" name="checkscantron">'.
1.523     raeburn  5155:              $default_form_data."\n".
                   5156:              &Apache::loncommon::start_data_table('LC_scantron_action')."\n".
                   5157:              &Apache::loncommon::start_data_table_header_row()."\n".
                   5158:              '<th colspan="2">
                   5159:               &nbsp;'.&mt('Review scantron data and submissions for a previously graded folder/sequence')."\n".
                   5160:              '</th>'."\n".
                   5161:               &Apache::loncommon::end_data_table_header_row()."\n".
                   5162:               &Apache::loncommon::start_data_table_row()."\n".
                   5163:               '<td> '.&mt('Graded folder/sequence:').' </td>'."\n".
                   5164:               '<td> '.$sequence_selector.' </td>'.
                   5165:               &Apache::loncommon::end_data_table_row()."\n".
                   5166:               &Apache::loncommon::start_data_table_row()."\n".
                   5167:               '<td> '.&mt('Filename of scoring office file:').' </td>'."\n".
                   5168:               '<td> '.$file_selector.' </td>'."\n".
                   5169:               &Apache::loncommon::end_data_table_row()."\n".
                   5170:               &Apache::loncommon::start_data_table_row()."\n".
                   5171:               '<td> '.&mt('Format of data file:').' </td>'."\n".
                   5172:               '<td> '.$format_selector.' </td>'."\n".
                   5173:               &Apache::loncommon::end_data_table_row()."\n".
                   5174:               &Apache::loncommon::start_data_table_row()."\n".
                   5175:               '<td colspan="2">'."\n".
                   5176:               '<input type="hidden" name="command" value="checksubmissions" />'."\n".
                   5177:               '<input type="submit" value="'.&mt('Review Scantron Data and Submission Records').'" />'."\n".
                   5178:               '</td>'."\n".
                   5179:               &Apache::loncommon::end_data_table_row()."\n".
                   5180:               &Apache::loncommon::end_data_table()."\n".
                   5181:               '</form><br />');
1.457     banghart 5182:     $r->print($grading_menu_button);
1.523     raeburn  5183:     return;
1.75      albertel 5184: }
                   5185: 
1.423     albertel 5186: =pod
                   5187: 
                   5188: =item get_scantron_config
                   5189: 
                   5190:    Parse and return the scantron configuration line selected as a
                   5191:    hash of configuration file fields.
                   5192: 
                   5193:  Arguments:
                   5194:     which - the name of the configuration to parse from the file.
                   5195: 
                   5196: 
                   5197:  Returns:
                   5198:             If the named configuration is not in the file, an empty
                   5199:             hash is returned.
                   5200:     a hash with the fields
                   5201:       name         - internal name for the this configuration setup
                   5202:       description  - text to display to operator that describes this config
                   5203:       CODElocation - if 0 or the string 'none'
                   5204:                           - no CODE exists for this config
                   5205:                      if -1 || the string 'letter'
                   5206:                           - a CODE exists for this config and is
                   5207:                             a string of letters
                   5208:                      Unsupported value (but planned for future support)
                   5209:                           if a positive integer
                   5210:                                - The CODE exists as the first n items from
                   5211:                                  the question section of the form
                   5212:                           if the string 'number'
                   5213:                                - The CODE exists for this config and is
                   5214:                                  a string of numbers
                   5215:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5216:                      the CODE starts
                   5217:       CODElength  - length of the CODE
                   5218:       IDstart     - column where the student ID number starts
                   5219:       IDlength    - length of the student ID info
                   5220:       Qstart      - column where the information from the bubbled
                   5221:                     'questions' start
                   5222:       Qlength     - number of columns comprising a single bubble line from
                   5223:                     the sheet. (usually either 1 or 10)
1.424     albertel 5224:       Qon         - either a single character representing the character used
1.423     albertel 5225:                     to signal a bubble was chosen in the positional setup, or
                   5226:                     the string 'letter' if the letter of the chosen bubble is
                   5227:                     in the final, or 'number' if a number representing the
                   5228:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5229:       Qoff        - the character used to represent that a bubble was
                   5230:                     left blank
1.423     albertel 5231:       PaperID     - if the scanning process generates a unique number for each
                   5232:                     sheet scanned the column that this ID number starts in
                   5233:       PaperIDlength - number of columns that comprise the unique ID number
                   5234:                       for the sheet of paper
1.424     albertel 5235:       FirstName   - column that the first name starts in
1.423     albertel 5236:       FirstNameLength - number of columns that the first name spans
                   5237:  
                   5238:       LastName    - column that the last name starts in
                   5239:       LastNameLength - number of columns that the last name spans
                   5240: 
                   5241: =cut
1.422     foxr     5242: 
1.82      albertel 5243: sub get_scantron_config {
                   5244:     my ($which) = @_;
1.518     raeburn  5245:     my @lines = &get_scantronformat_file();
1.82      albertel 5246:     my %config;
1.157     albertel 5247:     #FIXME probably should move to XML it has already gotten a bit much now
1.518     raeburn  5248:     foreach my $line (@lines) {
1.82      albertel 5249: 	my ($name,$descrip)=split(/:/,$line);
                   5250: 	if ($name ne $which ) { next; }
                   5251: 	chomp($line);
                   5252: 	my @config=split(/:/,$line);
                   5253: 	$config{'name'}=$config[0];
                   5254: 	$config{'description'}=$config[1];
                   5255: 	$config{'CODElocation'}=$config[2];
                   5256: 	$config{'CODEstart'}=$config[3];
                   5257: 	$config{'CODElength'}=$config[4];
                   5258: 	$config{'IDstart'}=$config[5];
                   5259: 	$config{'IDlength'}=$config[6];
                   5260: 	$config{'Qstart'}=$config[7];
1.497     foxr     5261:  	$config{'Qlength'}=$config[8];
1.82      albertel 5262: 	$config{'Qoff'}=$config[9];
                   5263: 	$config{'Qon'}=$config[10];
1.157     albertel 5264: 	$config{'PaperID'}=$config[11];
                   5265: 	$config{'PaperIDlength'}=$config[12];
                   5266: 	$config{'FirstName'}=$config[13];
                   5267: 	$config{'FirstNamelength'}=$config[14];
                   5268: 	$config{'LastName'}=$config[15];
                   5269: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5270: 	last;
                   5271:     }
                   5272:     return %config;
                   5273: }
                   5274: 
1.423     albertel 5275: =pod 
                   5276: 
                   5277: =item username_to_idmap
                   5278: 
                   5279:     creates a hash keyed by student id with values of the corresponding
                   5280:     student username:domain.
                   5281: 
                   5282:   Arguments:
                   5283: 
                   5284:     $classlist - reference to the class list hash. This is a hash
                   5285:                  keyed by student name:domain  whose elements are references
1.424     albertel 5286:                  to arrays containing various chunks of information
1.423     albertel 5287:                  about the student. (See loncoursedata for more info).
                   5288: 
                   5289:   Returns
                   5290:     %idmap - the constructed hash
                   5291: 
                   5292: =cut
                   5293: 
1.82      albertel 5294: sub username_to_idmap {
                   5295:     my ($classlist)= @_;
                   5296:     my %idmap;
                   5297:     foreach my $student (keys(%$classlist)) {
                   5298: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5299: 	    $student;
                   5300:     }
                   5301:     return %idmap;
                   5302: }
1.423     albertel 5303: 
                   5304: =pod
                   5305: 
1.424     albertel 5306: =item scantron_fixup_scanline
1.423     albertel 5307: 
                   5308:    Process a requested correction to a scanline.
                   5309: 
                   5310:   Arguments:
                   5311:     $scantron_config   - hash from &get_scantron_config()
                   5312:     $scan_data         - hash of correction information 
                   5313:                           (see &scantron_getfile())
                   5314:     $line              - existing scanline
                   5315:     $whichline         - line number of the passed in scanline
                   5316:     $field             - type of change to process 
                   5317:                          (either 
                   5318:                           'ID'     -> correct the student ID number
                   5319:                           'CODE'   -> correct the CODE
                   5320:                           'answer' -> fixup the submitted answers)
                   5321:     
                   5322:    $args               - hash of additional info,
                   5323:                           - 'ID' 
                   5324:                                'newid' -> studentID to use in replacement
1.424     albertel 5325:                                           of existing one
1.423     albertel 5326:                           - 'CODE' 
                   5327:                                'CODE_ignore_dup' - set to true if duplicates
                   5328:                                                    should be ignored.
                   5329: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5330:                                         if the existing unfound code should
1.423     albertel 5331:                                         be used as is
                   5332:                           - 'answer'
                   5333:                                'response' - new answer or 'none' if blank
                   5334:                                'question' - the bubble line to change
1.503     raeburn  5335:                                'questionnum' - the question identifier,
                   5336:                                                may include subquestion. 
1.423     albertel 5337: 
                   5338:   Returns:
                   5339:     $line - the modified scanline
                   5340: 
                   5341:   Side effects: 
                   5342:     $scan_data - may be updated
                   5343: 
                   5344: =cut
                   5345: 
1.82      albertel 5346: 
1.157     albertel 5347: sub scantron_fixup_scanline {
                   5348:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   5349:     if ($field eq 'ID') {
                   5350: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5351: 	    return ($line,1,'New value too large');
1.157     albertel 5352: 	}
                   5353: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5354: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5355: 				     $args->{'newid'});
                   5356: 	}
                   5357: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5358: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5359: 	if ($args->{'newid'}=~/^\s*$/) {
                   5360: 	    &scan_data($scan_data,"$whichline.user",
                   5361: 		       $args->{'username'}.':'.$args->{'domain'});
                   5362: 	}
1.186     albertel 5363:     } elsif ($field eq 'CODE') {
1.192     albertel 5364: 	if ($args->{'CODE_ignore_dup'}) {
                   5365: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5366: 	}
                   5367: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5368: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5369: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5370: 		return ($line,1,'New CODE value too large');
                   5371: 	    }
                   5372: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5373: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5374: 	    }
                   5375: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5376: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5377: 	}
1.157     albertel 5378:     } elsif ($field eq 'answer') {
1.497     foxr     5379: 	my $length=$scantron_config->{'Qlength'};
1.157     albertel 5380: 	my $off=$scantron_config->{'Qoff'};
                   5381: 	my $on=$scantron_config->{'Qon'};
1.497     foxr     5382: 	my $answer=${off}x$length;
                   5383: 	if ($args->{'response'} eq 'none') {
                   5384: 	    &scan_data($scan_data,
1.503     raeburn  5385: 		       "$whichline.no_bubble.".$args->{'questionnum'},'1');
1.497     foxr     5386: 	} else {
                   5387: 	    if ($on eq 'letter') {
                   5388: 		my @alphabet=('A'..'Z');
                   5389: 		$answer=$alphabet[$args->{'response'}];
                   5390: 	    } elsif ($on eq 'number') {
                   5391: 		$answer=$args->{'response'}+1;
                   5392: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5393: 	    } else {
1.497     foxr     5394: 		substr($answer,$args->{'response'},1)=$on;
1.274     albertel 5395: 	    }
1.497     foxr     5396: 	    &scan_data($scan_data,
1.503     raeburn  5397: 		       "$whichline.no_bubble.".$args->{'questionnum'},undef,'1');
1.157     albertel 5398: 	}
1.497     foxr     5399: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5400: 	substr($line,$where-1,$length)=$answer;
1.157     albertel 5401:     }
                   5402:     return $line;
                   5403: }
1.423     albertel 5404: 
                   5405: =pod
                   5406: 
                   5407: =item scan_data
                   5408: 
                   5409:     Edit or look up  an item in the scan_data hash.
                   5410: 
                   5411:   Arguments:
                   5412:     $scan_data  - The hash (see scantron_getfile)
                   5413:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5414:                   scantronfilename_key).
1.423     albertel 5415:     $data        - New value of the hash entry.
                   5416:     $delete      - If true, the entry is removed from the hash.
                   5417: 
                   5418:   Returns:
                   5419:     The new value of the hash table field (undefined if deleted).
                   5420: 
                   5421: =cut
                   5422: 
                   5423: 
1.157     albertel 5424: sub scan_data {
                   5425:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5426:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5427:     if (defined($value)) {
                   5428: 	$scan_data->{$filename.'_'.$key} = $value;
                   5429:     }
                   5430:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5431:     return $scan_data->{$filename.'_'.$key};
                   5432: }
1.423     albertel 5433: 
1.495     albertel 5434: # ----- These first few routines are general use routines.----
                   5435: 
                   5436: # Return the number of occurences of a pattern in a string.
                   5437: 
                   5438: sub occurence_count {
                   5439:     my ($string, $pattern) = @_;
                   5440: 
                   5441:     my @matches = ($string =~ /$pattern/g);
                   5442: 
                   5443:     return scalar(@matches);
                   5444: }
                   5445: 
                   5446: 
                   5447: # Take a string known to have digits and convert all the
                   5448: # digits into letters in the range J,A..I.
                   5449: 
                   5450: sub digits_to_letters {
                   5451:     my ($input) = @_;
                   5452: 
                   5453:     my @alphabet = ('J', 'A'..'I');
                   5454: 
                   5455:     my @input    = split(//, $input);
                   5456:     my $output ='';
                   5457:     for (my $i = 0; $i < scalar(@input); $i++) {
                   5458: 	if ($input[$i] =~ /\d/) {
                   5459: 	    $output .= $alphabet[$input[$i]];
                   5460: 	} else {
                   5461: 	    $output .= $input[$i];
                   5462: 	}
                   5463:     }
                   5464:     return $output;
                   5465: }
                   5466: 
1.423     albertel 5467: =pod 
                   5468: 
                   5469: =item scantron_parse_scanline
                   5470: 
                   5471:   Decodes a scanline from the selected scantron file
                   5472: 
                   5473:  Arguments:
                   5474:     line             - The text of the scantron file line to process
                   5475:     whichline        - Line number
                   5476:     scantron_config  - Hash describing the format of the scantron lines.
                   5477:     scan_data        - Hash of extra information about the scanline
                   5478:                        (see scantron_getfile for more information)
                   5479:     just_header      - True if should not process question answers but only
                   5480:                        the stuff to the left of the answers.
                   5481:  Returns:
                   5482:    Hash containing the result of parsing the scanline
                   5483: 
                   5484:    Keys are all proceeded by the string 'scantron.'
                   5485: 
                   5486:        CODE    - the CODE in use for this scanline
                   5487:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5488:                  by the operator
                   5489:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5490:                             CODEs were selected, but the usage has been
                   5491:                             forced by the operator
                   5492:        ID  - student ID
                   5493:        PaperID - if used, the ID number printed on the sheet when the 
                   5494:                  paper was scanned
                   5495:        FirstName - first name from the sheet
                   5496:        LastName  - last name from the sheet
                   5497: 
                   5498:      if just_header was not true these key may also exist
                   5499: 
1.447     foxr     5500:        missingerror - a list of bubble ranges that are considered to be answers
                   5501:                       to a single question that don't have any bubbles filled in.
                   5502:                       Of the form questionnumber:firstbubblenumber:count.
                   5503:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5504:                       to a single question that have more than one bubble filled in.
                   5505:                       Of the form questionnumber::firstbubblenumber:count
                   5506:    
                   5507:                 In the above, count is the number of bubble responses in the
                   5508:                 input line needed to represent the possible answers to the question.
                   5509:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5510:                 per line would have count = 2.
                   5511: 
1.423     albertel 5512:        maxquest     - the number of the last bubble line that was parsed
                   5513: 
                   5514:        (<number> starts at 1)
                   5515:        <number>.answer - zero or more letters representing the selected
                   5516:                          letters from the scanline for the bubble line 
                   5517:                          <number>.
                   5518:                          if blank there was either no bubble or there where
                   5519:                          multiple bubbles, (consult the keys missingerror and
                   5520:                          doubleerror if this is an error condition)
                   5521: 
                   5522: =cut
                   5523: 
1.82      albertel 5524: sub scantron_parse_scanline {
1.423     albertel 5525:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5526: 
1.82      albertel 5527:     my %record;
1.422     foxr     5528:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5529:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5530:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5531: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5532: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5533: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5534: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5535: 	    $record{'scantron.CODE'}=substr($data,
                   5536: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5537: 					    $$scantron_config{'CODElength'});
1.191     albertel 5538: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5539: 		$record{'scantron.useCODE'}=1;
                   5540: 	    }
1.192     albertel 5541: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5542: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5543: 	    }
1.82      albertel 5544: 	} else {
                   5545: 	    #FIXME interpret first N questions
                   5546: 	}
                   5547:     }
1.83      albertel 5548:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5549: 				  $$scantron_config{'IDlength'});
1.157     albertel 5550:     $record{'scantron.PaperID'}=
                   5551: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5552: 	       $$scantron_config{'PaperIDlength'});
                   5553:     $record{'scantron.FirstName'}=
                   5554: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5555: 	       $$scantron_config{'FirstNamelength'});
                   5556:     $record{'scantron.LastName'}=
                   5557: 	substr($data,$$scantron_config{'LastName'}-1,
                   5558: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5559:     if ($just_header) { return \%record; }
1.194     albertel 5560: 
1.82      albertel 5561:     my @alphabet=('A'..'Z');
                   5562:     my $questnum=0;
1.447     foxr     5563:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5564: 
1.470     foxr     5565:     chomp($questions);		# Get rid of any trailing \n.
                   5566:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5567:     while (length($questions)) {
1.447     foxr     5568: 	my $answers_needed = $bubble_lines_per_response{$questnum};
1.503     raeburn  5569:         my $answer_length  = ($$scantron_config{'Qlength'} * $answers_needed)
                   5570:                              || 1;
                   5571:         $questnum++;
                   5572:         my $quest_id = $questnum;
                   5573:         my $currentquest = substr($questions,0,$answer_length);
                   5574:         $questions       = substr($questions,$answer_length);
                   5575:         if (length($currentquest) < $answer_length) { next; }
                   5576: 
                   5577:         if ($subdivided_bubble_lines{$questnum-1} =~ /,/) {
                   5578:             my $subquestnum = 1;
                   5579:             my $subquestions = $currentquest;
                   5580:             my @subanswers_needed = 
                   5581:                 split(/,/,$subdivided_bubble_lines{$questnum-1});  
                   5582:             foreach my $subans (@subanswers_needed) {
                   5583:                 my $subans_length =
                   5584:                     ($$scantron_config{'Qlength'} * $subans)  || 1;
                   5585:                 my $currsubquest = substr($subquestions,0,$subans_length);
                   5586:                 $subquestions   = substr($subquestions,$subans_length);
                   5587:                 $quest_id = "$questnum.$subquestnum";
                   5588:                 if (($$scantron_config{'Qon'} eq 'letter') ||
                   5589:                     ($$scantron_config{'Qon'} eq 'number')) {
                   5590:                     $ansnum = &scantron_validator_lettnum($ansnum, 
                   5591:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,
                   5592:                         \@alphabet,\%record,$scantron_config,$scan_data);
                   5593:                 } else {
                   5594:                     $ansnum = &scantron_validator_positional($ansnum,
                   5595:                         $questnum,$quest_id,$subans,$currsubquest,$whichline,                        \@alphabet,\%record,$scantron_config,$scan_data);
                   5596:                 }
                   5597:                 $subquestnum ++;
                   5598:             }
                   5599:         } else {
                   5600:             if (($$scantron_config{'Qon'} eq 'letter') ||
                   5601:                 ($$scantron_config{'Qon'} eq 'number')) {
                   5602:                 $ansnum = &scantron_validator_lettnum($ansnum,$questnum,
                   5603:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5604:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5605:             } else {
                   5606:                 $ansnum = &scantron_validator_positional($ansnum,$questnum,
                   5607:                     $quest_id,$answers_needed,$currentquest,$whichline,
                   5608:                     \@alphabet,\%record,$scantron_config,$scan_data);
                   5609:             }
                   5610:         }
                   5611:     }
                   5612:     $record{'scantron.maxquest'}=$questnum;
                   5613:     return \%record;
                   5614: }
1.447     foxr     5615: 
1.503     raeburn  5616: sub scantron_validator_lettnum {
                   5617:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,$whichline,
                   5618:         $alphabet,$record,$scantron_config,$scan_data) = @_;
                   5619: 
                   5620:     # Qon 'letter' implies for each slot in currquest we have:
                   5621:     #    ? or * for doubles, a letter in A-Z for a bubble, and
                   5622:     #    about anything else (esp. a value of Qoff) for missing
                   5623:     #    bubbles.
                   5624:     #
                   5625:     # Qon 'number' implies each slot gives a digit that indexes the
                   5626:     #    bubbles filled, or Qoff, or a non-number for unbubbled lines,
                   5627:     #    and * or ? for double bubbles on a single line.
                   5628:     #
1.447     foxr     5629: 
1.503     raeburn  5630:     my $matchon;
                   5631:     if ($$scantron_config{'Qon'} eq 'letter') {
                   5632:         $matchon = '[A-Z]';
                   5633:     } elsif ($$scantron_config{'Qon'} eq 'number') {
                   5634:         $matchon = '\d';
                   5635:     }
                   5636:     my $occurrences = 0;
                   5637:     if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5638:         ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5639:         ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5640:         ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5641:         ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5642:         ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5643:         my @singlelines = split('',$currquest);
                   5644:         foreach my $entry (@singlelines) {
                   5645:             $occurrences = &occurence_count($entry,$matchon);
                   5646:             if ($occurrences > 1) {
                   5647:                 last;
                   5648:             }
                   5649:         } 
                   5650:     } else {
                   5651:         $occurrences = &occurence_count($currquest,$matchon); 
                   5652:     }
                   5653:     if (($currquest =~ /\?/ || $currquest =~ /\*/) || ($occurrences > 1)) {
                   5654:         push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5655:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5656:             my $bubble = substr($currquest,$ans,1);
                   5657:             if ($bubble =~ /$matchon/ ) {
                   5658:                 if ($$scantron_config{'Qon'} eq 'number') {
                   5659:                     if ($bubble == 0) {
                   5660:                         $bubble = 10; 
                   5661:                     }
                   5662:                     $record->{"scantron.$ansnum.answer"} = 
                   5663:                         $alphabet->[$bubble-1];
                   5664:                 } else {
                   5665:                     $record->{"scantron.$ansnum.answer"} = $bubble;
                   5666:                 }
                   5667:             } else {
                   5668:                 $record->{"scantron.$ansnum.answer"}='';
                   5669:             }
                   5670:             $ansnum++;
                   5671:         }
                   5672:     } elsif (!defined($currquest)
                   5673:             || (&occurence_count($currquest, $$scantron_config{'Qoff'}) == length($currquest))
                   5674:             || (&occurence_count($currquest,$matchon) == 0)) {
                   5675:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5676:             $record->{"scantron.$ansnum.answer"}='';
                   5677:             $ansnum++;
                   5678:         }
                   5679:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5680:             push(@{$record->{'scantron.missingerror'}},$quest_id);
                   5681:         }
                   5682:     } else {
                   5683:         if ($$scantron_config{'Qon'} eq 'number') {
                   5684:             $currquest = &digits_to_letters($currquest);            
                   5685:         }
                   5686:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5687:             my $bubble = substr($currquest,$ans,1);
                   5688:             $record->{"scantron.$ansnum.answer"} = $bubble;
                   5689:             $ansnum++;
                   5690:         }
                   5691:     }
                   5692:     return $ansnum;
                   5693: }
1.447     foxr     5694: 
1.503     raeburn  5695: sub scantron_validator_positional {
                   5696:     my ($ansnum,$questnum,$quest_id,$answers_needed,$currquest,
                   5697:         $whichline,$alphabet,$record,$scantron_config,$scan_data) = @_;
1.447     foxr     5698: 
1.503     raeburn  5699:     # Otherwise there's a positional notation;
                   5700:     # each bubble line requires Qlength items, and there are filled in
                   5701:     # bubbles for each case where there 'Qon' characters.
                   5702:     #
1.447     foxr     5703: 
1.503     raeburn  5704:     my @array=split($$scantron_config{'Qon'},$currquest,-1);
1.447     foxr     5705: 
1.503     raeburn  5706:     # If the split only gives us one element.. the full length of the
                   5707:     # answer string, no bubbles are filled in:
1.447     foxr     5708: 
1.507     raeburn  5709:     if ($answers_needed eq '') {
                   5710:         return;
                   5711:     }
                   5712: 
1.503     raeburn  5713:     if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5714:         for (my $ans=0; $ans<$answers_needed; $ans++ ) {
                   5715:             $record->{"scantron.$ansnum.answer"}='';
                   5716:             $ansnum++;
                   5717:         }
                   5718:         if (!&scan_data($scan_data,"$whichline.no_bubble.$quest_id")) {
                   5719:             push(@{$record->{"scantron.missingerror"}},$quest_id);
                   5720:         }
                   5721:     } elsif (scalar(@array) == 2) {
                   5722:         my $location = length($array[0]);
                   5723:         my $line_num = int($location / $$scantron_config{'Qlength'});
                   5724:         my $bubble   = $alphabet->[$location % $$scantron_config{'Qlength'}];
                   5725:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5726:             if ($ans eq $line_num) {
                   5727:                 $record->{"scantron.$ansnum.answer"} = $bubble;
                   5728:             } else {
                   5729:                 $record->{"scantron.$ansnum.answer"} = ' ';
                   5730:             }
                   5731:             $ansnum++;
                   5732:          }
                   5733:     } else {
                   5734:         #  If there's more than one instance of a bubble character
                   5735:         #  That's a double bubble; with positional notation we can
                   5736:         #  record all the bubbles filled in as well as the
                   5737:         #  fact this response consists of multiple bubbles.
                   5738:         #
                   5739:         if (($responsetype_per_response{$questnum-1} eq 'essayresponse') ||
                   5740:             ($responsetype_per_response{$questnum-1} eq 'formularesponse') ||
1.510     raeburn  5741:             ($responsetype_per_response{$questnum-1} eq 'stringresponse') ||
                   5742:             ($responsetype_per_response{$questnum-1} eq 'imageresponse') ||
                   5743:             ($responsetype_per_response{$questnum-1} eq 'reactionresponse') ||
                   5744:             ($responsetype_per_response{$questnum-1} eq 'organicresponse')) {
1.503     raeburn  5745:             my $doubleerror = 0;
                   5746:             while (($currquest >= $$scantron_config{'Qlength'}) && 
                   5747:                    (!$doubleerror)) {
                   5748:                my $currline = substr($currquest,0,$$scantron_config{'Qlength'});
                   5749:                $currquest = substr($currquest,$$scantron_config{'Qlength'});
                   5750:                my @currarray = split($$scantron_config{'Qon'},$currline,-1);
                   5751:                if (length(@currarray) > 2) {
                   5752:                    $doubleerror = 1;
                   5753:                } 
                   5754:             }
                   5755:             if ($doubleerror) {
                   5756:                 push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5757:             }
                   5758:         } else {
                   5759:             push(@{$record->{'scantron.doubleerror'}},$quest_id);
                   5760:         }
                   5761:         my $item = $ansnum;
                   5762:         for (my $ans=0; $ans<$answers_needed; $ans++) {
                   5763:             $record->{"scantron.$item.answer"} = '';
                   5764:             $item ++;
                   5765:         }
1.447     foxr     5766: 
1.503     raeburn  5767:         my @ans=@array;
                   5768:         my $i=0;
                   5769:         my $increment = 0;
                   5770:         while ($#ans) {
                   5771:             $i+=length($ans[0]) + $increment;
                   5772:             my $line   = int($i/$$scantron_config{'Qlength'} + $ansnum);
                   5773:             my $bubble = $i%$$scantron_config{'Qlength'};
                   5774:             $record->{"scantron.$line.answer"}.=$alphabet->[$bubble];
                   5775:             shift(@ans);
                   5776:             $increment = 1;
                   5777:         }
                   5778:         $ansnum += $answers_needed;
1.82      albertel 5779:     }
1.503     raeburn  5780:     return $ansnum;
1.82      albertel 5781: }
                   5782: 
1.423     albertel 5783: =pod
                   5784: 
                   5785: =item scantron_add_delay
                   5786: 
                   5787:    Adds an error message that occurred during the grading phase to a
                   5788:    queue of messages to be shown after grading pass is complete
                   5789: 
                   5790:  Arguments:
1.424     albertel 5791:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5792:    $scanline    - the scanline that caused the error
                   5793:    $errormesage - the error message
                   5794:    $errorcode   - a numeric code for the error
                   5795: 
                   5796:  Side Effects:
1.424     albertel 5797:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5798: 
                   5799: =cut
                   5800: 
1.82      albertel 5801: sub scantron_add_delay {
1.140     albertel 5802:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5803:     push(@$delayqueue,
                   5804: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5805: 	  'ecode' => $errorcode }
                   5806: 	 );
1.82      albertel 5807: }
                   5808: 
1.423     albertel 5809: =pod
                   5810: 
                   5811: =item scantron_find_student
                   5812: 
1.424     albertel 5813:    Finds the username for the current scanline
                   5814: 
                   5815:   Arguments:
                   5816:    $scantron_record - hash result from scantron_parse_scanline
                   5817:    $scan_data       - hash of correction information 
                   5818:                       (see &scantron_getfile() form more information)
                   5819:    $idmap           - hash from &username_to_idmap()
                   5820:    $line            - number of current scanline
                   5821:  
                   5822:   Returns:
                   5823:    Either 'username:domain' or undef if unknown
                   5824: 
1.423     albertel 5825: =cut
                   5826: 
1.82      albertel 5827: sub scantron_find_student {
1.157     albertel 5828:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5829:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5830:     if ($scanID =~ /^\s*$/) {
                   5831:  	return &scan_data($scan_data,"$line.user");
                   5832:     }
1.83      albertel 5833:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5834:  	if (lc($id) eq lc($scanID)) {
                   5835:  	    return $$idmap{$id};
                   5836:  	}
1.83      albertel 5837:     }
                   5838:     return undef;
                   5839: }
                   5840: 
1.423     albertel 5841: =pod
                   5842: 
                   5843: =item scantron_filter
                   5844: 
1.424     albertel 5845:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5846:    hidden resources was selected
                   5847: 
1.423     albertel 5848: =cut
                   5849: 
1.83      albertel 5850: sub scantron_filter {
                   5851:     my ($curres)=@_;
1.331     albertel 5852: 
                   5853:     if (ref($curres) && $curres->is_problem()) {
                   5854: 	# if the user has asked to not have either hidden
                   5855: 	# or 'randomout' controlled resources to be graded
                   5856: 	# don't include them
                   5857: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5858: 	    && $curres->randomout) {
                   5859: 	    return 0;
                   5860: 	}
1.83      albertel 5861: 	return 1;
                   5862:     }
                   5863:     return 0;
1.82      albertel 5864: }
                   5865: 
1.423     albertel 5866: =pod
                   5867: 
                   5868: =item scantron_process_corrections
                   5869: 
1.424     albertel 5870:    Gets correction information out of submitted form data and corrects
                   5871:    the scanline
                   5872: 
1.423     albertel 5873: =cut
                   5874: 
1.157     albertel 5875: sub scantron_process_corrections {
                   5876:     my ($r) = @_;
1.257     albertel 5877:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5878:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5879:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5880:     my $which=$env{'form.scantron_line'};
1.200     albertel 5881:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5882:     my ($skip,$err,$errmsg);
1.257     albertel 5883:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5884: 	$skip=1;
1.257     albertel 5885:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5886: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5887: 	    $env{'form.scantron_domain'};
1.157     albertel 5888: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5889: 	($line,$err,$errmsg)=
                   5890: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5891: 				     'ID',{'newid'=>$newid,
1.257     albertel 5892: 				    'username'=>$env{'form.scantron_username'},
                   5893: 				    'domain'=>$env{'form.scantron_domain'}});
                   5894:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5895: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5896: 	my $newCODE;
1.192     albertel 5897: 	my %args;
1.190     albertel 5898: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5899: 	    $newCODE='use_unfound';
1.190     albertel 5900: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5901: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5902: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5903: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5904: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5905: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5906: 	}
1.257     albertel 5907: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5908: 	    $args{'CODE_ignore_dup'}=1;
                   5909: 	}
                   5910: 	$args{'CODE'}=$newCODE;
1.186     albertel 5911: 	($line,$err,$errmsg)=
                   5912: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5913: 				     'CODE',\%args);
1.257     albertel 5914:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5915: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5916: 	    ($line,$err,$errmsg)=
                   5917: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5918: 					 $which,'answer',
                   5919: 					 { 'question'=>$question,
1.503     raeburn  5920: 		      		   'response'=>$env{"form.scantron_correct_Q_$question"},
                   5921:                                    'questionnum'=>$env{"form.scantron_questionnum_Q_$question"}});
1.157     albertel 5922: 	    if ($err) { last; }
                   5923: 	}
                   5924:     }
                   5925:     if ($err) {
1.398     albertel 5926: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5927:     } else {
1.200     albertel 5928: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5929: 	&scantron_putfile($scanlines,$scan_data);
                   5930:     }
                   5931: }
                   5932: 
1.423     albertel 5933: =pod
                   5934: 
                   5935: =item reset_skipping_status
                   5936: 
1.424     albertel 5937:    Forgets the current set of remember skipped scanlines (and thus
                   5938:    reverts back to considering all lines in the
                   5939:    scantron_skipped_<filename> file)
                   5940: 
1.423     albertel 5941: =cut
                   5942: 
1.200     albertel 5943: sub reset_skipping_status {
                   5944:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5945:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5946:     &scantron_putfile(undef,$scan_data);
                   5947: }
                   5948: 
1.423     albertel 5949: =pod
                   5950: 
                   5951: =item start_skipping
                   5952: 
1.424     albertel 5953:    Marks a scanline to be skipped. 
                   5954: 
1.423     albertel 5955: =cut
                   5956: 
1.376     albertel 5957: sub start_skipping {
1.200     albertel 5958:     my ($scan_data,$i)=@_;
                   5959:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5960:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5961: 	$remembered{$i}=2;
                   5962:     } else {
                   5963: 	$remembered{$i}=1;
                   5964:     }
1.200     albertel 5965:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5966: }
                   5967: 
1.423     albertel 5968: =pod
                   5969: 
                   5970: =item should_be_skipped
                   5971: 
1.424     albertel 5972:    Checks whether a scanline should be skipped.
                   5973: 
1.423     albertel 5974: =cut
                   5975: 
1.200     albertel 5976: sub should_be_skipped {
1.376     albertel 5977:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5978:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5979: 	# not redoing old skips
1.376     albertel 5980: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5981: 	return 0;
                   5982:     }
                   5983:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5984: 
                   5985:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5986: 	return 0;
                   5987:     }
1.200     albertel 5988:     return 1;
                   5989: }
                   5990: 
1.423     albertel 5991: =pod
                   5992: 
                   5993: =item remember_current_skipped
                   5994: 
1.424     albertel 5995:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5996:    file and remembers them into scan_data for later use.
                   5997: 
1.423     albertel 5998: =cut
                   5999: 
1.200     albertel 6000: sub remember_current_skipped {
                   6001:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6002:     my %to_remember;
                   6003:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6004: 	if ($scanlines->{'skipped'}[$i]) {
                   6005: 	    $to_remember{$i}=1;
                   6006: 	}
                   6007:     }
1.376     albertel 6008: 
1.200     albertel 6009:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   6010:     &scantron_putfile(undef,$scan_data);
                   6011: }
                   6012: 
1.423     albertel 6013: =pod
                   6014: 
                   6015: =item check_for_error
                   6016: 
1.424     albertel 6017:     Checks if there was an error when attempting to remove a specific
                   6018:     scantron_.. bubble sheet data file. Prints out an error if
                   6019:     something went wrong.
                   6020: 
1.423     albertel 6021: =cut
                   6022: 
1.200     albertel 6023: sub check_for_error {
                   6024:     my ($r,$result)=@_;
                   6025:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 6026: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 6027:     }
                   6028: }
1.157     albertel 6029: 
1.423     albertel 6030: =pod
                   6031: 
                   6032: =item scantron_warning_screen
                   6033: 
1.424     albertel 6034:    Interstitial screen to make sure the operator has selected the
                   6035:    correct options before we start the validation phase.
                   6036: 
1.423     albertel 6037: =cut
                   6038: 
1.203     albertel 6039: sub scantron_warning_screen {
                   6040:     my ($button_text)=@_;
1.257     albertel 6041:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 6042:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 6043:     my $CODElist;
1.284     albertel 6044:     if ($scantron_config{'CODElocation'} &&
                   6045: 	$scantron_config{'CODEstart'} &&
                   6046: 	$scantron_config{'CODElength'}) {
                   6047: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 6048: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 6049: 	$CODElist=
1.492     albertel 6050: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 6051: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 6052:     }
1.492     albertel 6053:     return ('
1.203     albertel 6054: <p>
1.492     albertel 6055: <span class="LC_warning">
                   6056: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 6057: </p>
                   6058: <table>
1.492     albertel 6059: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   6060: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   6061: '.$CODElist.'
1.203     albertel 6062: </table>
                   6063: <br />
1.492     albertel 6064: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   6065: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 6066: 
                   6067: <br />
1.492     albertel 6068: ');
1.203     albertel 6069: }
                   6070: 
1.423     albertel 6071: =pod
                   6072: 
                   6073: =item scantron_do_warning
                   6074: 
1.424     albertel 6075:    Check if the operator has picked something for all required
                   6076:    fields. Error out if something is missing.
                   6077: 
1.423     albertel 6078: =cut
                   6079: 
1.203     albertel 6080: sub scantron_do_warning {
                   6081:     my ($r)=@_;
1.324     albertel 6082:     my ($symb)=&get_symb($r);
1.203     albertel 6083:     if (!$symb) {return '';}
1.324     albertel 6084:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 6085:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 6086:     if ( $env{'form.selectpage'} eq '' ||
                   6087: 	 $env{'form.scantron_selectfile'} eq '' ||
                   6088: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 6089: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 6090: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 6091: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 6092: 	} 
1.257     albertel 6093: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 6094: 	    $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 6095: 	} 
1.257     albertel 6096: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 6097: 	    $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 6098: 	} 
                   6099:     } else {
1.265     www      6100: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 6101: 	$r->print('
                   6102: '.$warning.'
                   6103: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 6104: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 6105: ');
1.237     albertel 6106:     }
1.352     albertel 6107:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 6108:     return '';
                   6109: }
                   6110: 
1.423     albertel 6111: =pod
                   6112: 
                   6113: =item scantron_form_start
                   6114: 
1.424     albertel 6115:     html hidden input for remembering all selected grading options
                   6116: 
1.423     albertel 6117: =cut
                   6118: 
1.203     albertel 6119: sub scantron_form_start {
                   6120:     my ($max_bubble)=@_;
                   6121:     my $result= <<SCANTRONFORM;
                   6122: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 6123:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   6124:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   6125:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 6126:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 6127:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   6128:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   6129:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   6130:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 6131:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 6132: SCANTRONFORM
1.447     foxr     6133: 
                   6134:   my $line = 0;
                   6135:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   6136:        my $chunk =
                   6137: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     6138:        $chunk .=
                   6139: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.503     raeburn  6140:        $chunk .= 
                   6141:            '<input type="hidden" name="scantron.sub_bubblelines.'.$line.'" value="'.$env{"form.scantron.sub_bubblelines.$line"}.'" />'."\n";
1.504     raeburn  6142:        $chunk .=
                   6143:            '<input type="hidden" name="scantron.responsetype.'.$line.'" value="'.$env{"form.scantron.responsetype.$line"}.'" />'."\n";
1.447     foxr     6144:        $result .= $chunk;
                   6145:        $line++;
                   6146:    }
1.203     albertel 6147:     return $result;
                   6148: }
                   6149: 
1.423     albertel 6150: =pod
                   6151: 
                   6152: =item scantron_validate_file
                   6153: 
1.424     albertel 6154:     Dispatch routine for doing validation of a bubble sheet data file.
                   6155: 
                   6156:     Also processes any necessary information resets that need to
                   6157:     occur before validation begins (ignore previous corrections,
                   6158:     restarting the skipped records processing)
                   6159: 
1.423     albertel 6160: =cut
                   6161: 
1.157     albertel 6162: sub scantron_validate_file {
                   6163:     my ($r) = @_;
1.324     albertel 6164:     my ($symb)=&get_symb($r);
1.157     albertel 6165:     if (!$symb) {return '';}
1.324     albertel 6166:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 6167:     
                   6168:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 6169:     # them when doing the corrections reset
1.257     albertel 6170:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 6171: 	&reset_skipping_status();
                   6172:     }
1.257     albertel 6173:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 6174: 	&remember_current_skipped();
1.257     albertel 6175: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 6176:     }
                   6177: 
1.257     albertel 6178:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 6179: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   6180: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   6181: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 6182: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 6183:     }
1.200     albertel 6184: 
1.257     albertel 6185:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 6186: 	&scantron_process_corrections($r);
                   6187:     }
1.503     raeburn  6188:     $r->print('<p>'.&mt('Gathering necessary information.').'</p>');$r->rflush();
1.157     albertel 6189:     #get the student pick code ready
                   6190:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 6191:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 6192:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 6193:     $r->print($result);
                   6194:     
1.334     albertel 6195:     my @validate_phases=( 'sequence',
                   6196: 			  'ID',
1.157     albertel 6197: 			  'CODE',
                   6198: 			  'doublebubble',
                   6199: 			  'missingbubbles');
1.257     albertel 6200:     if (!$env{'form.validatepass'}) {
                   6201: 	$env{'form.validatepass'} = 0;
1.157     albertel 6202:     }
1.257     albertel 6203:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 6204: 
1.448     foxr     6205: 
1.157     albertel 6206:     my $stop=0;
                   6207:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.503     raeburn  6208: 	$r->print(&mt('Validating '.$validate_phases[$currentphase]).'<br />');
1.157     albertel 6209: 	$r->rflush();
                   6210: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6211: 	{
                   6212: 	    no strict 'refs';
                   6213: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6214: 	}
                   6215:     }
                   6216:     if (!$stop) {
1.203     albertel 6217: 	my $warning=&scantron_warning_screen('Start Grading');
1.512     www      6218: 	$r->print(&mt('Validation process complete.').'<br />
1.492     albertel 6219: '.$warning.'
                   6220: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6221: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6222: ');
1.203     albertel 6223: 
1.157     albertel 6224:     } else {
                   6225: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6226: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6227:     }
                   6228:     if ($stop) {
1.334     albertel 6229: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6230: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6231: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6232: 
1.492     albertel 6233: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6234: 	} else {
1.503     raeburn  6235:             if ($validate_phases[$currentphase] eq 'doublebubble' || $validate_phases[$currentphase] eq 'missingbubbles') {
                   6236: 	        $r->print('<input type="button" name="submitbutton" value="'.&mt('Continue -&gt;').'" onclick="javascript:verify_bubble_radio(this.form)" />');
                   6237:             } else {
                   6238:                 $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6239:             }
1.492     albertel 6240: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6241: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6242: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6243: 	}
1.157     albertel 6244:     }
1.352     albertel 6245:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6246:     return '';
                   6247: }
                   6248: 
1.423     albertel 6249: 
                   6250: =pod
                   6251: 
                   6252: =item scantron_remove_file
                   6253: 
1.424     albertel 6254:    Removes the requested bubble sheet data file, makes sure that
                   6255:    scantron_original_<filename> is never removed
                   6256: 
                   6257: 
1.423     albertel 6258: =cut
                   6259: 
1.200     albertel 6260: sub scantron_remove_file {
1.192     albertel 6261:     my ($which)=@_;
1.257     albertel 6262:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6263:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6264:     my $file='scantron_';
1.200     albertel 6265:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6266: 	$file.=$which.'_';
1.192     albertel 6267:     } else {
                   6268: 	return 'refused';
                   6269:     }
1.257     albertel 6270:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6271:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6272: }
                   6273: 
1.423     albertel 6274: 
                   6275: =pod
                   6276: 
                   6277: =item scantron_remove_scan_data
                   6278: 
1.424     albertel 6279:    Removes all scan_data correction for the requested bubble sheet
                   6280:    data file.  (In the case that both the are doing skipped records we need
                   6281:    to remember the old skipped lines for the time being so that element
                   6282:    persists for a while.)
                   6283: 
1.423     albertel 6284: =cut
                   6285: 
1.200     albertel 6286: sub scantron_remove_scan_data {
1.257     albertel 6287:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6288:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6289:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6290:     my @todelete;
1.257     albertel 6291:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6292:     foreach my $key (@keys) {
                   6293: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6294: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6295: 		$key=~/remember_skipping/) {
                   6296: 		next;
                   6297: 	    }
1.192     albertel 6298: 	    push(@todelete,$key);
                   6299: 	}
                   6300:     }
1.200     albertel 6301:     my $result;
1.192     albertel 6302:     if (@todelete) {
1.491     albertel 6303: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6304: 				       \@todelete,$cdom,$cname);
                   6305:     } else {
                   6306: 	$result = 'ok';
1.192     albertel 6307:     }
                   6308:     return $result;
                   6309: }
                   6310: 
1.423     albertel 6311: 
                   6312: =pod
                   6313: 
                   6314: =item scantron_getfile
                   6315: 
1.424     albertel 6316:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6317:     the scan_data hash
                   6318:   
                   6319:   Arguments:
                   6320:     None
                   6321: 
                   6322:   Returns:
                   6323:     2 hash references
                   6324: 
                   6325:      - first one has 
                   6326:          orig      -
                   6327:          corrected -
                   6328:          skipped   -  each of which points to an array ref of the specified
                   6329:                       file broken up into individual lines
                   6330:          count     - number of scanlines
                   6331:  
                   6332:      - second is the scan_data hash possible keys are
1.425     albertel 6333:        ($number refers to scanline numbered $number and thus the key affects
                   6334:         only that scanline
                   6335:         $bubline refers to the specific bubble line element and the aspects
                   6336:         refers to that specific bubble line element)
                   6337: 
                   6338:        $number.user - username:domain to use
                   6339:        $number.CODE_ignore_dup 
                   6340:                     - ignore the duplicate CODE error 
                   6341:        $number.useCODE
                   6342:                     - use the CODE in the scanline as is
                   6343:        $number.no_bubble.$bubline
                   6344:                     - it is valid that there is no bubbled in bubble
                   6345:                       at $number $bubline
                   6346:        remember_skipping
                   6347:                     - a frozen hash containing keys of $number and values
                   6348:                       of either 
                   6349:                         1 - we are on a 'do skipped records pass' and plan
                   6350:                             on processing this line
                   6351:                         2 - we are on a 'do skipped records pass' and this
                   6352:                             scanline has been marked to skip yet again
1.424     albertel 6353: 
1.423     albertel 6354: =cut
                   6355: 
1.157     albertel 6356: sub scantron_getfile {
1.200     albertel 6357:     #FIXME really would prefer a scantron directory
1.257     albertel 6358:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6359:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6360:     my $lines;
                   6361:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6362: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6363:     my %scanlines;
                   6364:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6365:     my $temp=$scanlines{'orig'};
                   6366:     $scanlines{'count'}=$#$temp;
                   6367: 
                   6368:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6369: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6370:     if ($lines eq '-1') {
                   6371: 	$scanlines{'corrected'}=[];
                   6372:     } else {
                   6373: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6374:     }
                   6375:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6376: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6377:     if ($lines eq '-1') {
                   6378: 	$scanlines{'skipped'}=[];
                   6379:     } else {
                   6380: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6381:     }
1.175     albertel 6382:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6383:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6384:     my %scan_data = @tmp;
                   6385:     return (\%scanlines,\%scan_data);
                   6386: }
                   6387: 
1.423     albertel 6388: =pod
                   6389: 
                   6390: =item lonnet_putfile
                   6391: 
1.424     albertel 6392:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6393: 
                   6394:  Arguments:
                   6395:    $contents - data to store
                   6396:    $filename - filename to store $contents into
                   6397: 
                   6398:  Returns:
                   6399:    result value from &Apache::lonnet::finishuserfileupload
                   6400: 
1.423     albertel 6401: =cut
                   6402: 
1.157     albertel 6403: sub lonnet_putfile {
                   6404:     my ($contents,$filename)=@_;
1.257     albertel 6405:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6406:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6407:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6408:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6409: 
                   6410: }
                   6411: 
1.423     albertel 6412: =pod
                   6413: 
                   6414: =item scantron_putfile
                   6415: 
1.424     albertel 6416:     Stores the current version of the bubble sheet data files, and the
                   6417:     scan_data hash. (Does not modify the original version only the
                   6418:     corrected and skipped versions.
                   6419: 
                   6420:  Arguments:
                   6421:     $scanlines - hash ref that looks like the first return value from
                   6422:                  &scantron_getfile()
                   6423:     $scan_data - hash ref that looks like the second return value from
                   6424:                  &scantron_getfile()
                   6425: 
1.423     albertel 6426: =cut
                   6427: 
1.157     albertel 6428: sub scantron_putfile {
                   6429:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6430:     #FIXME really would prefer a scantron directory
1.257     albertel 6431:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6432:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6433:     if ($scanlines) {
                   6434: 	my $prefix='scantron_';
1.157     albertel 6435: # no need to update orig, shouldn't change
                   6436: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6437: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6438: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6439: 			$prefix.'corrected_'.
1.257     albertel 6440: 			$env{'form.scantron_selectfile'});
1.200     albertel 6441: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6442: 			$prefix.'skipped_'.
1.257     albertel 6443: 			$env{'form.scantron_selectfile'});
1.200     albertel 6444:     }
1.175     albertel 6445:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6446: }
                   6447: 
1.423     albertel 6448: =pod
                   6449: 
                   6450: =item scantron_get_line
                   6451: 
1.424     albertel 6452:    Returns the correct version of the scanline
                   6453: 
                   6454:  Arguments:
                   6455:     $scanlines - hash ref that looks like the first return value from
                   6456:                  &scantron_getfile()
                   6457:     $scan_data - hash ref that looks like the second return value from
                   6458:                  &scantron_getfile()
                   6459:     $i         - number of the requested line (starts at 0)
                   6460: 
                   6461:  Returns:
                   6462:    A scanline, (either the original or the corrected one if it
                   6463:    exists), or undef if the requested scanline should be
                   6464:    skipped. (Either because it's an skipped scanline, or it's an
                   6465:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6466:    pass.
                   6467: 
1.423     albertel 6468: =cut
                   6469: 
1.157     albertel 6470: sub scantron_get_line {
1.200     albertel 6471:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6472:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6473:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6474:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6475:     return $scanlines->{'orig'}[$i]; 
                   6476: }
                   6477: 
1.423     albertel 6478: =pod
                   6479: 
                   6480: =item scantron_todo_count
                   6481: 
1.424     albertel 6482:     Counts the number of scanlines that need processing.
                   6483: 
                   6484:  Arguments:
                   6485:     $scanlines - hash ref that looks like the first return value from
                   6486:                  &scantron_getfile()
                   6487:     $scan_data - hash ref that looks like the second return value from
                   6488:                  &scantron_getfile()
                   6489: 
                   6490:  Returns:
                   6491:     $count - number of scanlines to process
                   6492: 
1.423     albertel 6493: =cut
                   6494: 
1.200     albertel 6495: sub get_todo_count {
                   6496:     my ($scanlines,$scan_data)=@_;
                   6497:     my $count=0;
                   6498:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6499: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6500: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6501: 	$count++;
                   6502:     }
                   6503:     return $count;
                   6504: }
                   6505: 
1.423     albertel 6506: =pod
                   6507: 
                   6508: =item scantron_put_line
                   6509: 
1.424     albertel 6510:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6511:     data file.
                   6512: 
                   6513:  Arguments:
                   6514:     $scanlines - hash ref that looks like the first return value from
                   6515:                  &scantron_getfile()
                   6516:     $scan_data - hash ref that looks like the second return value from
                   6517:                  &scantron_getfile()
                   6518:     $i         - line number to update
                   6519:     $newline   - contents of the updated scanline
                   6520:     $skip      - if true make the line for skipping and update the
                   6521:                  'skipped' file
                   6522: 
1.423     albertel 6523: =cut
                   6524: 
1.157     albertel 6525: sub scantron_put_line {
1.200     albertel 6526:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6527:     if ($skip) {
                   6528: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6529: 	&start_skipping($scan_data,$i);
1.157     albertel 6530: 	return;
                   6531:     }
                   6532:     $scanlines->{'corrected'}[$i]=$newline;
                   6533: }
                   6534: 
1.423     albertel 6535: =pod
                   6536: 
                   6537: =item scantron_clear_skip
                   6538: 
1.424     albertel 6539:    Remove a line from the 'skipped' file
                   6540: 
                   6541:  Arguments:
                   6542:     $scanlines - hash ref that looks like the first return value from
                   6543:                  &scantron_getfile()
                   6544:     $scan_data - hash ref that looks like the second return value from
                   6545:                  &scantron_getfile()
                   6546:     $i         - line number to update
                   6547: 
1.423     albertel 6548: =cut
                   6549: 
1.376     albertel 6550: sub scantron_clear_skip {
                   6551:     my ($scanlines,$scan_data,$i)=@_;
                   6552:     if (exists($scanlines->{'skipped'}[$i])) {
                   6553: 	undef($scanlines->{'skipped'}[$i]);
                   6554: 	return 1;
                   6555:     }
                   6556:     return 0;
                   6557: }
                   6558: 
1.423     albertel 6559: =pod
                   6560: 
                   6561: =item scantron_filter_not_exam
                   6562: 
1.424     albertel 6563:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6564:    filter out resources that are not marked as 'exam' mode
                   6565: 
1.423     albertel 6566: =cut
                   6567: 
1.334     albertel 6568: sub scantron_filter_not_exam {
                   6569:     my ($curres)=@_;
                   6570:     
                   6571:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6572: 	# if the user has asked to not have either hidden
                   6573: 	# or 'randomout' controlled resources to be graded
                   6574: 	# don't include them
                   6575: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6576: 	    && $curres->randomout) {
                   6577: 	    return 0;
                   6578: 	}
                   6579: 	return 1;
                   6580:     }
                   6581:     return 0;
                   6582: }
                   6583: 
1.423     albertel 6584: =pod
                   6585: 
                   6586: =item scantron_validate_sequence
                   6587: 
1.424     albertel 6588:     Validates the selected sequence, checking for resource that are
                   6589:     not set to exam mode.
                   6590: 
1.423     albertel 6591: =cut
                   6592: 
1.334     albertel 6593: sub scantron_validate_sequence {
                   6594:     my ($r,$currentphase) = @_;
                   6595: 
                   6596:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6597:     my (undef,undef,$sequence)=
                   6598: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6599: 
                   6600:     my $map=$navmap->getResourceByUrl($sequence);
                   6601: 
                   6602:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6603:                                     value="ignore" />');
                   6604:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6605: 	my @resources=
                   6606: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6607: 	if (@resources) {
1.357     banghart 6608: 	    $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 6609: 	    return (1,$currentphase);
                   6610: 	}
                   6611:     }
                   6612: 
                   6613:     return (0,$currentphase+1);
                   6614: }
                   6615: 
1.423     albertel 6616: =pod
                   6617: 
                   6618: =item scantron_validate_ID
                   6619: 
1.424     albertel 6620:    Validates all scanlines in the selected file to not have any
                   6621:    invalid or underspecified student IDs
                   6622: 
1.423     albertel 6623: =cut
                   6624: 
1.157     albertel 6625: sub scantron_validate_ID {
                   6626:     my ($r,$currentphase) = @_;
                   6627:     
                   6628:     #get student info
                   6629:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6630:     my %idmap=&username_to_idmap($classlist);
                   6631: 
                   6632:     #get scantron line setup
1.257     albertel 6633:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6634:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6635:     
                   6636:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6637: 
                   6638:     my %found=('ids'=>{},'usernames'=>{});
                   6639:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6640: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6641: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6642: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6643: 						 $scan_data);
                   6644: 	my $id=$$scan_record{'scantron.ID'};
                   6645: 	my $found;
                   6646: 	foreach my $checkid (keys(%idmap)) {
                   6647: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6648: 	}
                   6649: 	if ($found) {
                   6650: 	    my $username=$idmap{$found};
                   6651: 	    if ($found{'ids'}{$found}) {
                   6652: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6653: 					 $line,'duplicateID',$found);
1.194     albertel 6654: 		return(1,$currentphase);
1.157     albertel 6655: 	    } elsif ($found{'usernames'}{$username}) {
                   6656: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6657: 					 $line,'duplicateID',$username);
1.194     albertel 6658: 		return(1,$currentphase);
1.157     albertel 6659: 	    }
1.186     albertel 6660: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6661: 	    $found{'ids'}{$found}++;
                   6662: 	    $found{'usernames'}{$username}++;
                   6663: 	} else {
                   6664: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6665: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6666: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6667: 		    &scantron_get_correction($r,$i,$scan_record,
                   6668: 					     \%scantron_config,
                   6669: 					     $line,'duplicateID',$username);
1.194     albertel 6670: 		    return(1,$currentphase);
1.157     albertel 6671: 		} elsif (!defined($username)) {
                   6672: 		    &scantron_get_correction($r,$i,$scan_record,
                   6673: 					     \%scantron_config,
                   6674: 					     $line,'incorrectID');
1.194     albertel 6675: 		    return(1,$currentphase);
1.157     albertel 6676: 		}
                   6677: 		$found{'usernames'}{$username}++;
                   6678: 	    } else {
                   6679: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6680: 					 $line,'incorrectID');
1.194     albertel 6681: 		return(1,$currentphase);
1.157     albertel 6682: 	    }
                   6683: 	}
                   6684:     }
                   6685: 
                   6686:     return (0,$currentphase+1);
                   6687: }
                   6688: 
1.423     albertel 6689: =pod
                   6690: 
                   6691: =item scantron_get_correction
                   6692: 
1.424     albertel 6693:    Builds the interface screen to interact with the operator to fix a
                   6694:    specific error condition in a specific scanline
                   6695: 
                   6696:  Arguments:
                   6697:     $r           - Apache request object
                   6698:     $i           - number of the current scanline
                   6699:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6700:     $scan_config - hash ref as returned from &get_scantron_config()
                   6701:     $line        - full contents of the current scanline
                   6702:     $error       - error condition, valid values are
                   6703:                    'incorrectCODE', 'duplicateCODE',
                   6704:                    'doublebubble', 'missingbubble',
                   6705:                    'duplicateID', 'incorrectID'
                   6706:     $arg         - extra information needed
                   6707:        For errors:
                   6708:          - duplicateID   - paper number that this studentID was seen before on
                   6709:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6710:                            seen on before
                   6711:          - incorrectCODE - current incorrect CODE 
                   6712:          - doublebubble  - array ref of the bubble lines that have double
                   6713:                            bubble errors
                   6714:          - missingbubble - array ref of the bubble lines that have missing
                   6715:                            bubble errors
                   6716: 
1.423     albertel 6717: =cut
                   6718: 
1.157     albertel 6719: sub scantron_get_correction {
                   6720:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
1.454     banghart 6721: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6722: #to show both the current line and the previous one and allow skipping
                   6723: #the previous one or the current one
                   6724: 
1.333     albertel 6725:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6726: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6727: 			    " for PaperID <tt>[_1]</tt>",
                   6728: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6729:     } else {
1.492     albertel 6730: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6731: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6732: 			    $i,$line)."</p> \n");
                   6733:     }
                   6734:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6735: 			  "The name on the paper is [_2],[_3]",
                   6736: 			  $$scan_record{'scantron.ID'},
                   6737: 			  $$scan_record{'scantron.LastName'},
                   6738: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6739: 
1.157     albertel 6740:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6741:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
1.503     raeburn  6742:                            # Array populated for doublebubble or
                   6743:     my @lines_to_correct;  # missingbubble errors to build javascript
                   6744:                            # to validate radio button checking   
                   6745: 
1.157     albertel 6746:     if ($error =~ /ID$/) {
1.186     albertel 6747: 	if ($error eq 'incorrectID') {
1.492     albertel 6748: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6749: 		      "</p>\n");
1.157     albertel 6750: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6751: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6752: 	}
1.242     albertel 6753: 	$r->print($message);
1.492     albertel 6754: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6755: 	$r->print("\n<ul><li> ");
                   6756: 	#FIXME it would be nice if this sent back the user ID and
                   6757: 	#could do partial userID matches
                   6758: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6759: 				       'scantron_username','scantron_domain'));
                   6760: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6761: 	$r->print("\n@".
1.257     albertel 6762: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6763: 
                   6764: 	$r->print('</li>');
1.186     albertel 6765:     } elsif ($error =~ /CODE$/) {
                   6766: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6767: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6768: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6769: 	    $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 6770: 	}
1.492     albertel 6771: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6772: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6773: 	$r->print($message);
1.492     albertel 6774: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6775: 	$r->print("\n<br /> ");
1.194     albertel 6776: 	my $i=0;
1.273     albertel 6777: 	if ($error eq 'incorrectCODE' 
                   6778: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6779: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6780: 	    if ($closest > 0) {
                   6781: 		foreach my $testcode (@{$closest}) {
                   6782: 		    my $checked='';
1.401     albertel 6783: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6784: 		    $r->print("
                   6785:    <label>
                   6786:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6787:        ".&mt("Use the similar CODE [_1] instead.",
                   6788: 	    "<b><tt>".$testcode."</tt></b>")."
                   6789:     </label>
                   6790:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6791: 		    $r->print("\n<br />");
                   6792: 		    $i++;
                   6793: 		}
1.194     albertel 6794: 	    }
                   6795: 	}
1.273     albertel 6796: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6797: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6798: 	    $r->print("
                   6799:     <label>
                   6800:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6801:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6802: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6803:     </label>");
1.273     albertel 6804: 	    $r->print("\n<br />");
                   6805: 	}
1.194     albertel 6806: 
1.188     albertel 6807: 	$r->print(<<ENDSCRIPT);
                   6808: <script type="text/javascript">
                   6809: function change_radio(field) {
1.190     albertel 6810:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6811:     var i;
                   6812:     for (i=0;i<slct.length;i++) {
                   6813:         if (slct[i].value==field) { slct[i].checked=true; }
                   6814:     }
                   6815: }
                   6816: </script>
                   6817: ENDSCRIPT
1.187     albertel 6818: 	my $href="/adm/pickcode?".
1.359     www      6819: 	   "form=".&escape("scantronupload").
                   6820: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6821: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6822: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6823: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6824: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6825: 	    $r->print("
                   6826:     <label>
                   6827:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6828:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6829: 	     "<a target='_blank' href='$href'>","</a>")."
                   6830:     </label> 
                   6831:     ".&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 6832: 	    $r->print("\n<br />");
                   6833: 	}
1.492     albertel 6834: 	$r->print("
                   6835:     <label>
                   6836:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6837:        ".&mt("Use [_1] as the CODE.",
                   6838: 	     "</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 6839: 	$r->print("\n<br /><br />");
1.157     albertel 6840:     } elsif ($error eq 'doublebubble') {
1.503     raeburn  6841: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for some question(s)")."</p>\n");
1.497     foxr     6842: 
                   6843: 	# The form field scantron_questions is acutally a list of line numbers.
                   6844: 	# represented by this form so:
                   6845: 
                   6846: 	my $line_list = &questions_to_line_list($arg);
                   6847: 
1.157     albertel 6848: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6849: 		  $line_list.'" />');
1.242     albertel 6850: 	$r->print($message);
1.492     albertel 6851: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6852: 	foreach my $question (@{$arg}) {
1.503     raeburn  6853: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6854:                                                    $scan_record, $error);
1.524     raeburn  6855:             push(@lines_to_correct,@linenums);
1.157     albertel 6856: 	}
1.503     raeburn  6857:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6858:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6859: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6860: 	$r->print($message);
1.492     albertel 6861: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
1.503     raeburn  6862: 	$r->print(&mt("Some questions have no scanned bubbles.")."\n");
1.497     foxr     6863: 
1.503     raeburn  6864: 	# The form field scantron_questions is actually a list of line numbers not
1.497     foxr     6865: 	# a list of question numbers. Therefore:
                   6866: 	#
                   6867: 	
                   6868: 	my $line_list = &questions_to_line_list($arg);
                   6869: 
1.157     albertel 6870: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
1.497     foxr     6871: 		  $line_list.'" />');
1.157     albertel 6872: 	foreach my $question (@{$arg}) {
1.503     raeburn  6873: 	    my @linenums = &prompt_for_corrections($r,$question,$scan_config,
                   6874:                                                    $scan_record, $error);
1.524     raeburn  6875:             push(@lines_to_correct,@linenums);
1.157     albertel 6876: 	}
1.503     raeburn  6877:         $r->print(&verify_bubbles_checked(@lines_to_correct));
1.157     albertel 6878:     } else {
                   6879: 	$r->print("\n<ul>");
                   6880:     }
                   6881:     $r->print("\n</li></ul>");
1.497     foxr     6882: }
                   6883: 
1.503     raeburn  6884: sub verify_bubbles_checked {
                   6885:     my (@ansnums) = @_;
                   6886:     my $ansnumstr = join('","',@ansnums);
                   6887:     my $warning = &mt("A bubble or 'No bubble' selection has not been made for one or more lines.");
                   6888:     my $output = (<<ENDSCRIPT);
                   6889: <script type="text/javascript">
                   6890: function verify_bubble_radio(form) {
                   6891:     var ansnumArray = new Array ("$ansnumstr");
                   6892:     var need_bubble_count = 0;
                   6893:     for (var i=0; i<ansnumArray.length; i++) {
                   6894:         if (form.elements["scantron_correct_Q_"+ansnumArray[i]].length > 1) {
                   6895:             var bubble_picked = 0; 
                   6896:             for (var j=0; j<form.elements["scantron_correct_Q_"+ansnumArray[i]].length; j++) {
                   6897:                 if (form.elements["scantron_correct_Q_"+ansnumArray[i]][j].checked == true) {
                   6898:                     bubble_picked = 1;
                   6899:                 }
                   6900:             }
                   6901:             if (bubble_picked == 0) {
                   6902:                 need_bubble_count ++;
                   6903:             }
                   6904:         }
                   6905:     }
                   6906:     if (need_bubble_count) {
                   6907:         alert("$warning");
                   6908:         return;
                   6909:     }
                   6910:     form.submit(); 
                   6911: }
                   6912: </script>
                   6913: ENDSCRIPT
                   6914:     return $output;
                   6915: }
                   6916: 
1.497     foxr     6917: =pod
                   6918: 
                   6919: =item  questions_to_line_list
1.157     albertel 6920: 
1.497     foxr     6921: Converts a list of questions into a string of comma separated
                   6922: line numbers in the answer sheet used by the questions.  This is
                   6923: used to fill in the scantron_questions form field.
                   6924: 
                   6925:   Arguments:
                   6926:      questions    - Reference to an array of questions.
                   6927: 
                   6928: =cut
                   6929: 
                   6930: 
                   6931: sub questions_to_line_list {
                   6932:     my ($questions) = @_;
                   6933:     my @lines;
                   6934: 
1.503     raeburn  6935:     foreach my $item (@{$questions}) {
                   6936:         my $question = $item;
                   6937:         my ($first,$count,$last);
                   6938:         if ($item =~ /^(\d+)\.(\d+)$/) {
                   6939:             $question = $1;
                   6940:             my $subquestion = $2;
                   6941:             $first = $first_bubble_line{$question-1} + 1;
                   6942:             my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   6943:             my $subcount = 1;
                   6944:             while ($subcount<$subquestion) {
                   6945:                 $first += $subans[$subcount-1];
                   6946:                 $subcount ++;
                   6947:             }
                   6948:             $count = $subans[$subquestion-1];
                   6949:         } else {
                   6950: 	    $first   = $first_bubble_line{$question-1} + 1;
                   6951: 	    $count   = $bubble_lines_per_response{$question-1};
                   6952:         }
1.506     raeburn  6953:         $last = $first+$count-1;
1.503     raeburn  6954:         push(@lines, ($first..$last));
1.497     foxr     6955:     }
                   6956:     return join(',', @lines);
                   6957: }
                   6958: 
                   6959: =pod 
                   6960: 
                   6961: =item prompt_for_corrections
                   6962: 
                   6963: Prompts for a potentially multiline correction to the
                   6964: user's bubbling (factors out common code from scantron_get_correction
                   6965: for multi and missing bubble cases).
                   6966: 
                   6967:  Arguments:
                   6968:    $r           - Apache request object.
                   6969:    $question    - The question number to prompt for.
                   6970:    $scan_config - The scantron file configuration hash.
                   6971:    $scan_record - Reference to the hash that has the the parsed scanlines.
1.503     raeburn  6972:    $error       - Type of error
1.497     foxr     6973: 
                   6974:  Implicit inputs:
                   6975:    %bubble_lines_per_response   - Starting line numbers for each question.
                   6976:                                   Numbered from 0 (but question numbers are from
                   6977:                                   1.
                   6978:    %first_bubble_line           - Starting bubble line for each question.
1.509     raeburn  6979:    %subdivided_bubble_lines     - optionresponse, matchresponse and rankresponse 
                   6980:                                   type problems render as separate sub-questions, 
1.503     raeburn  6981:                                   in exam mode. This hash contains a 
                   6982:                                   comma-separated list of the lines per 
                   6983:                                   sub-question.
1.510     raeburn  6984:    %responsetype_per_response   - essayresponse, formularesponse,
                   6985:                                   stringresponse, imageresponse, reactionresponse,
                   6986:                                   and organicresponse type problem parts can have
1.503     raeburn  6987:                                   multiple lines per response if the weight
                   6988:                                   assigned exceeds 10.  In this case, only
                   6989:                                   one bubble per line is permitted, but more 
                   6990:                                   than one line might contain bubbles, e.g.
                   6991:                                   bubbling of: line 1 - J, line 2 - J, 
                   6992:                                   line 3 - B would assign 22 points.  
1.497     foxr     6993: 
                   6994: =cut
                   6995: 
                   6996: sub prompt_for_corrections {
1.503     raeburn  6997:     my ($r, $question, $scan_config, $scan_record, $error) = @_;
                   6998:     my ($current_line,$lines);
                   6999:     my @linenums;
                   7000:     my $questionnum = $question;
                   7001:     if ($question =~ /^(\d+)\.(\d+)$/) {
                   7002:         $question = $1;
                   7003:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7004:         my $subquestion = $2;
                   7005:         my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7006:         my $subcount = 1;
                   7007:         while ($subcount<$subquestion) {
                   7008:             $current_line += $subans[$subcount-1];
                   7009:             $subcount ++;
                   7010:         }
                   7011:         $lines = $subans[$subquestion-1];
                   7012:     } else {
                   7013:         $current_line = $first_bubble_line{$question-1} + 1 ;
                   7014:         $lines        = $bubble_lines_per_response{$question-1};
                   7015:     }
1.497     foxr     7016:     if ($lines > 1) {
1.503     raeburn  7017:         $r->print(&mt('The group of bubble lines below responds to a single question.').'<br />');
                   7018:         if (($responsetype_per_response{$question-1} eq 'essayresponse') ||
                   7019:             ($responsetype_per_response{$question-1} eq 'formularesponse') ||
1.510     raeburn  7020:             ($responsetype_per_response{$question-1} eq 'stringresponse') ||
                   7021:             ($responsetype_per_response{$question-1} eq 'imageresponse') ||
                   7022:             ($responsetype_per_response{$question-1} eq 'reactionresponse') ||
                   7023:             ($responsetype_per_response{$question-1} eq 'organicresponse')) {
1.503     raeburn  7024:             $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 />');
                   7025:         } else {
                   7026:             $r->print(&mt("Select at most one bubble in a single line and select 'No Bubble' in all the other lines. ")."<br />");
                   7027:         }
1.497     foxr     7028:     }
                   7029:     for (my $i =0; $i < $lines; $i++) {
1.503     raeburn  7030:         my $selected = $$scan_record{"scantron.$current_line.answer"};
                   7031: 	&scantron_bubble_selector($r,$scan_config,$current_line, 
                   7032: 	        		  $questionnum,$error,split('', $selected));
1.524     raeburn  7033:         push(@linenums,$current_line);
1.497     foxr     7034: 	$current_line++;
                   7035:     }
                   7036:     if ($lines > 1) {
                   7037: 	$r->print("<hr /><br />");
                   7038:     }
1.503     raeburn  7039:     return @linenums;
1.157     albertel 7040: }
1.423     albertel 7041: 
                   7042: =pod
                   7043: 
                   7044: =item scantron_bubble_selector
                   7045:   
                   7046:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 7047:    possibly showing the existing the selected bubbles if known
1.423     albertel 7048: 
                   7049:  Arguments:
                   7050:     $r           - Apache request object
                   7051:     $scan_config - hash from &get_scantron_config()
1.497     foxr     7052:     $line        - Number of the line being displayed.
1.503     raeburn  7053:     $questionnum - Question number (may include subquestion)
                   7054:     $error       - Type of error.
1.497     foxr     7055:     @selected    - Array of bubbles picked on this line.
1.423     albertel 7056: 
                   7057: =cut
                   7058: 
1.157     albertel 7059: sub scantron_bubble_selector {
1.503     raeburn  7060:     my ($r,$scan_config,$line,$questionnum,$error,@selected)=@_;
1.157     albertel 7061:     my $max=$$scan_config{'Qlength'};
1.274     albertel 7062: 
                   7063:     my $scmode=$$scan_config{'Qon'};
                   7064:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   7065: 
1.157     albertel 7066:     my @alphabet=('A'..'Z');
1.503     raeburn  7067:     $r->print(&Apache::loncommon::start_data_table().
                   7068:               &Apache::loncommon::start_data_table_row());
                   7069:     $r->print('<td rowspan="2" class="LC_leftcol_header">'.$line.'</td>');
1.497     foxr     7070:     for (my $i=0;$i<$max+1;$i++) {
                   7071: 	$r->print("\n".'<td align="center">');
                   7072: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   7073: 	else { $r->print('&nbsp;'); }
                   7074: 	$r->print('</td>');
                   7075:     }
1.503     raeburn  7076:     $r->print(&Apache::loncommon::end_data_table_row().
                   7077:               &Apache::loncommon::start_data_table_row());
1.497     foxr     7078:     for (my $i=0;$i<$max;$i++) {
                   7079: 	$r->print("\n".
                   7080: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
                   7081: 		  $line.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   7082:     }
1.503     raeburn  7083:     my $nobub_checked = ' ';
                   7084:     if ($error eq 'missingbubble') {
                   7085:         $nobub_checked = ' checked = "checked" ';
                   7086:     }
                   7087:     $r->print("\n".'<td><label><input type="radio" name="scantron_correct_Q_'.
                   7088: 	      $line.'" value="none"'.$nobub_checked.'/>'.&mt('No bubble').
                   7089:               '</label>'."\n".'<input type="hidden" name="scantron_questionnum_Q_'.
                   7090:               $line.'" value="'.$questionnum.'" /></td>');
                   7091:     $r->print(&Apache::loncommon::end_data_table_row().
                   7092:               &Apache::loncommon::end_data_table());
1.157     albertel 7093: }
                   7094: 
1.423     albertel 7095: =pod
                   7096: 
                   7097: =item num_matches
                   7098: 
1.424     albertel 7099:    Counts the number of characters that are the same between the two arguments.
                   7100: 
                   7101:  Arguments:
                   7102:    $orig - CODE from the scanline
                   7103:    $code - CODE to match against
                   7104: 
                   7105:  Returns:
                   7106:    $count - integer count of the number of same characters between the
                   7107:             two arguments
                   7108: 
1.423     albertel 7109: =cut
                   7110: 
1.194     albertel 7111: sub num_matches {
                   7112:     my ($orig,$code) = @_;
                   7113:     my @code=split(//,$code);
                   7114:     my @orig=split(//,$orig);
                   7115:     my $same=0;
                   7116:     for (my $i=0;$i<scalar(@code);$i++) {
                   7117: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   7118:     }
                   7119:     return $same;
                   7120: }
                   7121: 
1.423     albertel 7122: =pod
                   7123: 
                   7124: =item scantron_get_closely_matching_CODEs
                   7125: 
1.424     albertel 7126:    Cycles through all CODEs and finds the set that has the greatest
                   7127:    number of same characters as the provided CODE
                   7128: 
                   7129:  Arguments:
                   7130:    $allcodes - hash ref returned by &get_codes()
                   7131:    $CODE     - CODE from the current scanline
                   7132: 
                   7133:  Returns:
                   7134:    2 element list
                   7135:     - first elements is number of how closely matching the best fit is 
                   7136:       (5 means best set has 5 matching characters)
                   7137:     - second element is an arrary ref containing the set of valid CODEs
                   7138:       that best fit the passed in CODE
                   7139: 
1.423     albertel 7140: =cut
                   7141: 
1.194     albertel 7142: sub scantron_get_closely_matching_CODEs {
                   7143:     my ($allcodes,$CODE)=@_;
                   7144:     my @CODEs;
                   7145:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   7146: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   7147:     }
                   7148: 
                   7149:     return ($#CODEs,$CODEs[-1]);
                   7150: }
                   7151: 
1.423     albertel 7152: =pod
                   7153: 
                   7154: =item get_codes
                   7155: 
1.424     albertel 7156:    Builds a hash which has keys of all of the valid CODEs from the selected
                   7157:    set of remembered CODEs.
                   7158: 
                   7159:  Arguments:
                   7160:   $old_name - name of the set of remembered CODEs
                   7161:   $cdom     - domain of the course
                   7162:   $cnum     - internal course name
                   7163: 
                   7164:  Returns:
                   7165:   %allcodes - keys are the valid CODEs, values are all 1
                   7166: 
1.423     albertel 7167: =cut
                   7168: 
1.194     albertel 7169: sub get_codes {
1.280     foxr     7170:     my ($old_name, $cdom, $cnum) = @_;
                   7171:     if (!$old_name) {
                   7172: 	$old_name=$env{'form.scantron_CODElist'};
                   7173:     }
                   7174:     if (!$cdom) {
                   7175: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7176:     }
                   7177:     if (!$cnum) {
                   7178: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   7179:     }
1.278     albertel 7180:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   7181: 				    $cdom,$cnum);
                   7182:     my %allcodes;
                   7183:     if ($result{"type\0$old_name"} eq 'number') {
                   7184: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   7185:     } else {
                   7186: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   7187:     }
1.194     albertel 7188:     return %allcodes;
                   7189: }
                   7190: 
1.423     albertel 7191: =pod
                   7192: 
                   7193: =item scantron_validate_CODE
                   7194: 
1.424     albertel 7195:    Validates all scanlines in the selected file to not have any
                   7196:    invalid or underspecified CODEs and that none of the codes are
                   7197:    duplicated if this was requested.
                   7198: 
1.423     albertel 7199: =cut
                   7200: 
1.157     albertel 7201: sub scantron_validate_CODE {
                   7202:     my ($r,$currentphase) = @_;
1.257     albertel 7203:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 7204:     if ($scantron_config{'CODElocation'} &&
                   7205: 	$scantron_config{'CODEstart'} &&
                   7206: 	$scantron_config{'CODElength'}) {
1.257     albertel 7207: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 7208: 	    &FIXME_blow_up()
                   7209: 	}
                   7210:     } else {
                   7211: 	return (0,$currentphase+1);
                   7212:     }
                   7213:     
                   7214:     my %usedCODEs;
                   7215: 
1.194     albertel 7216:     my %allcodes=&get_codes();
1.186     albertel 7217: 
1.447     foxr     7218:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   7219: 
1.186     albertel 7220:     my ($scanlines,$scan_data)=&scantron_getfile();
                   7221:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7222: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 7223: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7224: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7225: 						 $scan_data);
                   7226: 	my $CODE=$$scan_record{'scantron.CODE'};
                   7227: 	my $error=0;
1.224     albertel 7228: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   7229: 	    &scantron_get_correction($r,$i,$scan_record,
                   7230: 				     \%scantron_config,
                   7231: 				     $line,'incorrectCODE',\%allcodes);
                   7232: 	    return(1,$currentphase);
                   7233: 	}
1.221     albertel 7234: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   7235: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 7236: 	    &scantron_get_correction($r,$i,$scan_record,
                   7237: 				     \%scantron_config,
1.194     albertel 7238: 				     $line,'incorrectCODE',\%allcodes);
                   7239: 	    return(1,$currentphase);
1.186     albertel 7240: 	}
1.214     albertel 7241: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 7242: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 7243: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 7244: 	    &scantron_get_correction($r,$i,$scan_record,
                   7245: 				     \%scantron_config,
1.194     albertel 7246: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   7247: 	    return(1,$currentphase);
1.186     albertel 7248: 	}
1.524     raeburn  7249: 	push(@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 7250:     }
1.157     albertel 7251:     return (0,$currentphase+1);
                   7252: }
                   7253: 
1.423     albertel 7254: =pod
                   7255: 
                   7256: =item scantron_validate_doublebubble
                   7257: 
1.424     albertel 7258:    Validates all scanlines in the selected file to not have any
                   7259:    bubble lines with multiple bubbles marked.
                   7260: 
1.423     albertel 7261: =cut
                   7262: 
1.157     albertel 7263: sub scantron_validate_doublebubble {
                   7264:     my ($r,$currentphase) = @_;
                   7265:     #get student info
                   7266:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7267:     my %idmap=&username_to_idmap($classlist);
                   7268: 
                   7269:     #get scantron line setup
1.257     albertel 7270:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7271:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     7272:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   7273: 
1.157     albertel 7274:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7275: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7276: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7277: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7278: 						 $scan_data);
                   7279: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   7280: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   7281: 				 'doublebubble',
                   7282: 				 $$scan_record{'scantron.doubleerror'});
                   7283:     	return (1,$currentphase);
                   7284:     }
                   7285:     return (0,$currentphase+1);
                   7286: }
                   7287: 
1.423     albertel 7288: =pod
                   7289: 
                   7290: =item scantron_get_maxbubble
                   7291: 
1.424     albertel 7292:    Returns the maximum number of bubble lines that are expected to
                   7293:    occur. Does this by walking the selected sequence rendering the
                   7294:    resource and then checking &Apache::lonxml::get_problem_counter()
                   7295:    for what the current value of the problem counter is.
                   7296: 
1.447     foxr     7297:    Caches the results to $env{'form.scantron_maxbubble'},
1.503     raeburn  7298:    $env{'form.scantron.bubble_lines.n'}, 
                   7299:    $env{'form.scantron.first_bubble_line.n'} and
                   7300:    $env{"form.scantron.sub_bubblelines.n"}
1.447     foxr     7301:    which are the total number of bubble, lines, the number of bubble
1.503     raeburn  7302:    lines for response n and number of the first bubble line for response n,
                   7303:    and a comma separated list of numbers of bubble lines for sub-questions
1.509     raeburn  7304:    (for optionresponse, matchresponse, and rankresponse items), for response n.  
1.424     albertel 7305: 
1.423     albertel 7306: =cut
                   7307: 
1.503     raeburn  7308: sub scantron_get_maxbubble {
1.257     albertel 7309:     if (defined($env{'form.scantron_maxbubble'}) &&
                   7310: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     7311: 	&restore_bubble_lines();
1.257     albertel 7312: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 7313:     }
1.330     albertel 7314: 
1.447     foxr     7315:     my (undef, undef, $sequence) =
1.257     albertel 7316: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 7317: 
1.447     foxr     7318:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 7319:     my $map=$navmap->getResourceByUrl($sequence);
                   7320:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 7321: 
                   7322:     &Apache::lonxml::clear_problem_counter();
                   7323: 
1.435     foxr     7324:     my $uname       = $env{'form.student'};
                   7325:     my $udom        = $env{'form.userdom'};
                   7326:     my $cid         = $env{'request.course.id'};
                   7327:     my $total_lines = 0;
                   7328:     %bubble_lines_per_response = ();
1.447     foxr     7329:     %first_bubble_line         = ();
1.503     raeburn  7330:     %subdivided_bubble_lines   = ();
                   7331:     %responsetype_per_response = ();
1.447     foxr     7332:   
                   7333:     my $response_number = 0;
                   7334:     my $bubble_line     = 0;
1.191     albertel 7335:     foreach my $resource (@resources) {
1.528.2.4  raeburn  7336:         my ($analysis,$parts) = &scantron_partids_tograde($resource,$cid,$uname,$udom);
                   7337:         if ((ref($analysis) eq 'HASH') && (ref($parts) eq 'ARRAY')) {
                   7338:             foreach my $part_id (@{$parts}) {
                   7339: 
                   7340:                 my $lines;
                   7341: 
                   7342: 	        # TODO - make this a persistent hash not an array.
                   7343: 
                   7344:                 # optionresponse, matchresponse and rankresponse type items 
                   7345:                 # render as separate sub-questions in exam mode.
                   7346:                 if (($analysis->{$part_id.'.type'} eq 'optionresponse') ||
                   7347:                     ($analysis->{$part_id.'.type'} eq 'matchresponse') ||
                   7348:                     ($analysis->{$part_id.'.type'} eq 'rankresponse')) {
                   7349:                     my ($numbub,$numshown);
                   7350:                     if ($analysis->{$part_id.'.type'} eq 'optionresponse') {
                   7351:                         if (ref($analysis->{$part_id.'.options'}) eq 'ARRAY') {
1.528.2.5  raeburn  7352:                             $numbub = scalar(@{$analysis->{$part_id.'.options'}});
1.528.2.4  raeburn  7353:                         }
                   7354:                     } elsif ($analysis->{$part_id.'.type'} eq 'matchresponse') {
1.528.2.5  raeburn  7355:                         if (ref($analysis->{$part_id.'.items'}) eq 'ARRAY') {
                   7356:                             $numbub = scalar(@{$analysis->{$part_id.'.items'}});
1.528.2.4  raeburn  7357:                         }
                   7358:                     } elsif ($analysis->{$part_id.'.type'} eq 'rankresponse') {
                   7359:                         if (ref($analysis->{$part_id.'.foils'}) eq 'ARRAY') {
                   7360:                             $numbub = scalar(@{$analysis->{$part_id.'.foils'}});
                   7361:                         }
                   7362:                     }
                   7363:                     if (ref($analysis->{$part_id.'.shown'}) eq 'ARRAY') {
                   7364:                         $numshown = scalar(@{$analysis->{$part_id.'.shown'}});
                   7365:                     }
                   7366:                     my $bubbles_per_line = 10;
                   7367:                     my $inner_bubble_lines = int($numbub/$bubbles_per_line);
                   7368:                     if (($numbub % $bubbles_per_line) != 0) {
                   7369:                         $inner_bubble_lines++;
                   7370:                     }
                   7371:                     for (my $i=0; $i<$numshown; $i++) {
                   7372:                         $subdivided_bubble_lines{$response_number} .= 
                   7373:                             $inner_bubble_lines.',';
                   7374:                     }
                   7375:                     $subdivided_bubble_lines{$response_number} =~ s/,$//;
                   7376:                     $lines = $numshown * $inner_bubble_lines;
                   7377:                 } else {
                   7378:                     $lines = $analysis->{"$part_id.bubble_lines"};
                   7379:                 } 
                   7380: 
                   7381:                 $first_bubble_line{$response_number} = $bubble_line;
                   7382: 	        $bubble_lines_per_response{$response_number} = $lines;
                   7383:                 $responsetype_per_response{$response_number} = 
                   7384:                     $analysis->{$part_id.'.type'};
                   7385: 	        $response_number++;
                   7386: 
                   7387: 	        $bubble_line +=  $lines;
                   7388: 	        $total_lines +=  $lines;
                   7389: 	    }
                   7390:         }
                   7391:     }
                   7392:     &Apache::lonnet::delenv('scantron\.');
                   7393: 
                   7394:     &save_bubble_lines();
                   7395:     $env{'form.scantron_maxbubble'} =
                   7396: 	$total_lines;
                   7397:     return $env{'form.scantron_maxbubble'};
                   7398: }
1.523     raeburn  7399: 
1.528.2.4  raeburn  7400: sub scantron_partids_tograde {
                   7401:     my ($resource,$cid,$uname,$udom) = @_;
                   7402:     my (%analysis,@parts);
1.435     foxr     7403: 
1.528.2.4  raeburn  7404:     if (ref($resource)) {
                   7405:         my $symb = $resource->symb();
1.523     raeburn  7406:         my $result=&ssi_with_retries($resource->src(), $ssi_retries,
                   7407:                                         ('symb' => $symb,
                   7408:                                          'grade_target' => 'analyze',
                   7409:                                          'grade_courseid' => $cid,
                   7410:                                          'grade_domain' => $udom,
                   7411:                                          'grade_username' => $uname));
1.528.2.4  raeburn  7412:         my (undef, $an) = split(/_HASH_REF__/,$result, 2);
                   7413:         %analysis = &Apache::lonnet::str2hash($an);
1.435     foxr     7414: 
1.503     raeburn  7415:         if (ref($analysis{'parts'}) eq 'ARRAY') {
1.515     raeburn  7416:             foreach my $part (@{$analysis{'parts'}}) {
                   7417:                 my ($id,$respid) = split(/\./,$part);
                   7418:                 if (!&Apache::loncommon::check_if_partid_hidden($id,$symb,$udom,$uname)) {
                   7419:                     push(@parts,$part);
                   7420:                 }
                   7421:             }
1.503     raeburn  7422:         }
1.191     albertel 7423:     }
1.528.2.4  raeburn  7424:     return (\%analysis,\@parts);
1.191     albertel 7425: }
                   7426: 
1.423     albertel 7427: =pod
                   7428: 
                   7429: =item scantron_validate_missingbubbles
                   7430: 
1.424     albertel 7431:    Validates all scanlines in the selected file to not have any
1.447     foxr     7432:     answers that don't have bubbles that have not been verified
                   7433:     to be bubble free.
1.424     albertel 7434: 
1.423     albertel 7435: =cut
                   7436: 
1.157     albertel 7437: sub scantron_validate_missingbubbles {
                   7438:     my ($r,$currentphase) = @_;
                   7439:     #get student info
                   7440:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7441:     my %idmap=&username_to_idmap($classlist);
                   7442: 
                   7443:     #get scantron line setup
1.257     albertel 7444:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7445:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7446:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7447:     if (!$max_bubble) { $max_bubble=2**31; }
                   7448:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7449: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7450: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7451: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7452: 						 $scan_data);
                   7453: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7454: 	my @to_correct;
1.470     foxr     7455: 	
                   7456: 	# Probably here's where the error is...
                   7457: 
1.157     albertel 7458: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
1.505     raeburn  7459:             my $lastbubble;
                   7460:             if ($missing =~ /^(\d+)\.(\d+)$/) {
                   7461:                my $question = $1;
                   7462:                my $subquestion = $2;
                   7463:                if (!defined($first_bubble_line{$question -1})) { next; }
                   7464:                my $first = $first_bubble_line{$question-1};
                   7465:                my @subans = split(/,/,$subdivided_bubble_lines{$question-1});
                   7466:                my $subcount = 1;
                   7467:                while ($subcount<$subquestion) {
                   7468:                    $first += $subans[$subcount-1];
                   7469:                    $subcount ++;
                   7470:                }
                   7471:                my $count = $subans[$subquestion-1];
                   7472:                $lastbubble = $first + $count;
                   7473:             } else {
                   7474:                 if (!defined($first_bubble_line{$missing - 1})) { next; }
                   7475:                 $lastbubble = $first_bubble_line{$missing - 1} + $bubble_lines_per_response{$missing - 1};
                   7476:             }
                   7477:             if ($lastbubble > $max_bubble) { next; }
1.157     albertel 7478: 	    push(@to_correct,$missing);
                   7479: 	}
                   7480: 	if (@to_correct) {
                   7481: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7482: 				     $line,'missingbubble',\@to_correct);
                   7483: 	    return (1,$currentphase);
                   7484: 	}
                   7485: 
                   7486:     }
                   7487:     return (0,$currentphase+1);
                   7488: }
                   7489: 
1.423     albertel 7490: =pod
                   7491: 
                   7492: =item scantron_process_students
                   7493: 
                   7494:    Routine that does the actual grading of the bubble sheet information.
                   7495: 
                   7496:    The parsed scanline hash is added to %env 
                   7497: 
                   7498:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7499:    foreach resource , with the form data of
                   7500: 
                   7501: 	'submitted'     =>'scantron' 
                   7502: 	'grade_target'  =>'grade',
                   7503: 	'grade_username'=> username of student
                   7504: 	'grade_domain'  => domain of student
                   7505: 	'grade_courseid'=> of course
                   7506: 	'grade_symb'    => symb of resource to grade
                   7507: 
                   7508:     This triggers a grading pass. The problem grading code takes care
                   7509:     of converting the bubbled letter information (now in %env) into a
                   7510:     valid submission.
                   7511: 
                   7512: =cut
                   7513: 
1.82      albertel 7514: sub scantron_process_students {
1.75      albertel 7515:     my ($r) = @_;
1.513     foxr     7516: 
1.257     albertel 7517:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7518:     my ($symb)=&get_symb($r);
1.513     foxr     7519:     if (!$symb) {
                   7520: 	return '';
                   7521:     }
1.324     albertel 7522:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7523: 
1.257     albertel 7524:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7525:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7526:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7527:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7528:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7529:     my $map=$navmap->getResourceByUrl($sequence);
                   7530:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.528.2.4  raeburn  7531: 
                   7532:     my ($uname,$udom,%partids_by_symb);
                   7533:     foreach my $resource (@resources) {
                   7534:         my $ressymb = $resource->symb();
                   7535:         my ($analysis,$parts) =
                   7536:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7537:         $partids_by_symb{$ressymb} = $parts;
                   7538:     }
1.140     albertel 7539: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7540:     my $result= <<SCANTRONFORM;
1.81      albertel 7541: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7542:   <input type="hidden" name="command" value="scantron_configphase" />
                   7543:   $default_form_data
                   7544: SCANTRONFORM
1.82      albertel 7545:     $r->print($result);
                   7546: 
                   7547:     my @delayqueue;
1.528.2.4  raeburn  7548:     my (%completedstudents,,%scandata);
1.140     albertel 7549:     
1.520     www      7550:     my $lock=&Apache::lonnet::set_lock(&mt('Grading bubblesheet exam'));
1.200     albertel 7551:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7552:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7553:  				    'Scantron Progress',$count,
1.195     albertel 7554: 				    'inline',undef,'scantronupload');
1.140     albertel 7555:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7556: 					  'Processing first student');
1.528.2.4  raeburn  7557:     $r->print('<br />');
1.140     albertel 7558:     my $start=&Time::HiRes::time();
1.158     albertel 7559:     my $i=-1;
1.528.2.4  raeburn  7560:     my $started;
1.447     foxr     7561: 
                   7562:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
1.513     foxr     7563:     
                   7564: 
                   7565:     # If an ssi failed in scantron_get_maxbubble, put an error message out to
                   7566:     # the user and return.
                   7567: 
                   7568:     if ($ssi_error) {
                   7569: 	$r->print("</form>");
                   7570: 	&ssi_print_error($r);
                   7571: 	$r->print(&show_grading_menu_form($symb));
1.520     www      7572:         &Apache::lonnet::remove_lock($lock);
1.513     foxr     7573: 	return '';		# Dunno why the other returns return '' rather than just returning.
                   7574:     }
1.447     foxr     7575: 
1.528.2.4  raeburn  7576:     my %lettdig = &letter_to_digits();
                   7577:     my $numletts = scalar(keys(%lettdig));
                   7578: 
1.157     albertel 7579:     while ($i<$scanlines->{'count'}) {
                   7580:  	($uname,$udom)=('','');
                   7581:  	$i++;
1.200     albertel 7582:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7583:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7584: 	if ($started) {
                   7585: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7586: 						     'last student');
                   7587: 	}
                   7588: 	$started=1;
1.157     albertel 7589:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7590:  						 $scan_data);
                   7591:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7592:  					      \%idmap,$i)) {
                   7593:   	    &scantron_add_delay(\@delayqueue,$line,
                   7594:  				'Unable to find a student that matches',1);
                   7595:  	    next;
                   7596:   	}
                   7597:  	if (exists $completedstudents{$uname}) {
                   7598:  	    &scantron_add_delay(\@delayqueue,$line,
                   7599:  				'Student '.$uname.' has multiple sheets',2);
                   7600:  	    next;
                   7601:  	}
                   7602:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7603: 
                   7604: 	&Apache::lonxml::clear_problem_counter();
1.514     raeburn  7605:   	&Apache::lonnet::appenv($scan_record);
1.376     albertel 7606: 
                   7607: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7608: 	    &scantron_putfile($scanlines,$scan_data);
                   7609: 	}
1.513     foxr     7610: 
1.528.2.4  raeburn  7611:         my $scancode;
                   7612:         if ((exists($scan_record->{'scantron.CODE'})) &&
                   7613:             (&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'}))) {
                   7614:             $scancode = $scan_record->{'scantron.CODE'};
                   7615:         } else {
                   7616:             $scancode = '';
                   7617:         }
                   7618: 
                   7619:         if (&grade_student_bubbles($r,$uname,$udom,$scan_record,$scancode,
                   7620:                                    @resources) eq 'ssi_error') {
                   7621:             $ssi_error = 0; # So end of handler error message does not trigger.
                   7622:             $r->print("</form>");
                   7623:             &ssi_print_error($r);
                   7624:             $r->print(&show_grading_menu_form($symb));
                   7625:             &Apache::lonnet::remove_lock($lock);
                   7626:             return '';      # Why return ''?  Beats me.
                   7627:         }
                   7628: 
1.140     albertel 7629: 	$completedstudents{$uname}={'line'=>$line};
1.528.2.4  raeburn  7630:         if ($env{'form.verifyrecord'}) {
                   7631:             my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7632:             my $studentdata = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7633:             chomp($studentdata);
                   7634:             $studentdata =~ s/\r$//;
                   7635:             my $studentrecord = '';
                   7636:             my $counter = -1;
                   7637:             foreach my $resource (@resources) {
                   7638:                 ($counter,my $recording) =
                   7639:                     &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
                   7640:                                              $counter,$studentdata,\%partids_by_symb,
                   7641:                                              \%scantron_config,\%lettdig,$numletts);
                   7642:                 $studentrecord .= $recording;
                   7643:             }
                   7644:             if ($studentrecord ne $studentdata) {
                   7645:                 $counter = -1;
                   7646:                 $studentrecord = '';
                   7647:                 foreach my $resource (@resources) {
                   7648:                     ($counter,my $recording) =
                   7649:                         &verify_scantron_grading($resource,$udom,$uname,$env{'request.course.id'},
                   7650:                                                  $counter,$studentdata,\%partids_by_symb,
                   7651:                                                  \%scantron_config,\%lettdig,$numletts);
                   7652:                     $studentrecord .= $recording;
                   7653:                 }
                   7654:                 if ($studentrecord ne $studentdata) {
                   7655:                     $r->print('<p><span class="LC_error">');
                   7656:                     if ($scancode eq '') {
                   7657:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2].',
                   7658:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'}));
                   7659:                     } else {
                   7660:                         $r->print(&mt('Mismatch grading bubble sheet for user: [_1] with ID: [_2] and CODE: [_3].',
                   7661:                                   $uname.':'.$udom,$scan_record->{'scantron.ID'},$scancode));
                   7662:                     }
                   7663:                     $r->print('</span><br />'.&Apache::loncommon::start_data_table()."\n".
                   7664:                               &Apache::loncommon::start_data_table_header_row()."\n".
                   7665:                               '<th>'.&mt('Source').'</th><th>'.&mt('Bubbled responses').'</th>'.
                   7666:                               &Apache::loncommon::end_data_table_header_row()."\n".
                   7667:                               &Apache::loncommon::start_data_table_row().
                   7668:                               '<td>'.&mt('Bubble Sheet').'</td>'.
                   7669:                               '<td><span class="LC_nobreak">'.$studentdata.'</span></td>'.
                   7670:                               &Apache::loncommon::end_data_table_row().
                   7671:                               &Apache::loncommon::start_data_table_row().
                   7672:                               '<td>Stored submissions</td>'.
                   7673:                               '<td><span class="LC_nobreak">'.$studentrecord.'</span></td>'."\n".
                   7674:                               &Apache::loncommon::end_data_table_row().
                   7675:                               &Apache::loncommon::end_data_table().'</p>');
                   7676:                 } else {
                   7677:                     $r->print('<br /><span class="LC_warning">'.
                   7678:                              &mt('A second grading pass was needed for user: [_1] with ID: [_2], because a mismatch was seen on the first pass.',$uname.':'.$udom,$scan_record->{'scantron.ID'}).'<br />'.
                   7679:                              &mt("As a consequence, this user's submission history records two tries.").
                   7680:                                  '</span><br />');
                   7681:                 }
                   7682:             }
                   7683:         }
1.213     albertel 7684: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7685:     } continue {
1.330     albertel 7686: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7687: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7688:     }
1.140     albertel 7689:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.520     www      7690:     &Apache::lonnet::remove_lock($lock);
1.172     albertel 7691: #    my $lasttime = &Time::HiRes::time()-$start;
                   7692: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7693: 
1.200     albertel 7694:     $r->print("</form>");
1.324     albertel 7695:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7696:     return '';
1.75      albertel 7697: }
1.157     albertel 7698: 
1.528.2.4  raeburn  7699: sub grade_student_bubbles {
                   7700:     my ($r,$uname,$udom,$scan_record,$scancode,@resources) = @_;
                   7701:     foreach my $resource (@resources) {
                   7702:         my %form = ('submitted'     => 'scantron',
                   7703:                     'grade_target'  => 'grade',
                   7704:                     'grade_username'=> $uname,
                   7705:                     'grade_domain'  => $udom,
                   7706:                     'grade_courseid'=> $env{'request.course.id'},
                   7707:                     'grade_symb'    => $resource->symb(),
                   7708:                     'code'          => $scancode);
                   7709:         my $result=&ssi_with_retries($resource->src(),$ssi_retries,%form);
                   7710:         return 'ssi_error' if ($ssi_error);
                   7711:         last if (&Apache::loncommon::connection_aborted($r));
                   7712:     }
                   7713:     return;
                   7714: }
                   7715: 
1.423     albertel 7716: =pod
                   7717: 
                   7718: =item scantron_upload_scantron_data
                   7719: 
                   7720:     Creates the screen for adding a new bubble sheet data file to a course.
                   7721: 
                   7722: =cut
                   7723: 
1.157     albertel 7724: sub scantron_upload_scantron_data {
                   7725:     my ($r)=@_;
1.257     albertel 7726:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7727:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7728: 							  'domainid',
                   7729: 							  'coursename');
1.257     albertel 7730:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7731: 						   'domainid');
1.324     albertel 7732:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7733:     $r->print('
1.157     albertel 7734: <script type="text/javascript" language="javascript">
                   7735:     function checkUpload(formname) {
                   7736: 	if (formname.upfile.value == "") {
                   7737: 	    alert("Please use the browse button to select a file from your local directory.");
                   7738: 	    return false;
                   7739: 	}
                   7740: 	formname.submit();
                   7741:     }
                   7742: </script>
                   7743: 
1.492     albertel 7744: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7745: '.$default_form_data.'
1.181     albertel 7746: <table>
1.492     albertel 7747: <tr><td>'.$select_link.'                             </td></tr>
                   7748: <tr><td>'.&mt('Course ID:').'     </td>
                   7749:     <td><input name="courseid"   type="text" />      </td></tr>
                   7750: <tr><td>'.&mt('Course Name:').'   </td>
                   7751:     <td><input name="coursename" type="text" />      </td></tr>
                   7752: <tr><td>'.&mt('Domain:').'        </td>
                   7753:     <td>'.$domsel.'                                  </td></tr>
                   7754: <tr><td>'.&mt('File to upload:').'</td>
                   7755:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7756: </table>
1.492     albertel 7757: <input name="command" value="scantronupload_save" type="hidden" />
                   7758: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7759: </form>
1.492     albertel 7760: ');
1.157     albertel 7761:     return '';
                   7762: }
                   7763: 
1.423     albertel 7764: =pod
                   7765: 
                   7766: =item scantron_upload_scantron_data_save
                   7767: 
                   7768:    Adds a provided bubble information data file to the course if user
                   7769:    has the correct privileges to do so.  
                   7770: 
                   7771: =cut
                   7772: 
1.157     albertel 7773: sub scantron_upload_scantron_data_save {
                   7774:     my($r)=@_;
1.324     albertel 7775:     my ($symb)=&get_symb($r,1);
1.182     albertel 7776:     my $doanotherupload=
                   7777: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7778: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7779: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7780: 	'</form>'."\n";
1.257     albertel 7781:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7782: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7783: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7784: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7785: 	if ($symb) {
1.324     albertel 7786: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7787: 	} else {
                   7788: 	    $r->print($doanotherupload);
                   7789: 	}
1.162     albertel 7790: 	return '';
                   7791:     }
1.257     albertel 7792:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7793:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7794:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7795:     #FIXME
                   7796:     #copied from lonnet::userfileupload()
                   7797:     #make that function able to target a specified course
                   7798:     # Replace Windows backslashes by forward slashes
                   7799:     $fname=~s/\\/\//g;
                   7800:     # Get rid of everything but the actual filename
                   7801:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7802:     # Replace spaces by underscores
                   7803:     $fname=~s/\s+/\_/g;
                   7804:     # Replace all other weird characters by nothing
                   7805:     $fname=~s/[^\w\.\-]//g;
                   7806:     # See if there is anything left
                   7807:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7808:     my $uploadedfile=$fname;
1.157     albertel 7809:     $fname='scantron_orig_'.$fname;
1.257     albertel 7810:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7811: 	$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 7812:     } else {
1.275     albertel 7813: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7814: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7815: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7816: 			  (length($env{'form.upfile'})-1),
                   7817: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7818: 	} else {
1.492     albertel 7819: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7820: 			  $result,
                   7821: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7822: 
1.183     albertel 7823: 	}
                   7824:     }
1.174     albertel 7825:     if ($symb) {
1.209     ng       7826: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7827:     } else {
1.182     albertel 7828: 	$r->print($doanotherupload);
1.174     albertel 7829:     }
1.157     albertel 7830:     return '';
                   7831: }
                   7832: 
1.423     albertel 7833: =pod
                   7834: 
                   7835: =item valid_file
                   7836: 
1.424     albertel 7837:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7838: 
                   7839: =cut
                   7840: 
1.202     albertel 7841: sub valid_file {
                   7842:     my ($requested_file)=@_;
                   7843:     foreach my $filename (sort(&scantron_filenames())) {
                   7844: 	if ($requested_file eq $filename) { return 1; }
                   7845:     }
                   7846:     return 0;
                   7847: }
                   7848: 
1.423     albertel 7849: =pod
                   7850: 
                   7851: =item scantron_download_scantron_data
                   7852: 
                   7853:    Shows a list of the three internal files (original, corrected,
                   7854:    skipped) for a specific bubble sheet data file that exists in the
                   7855:    course.
                   7856: 
                   7857: =cut
                   7858: 
1.202     albertel 7859: sub scantron_download_scantron_data {
                   7860:     my ($r)=@_;
1.324     albertel 7861:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7862:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7863:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7864:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7865:     if (! &valid_file($file)) {
1.492     albertel 7866: 	$r->print('
1.202     albertel 7867: 	<p>
1.492     albertel 7868: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7869:         </p>
1.492     albertel 7870: ');
1.324     albertel 7871: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7872: 	return;
                   7873:     }
                   7874:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7875:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7876:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7877:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7878:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7879:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7880:     $r->print('
1.202     albertel 7881:     <p>
1.492     albertel 7882: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7883: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7884:     </p>
                   7885:     <p>
1.492     albertel 7886: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7887: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7888:     </p>
                   7889:     <p>
1.492     albertel 7890: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7891: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7892:     </p>
1.492     albertel 7893: ');
1.324     albertel 7894:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7895:     return '';
                   7896: }
1.157     albertel 7897: 
1.523     raeburn  7898: sub checkscantron_results {
                   7899:     my ($r) = @_;
                   7900:     my ($symb)=&get_symb($r);
                   7901:     if (!$symb) {return '';}
                   7902:     my $grading_menu_button=&show_grading_menu_form($symb);
                   7903:     my $cid = $env{'request.course.id'};
1.528.2.4  raeburn  7904:     my %lettdig = &letter_to_digits();
1.523     raeburn  7905:     my $numletts = scalar(keys(%lettdig));
                   7906:     my $cnum = $env{'course.'.$cid.'.num'};
                   7907:     my $cdom = $env{'course.'.$cid.'.domain'};
                   7908:     my (undef, undef, $sequence) = &Apache::lonnet::decode_symb($env{'form.selectpage'});
                   7909:     my %record;
                   7910:     my %scantron_config =
                   7911:         &Apache::grades::get_scantron_config($env{'form.scantron_format'});
                   7912:     my ($scanlines,$scan_data)=&Apache::grades::scantron_getfile();
                   7913:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7914:     my %idmap=&Apache::grades::username_to_idmap($classlist);
                   7915:     my $navmap=Apache::lonnavmaps::navmap->new();
                   7916:     my $map=$navmap->getResourceByUrl($sequence);
                   7917:     my @resources=$navmap->retrieveResources($map,undef,1,0);
1.528.2.4  raeburn  7918:     my ($uname,$udom,%partids_by_symb);
                   7919:     foreach my $resource (@resources) {
                   7920:         my $ressymb = $resource->symb();
                   7921:         my ($analysis,$parts) =
                   7922:             &scantron_partids_tograde($resource,$env{'request.course.id'},$uname,$udom);
                   7923:         $partids_by_symb{$ressymb} = $parts;
                   7924:     }
1.523     raeburn  7925:     my (%scandata,%lastname,%bylast);
                   7926:     $r->print('
                   7927: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="checkscantron">'."\n");
                   7928: 
                   7929:     my @delayqueue;
                   7930:     my %completedstudents;
                   7931: 
                   7932:     my $count=&Apache::grades::get_todo_count($scanlines,$scan_data);
                   7933:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron/Submissions Comparison Status',
                   7934:                                     'Progress of Scantron Data/Submission Records Comparison',$count,
                   7935:                                     'inline',undef,'checkscantron');
1.528.2.8! raeburn  7936:     my ($username,$domain,$started);
1.523     raeburn  7937: 
                   7938:     &Apache::grades::scantron_get_maxbubble();  # Need the bubble lines array to parse.
                   7939: 
                   7940:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7941:                                           'Processing first student');
                   7942:     my $start=&Time::HiRes::time();
                   7943:     my $i=-1;
                   7944: 
                   7945:     while ($i<$scanlines->{'count'}) {
                   7946:         ($username,$domain,$uname)=('','','');
                   7947:         $i++;
                   7948:         my $line=&Apache::grades::scantron_get_line($scanlines,$scan_data,$i);
                   7949:         if ($line=~/^[\s\cz]*$/) { next; }
                   7950:         if ($started) {
                   7951:             &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7952:                                                      'last student');
                   7953:         }
                   7954:         $started=1;
                   7955:         my $scan_record=
                   7956:             &Apache::grades::scantron_parse_scanline($line,$i,\%scantron_config,
                   7957:                                                      $scan_data);
                   7958:         unless ($uname=&Apache::grades::scantron_find_student($scan_record,$scan_data,
                   7959:                                                               \%idmap,$i)) {
                   7960:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7961:                                 'Unable to find a student that matches',1);
                   7962:             next;
                   7963:         }
                   7964:         if (exists $completedstudents{$uname}) {
                   7965:             &Apache::grades::scantron_add_delay(\@delayqueue,$line,
                   7966:                                 'Student '.$uname.' has multiple sheets',2);
                   7967:             next;
                   7968:         }
                   7969:         my $pid = $scan_record->{'scantron.ID'};
                   7970:         $lastname{$pid} = $scan_record->{'scantron.LastName'};
                   7971:         push(@{$bylast{$lastname{$pid}}},$pid);
                   7972:         my $lastpos = $env{'form.scantron_maxbubble'}*$scantron_config{'Qlength'};
                   7973:         $scandata{$pid} = substr($line,$scantron_config{'Qstart'}-1,$lastpos);
                   7974:         chomp($scandata{$pid});
                   7975:         $scandata{$pid} =~ s/\r$//;
                   7976:         ($username,$domain)=split(/:/,$uname);
                   7977:         my $counter = -1;
                   7978:         foreach my $resource (@resources) {
1.528.2.4  raeburn  7979:             ($counter,my $recording) =
                   7980:                 &verify_scantron_grading($resource,$domain,$username,$cid,$counter,
                   7981:                                          $scandata{$pid},\%partids_by_symb,
                   7982:                                          \%scantron_config,\%lettdig,$numletts);
                   7983:             $record{$pid} .= $recording;
1.523     raeburn  7984:         }
                   7985:     }
                   7986:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   7987:     $r->print('<br />');
                   7988:     my ($okstudents,$badstudents,$numstudents,$passed,$failed);
                   7989:     $passed = 0;
                   7990:     $failed = 0;
                   7991:     $numstudents = 0;
                   7992:     foreach my $last (sort(keys(%bylast))) {
                   7993:         if (ref($bylast{$last}) eq 'ARRAY') {
                   7994:             foreach my $pid (sort(@{$bylast{$last}})) {
                   7995:                 my $showscandata = $scandata{$pid};
                   7996:                 my $showrecord = $record{$pid};
                   7997:                 $showscandata =~ s/\s/&nbsp;/g;
                   7998:                 $showrecord =~ s/\s/&nbsp;/g;
                   7999:                 if ($scandata{$pid} eq $record{$pid}) {
                   8000:                     my $css_class = ($passed % 2)?'LC_odd_row':'LC_even_row';
                   8001:                     $okstudents .= '<tr class="'.$css_class.'">'.
                   8002: '<td>'.&mt('Scantron').'</td><td>'.$showscandata.'</td><td rowspan="2">'.$last.'</td><td rowspan="2">'.$pid.'</td>'."\n".
                   8003: '</tr>'."\n".
                   8004: '<tr class="'.$css_class.'">'."\n".
                   8005: '<td>Submissions</td><td>'.$showrecord.'</td></tr>'."\n";
                   8006:                     $passed ++;
                   8007:                 } else {
                   8008:                     my $css_class = ($failed % 2)?'LC_odd_row':'LC_even_row';
                   8009:                     $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".
                   8010: '</tr>'."\n".
                   8011: '<tr class="'.$css_class.'">'."\n".
                   8012: '<td>Submissions</td><td><span class="LC_nobreak">'.$record{$pid}.'</span></td>'."\n".
                   8013: '</tr>'."\n";
                   8014:                     $failed ++;
                   8015:                 }
                   8016:                 $numstudents ++;
                   8017:             }
                   8018:         }
                   8019:     }
                   8020:     $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>');
                   8021:     $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>');
                   8022:     if ($passed) {
                   8023:         $r->print(&mt('Students with exact correspondence between scantron data and submissions are as follows:').'<br /><br />');
                   8024:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8025:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8026:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8027:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8028:                  $okstudents."\n".
                   8029:                  &Apache::loncommon::end_data_table().'<br />');
                   8030:     }
                   8031:     if ($failed) {
                   8032:         $r->print(&mt('Students with differences between scantron data and submissions are as follows:').'<br /><br />');
                   8033:         $r->print(&Apache::loncommon::start_data_table()."\n".
                   8034:                  &Apache::loncommon::start_data_table_header_row()."\n".
                   8035:                  '<th>'.&mt('Source').'</th><th>'.&mt('Bubble records').'</th><th>'.&mt('Name').'</th><th>'.&mt('ID').'</th>'.
                   8036:                  &Apache::loncommon::end_data_table_header_row()."\n".
                   8037:                  $badstudents."\n".
                   8038:                  &Apache::loncommon::end_data_table()).'<br />'.
                   8039:                  &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.');  
                   8040:     }
                   8041:     $r->print('</form><br />'.$grading_menu_button);
                   8042:     return;
                   8043: }
                   8044: 
1.528.2.4  raeburn  8045: sub verify_scantron_grading {
                   8046:     my ($resource,$domain,$username,$cid,$counter,$scandata,$partids_by_symb,
                   8047:         $scantron_config,$lettdig,$numletts) = @_;
                   8048:     my ($record,%expected,%startpos);
                   8049:     return ($counter,$record) if (!ref($resource));
                   8050:     return ($counter,$record) if (!$resource->is_problem());
                   8051:     my $symb = $resource->symb();
                   8052:     return ($counter,$record) if (ref($partids_by_symb) ne 'HASH');
                   8053:     return ($counter,$record) if (ref($partids_by_symb->{$symb}) ne 'ARRAY');
                   8054:     foreach my $part_id (@{$partids_by_symb->{$symb}}) {
                   8055:         $counter ++;
                   8056:         $expected{$part_id} = 0;
                   8057:         if ($env{"form.scantron.sub_bubblelines.$counter"}) {
                   8058:             my @sub_lines = split(/,/,$env{"form.scantron.sub_bubblelines.$counter"});
                   8059:             foreach my $item (@sub_lines) {
                   8060:                 $expected{$part_id} += $item;
                   8061:             }
                   8062:         } else {
                   8063:             $expected{$part_id} = $env{"form.scantron.bubblelines.$counter"};
                   8064:         }
                   8065:         $startpos{$part_id} = $env{"form.scantron.first_bubble_line.$counter"};
                   8066:     }
                   8067:     if ($symb) {
                   8068:         my %recorded;
                   8069:         my (%returnhash) = &Apache::lonnet::restore($symb,$cid,$domain,$username);
                   8070:         if ($returnhash{'version'}) {
                   8071:             my %lasthash=();
                   8072:             my $version;
                   8073:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   8074:                 foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   8075:                     $lasthash{$key}=$returnhash{$version.':'.$key};
                   8076:                 }
                   8077:             }
                   8078:             foreach my $key (keys(%lasthash)) {
                   8079:                 if ($key =~ /\.scantron$/) {
                   8080:                     my $value = &unescape($lasthash{$key});
                   8081:                     my ($part_id) = ($key =~ /^resource\.(.+)\.scantron$/);
                   8082:                     if ($value eq '') {
                   8083:                         for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8084:                             for (my $j=0; $j<$scantron_config->{'length'}; $j++) {
                   8085:                                 $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8086:                             }
                   8087:                         }
                   8088:                     } else {
                   8089:                         my @tocheck;
                   8090:                         my @items = split(//,$value);
                   8091:                         if (($scantron_config->{'Qon'} eq 'letter') ||
                   8092:                             ($scantron_config->{'Qon'} eq 'number')) {
                   8093:                             if (@items < $expected{$part_id}) {
                   8094:                                 my $fragment = substr($scandata,$startpos{$part_id},$expected{$part_id});
                   8095:                                 my @singles = split(//,$fragment);
                   8096:                                 foreach my $pos (@singles) {
                   8097:                                     if ($pos eq ' ') {
                   8098:                                         push(@tocheck,$pos);
                   8099:                                     } else {
                   8100:                                         my $next = shift(@items);
                   8101:                                         push(@tocheck,$next);
                   8102:                                     }
                   8103:                                 }
                   8104:                             } else {
                   8105:                                 @tocheck = @items;
                   8106:                             }
                   8107:                             foreach my $letter (@tocheck) {
                   8108:                                 if ($scantron_config->{'Qon'} eq 'letter') {
                   8109:                                     if ($letter !~ /^[A-J]$/) {
                   8110:                                         $letter = $scantron_config->{'Qoff'};
                   8111:                                     }
                   8112:                                     $recorded{$part_id} .= $letter;
                   8113:                                 } elsif ($scantron_config->{'Qon'} eq 'number') {
                   8114:                                     my $digit;
                   8115:                                     if ($letter !~ /^[A-J]$/) {
                   8116:                                         $digit = $scantron_config->{'Qoff'};
                   8117:                                     } else {
                   8118:                                         $digit = $lettdig->{$letter};
                   8119:                                     }
                   8120:                                     $recorded{$part_id} .= $digit;
                   8121:                                 }
                   8122:                             }
                   8123:                         } else {
                   8124:                             @tocheck = @items;
                   8125:                             for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8126:                                 my $curr_sub = shift(@tocheck);
                   8127:                                 my $digit;
                   8128:                                 if ($curr_sub =~ /^[A-J]$/) {
                   8129:                                     $digit = $lettdig->{$curr_sub}-1;
                   8130:                                 }
                   8131:                                 if ($curr_sub eq 'J') {
                   8132:                                     $digit += scalar($numletts);
                   8133:                                 }
                   8134:                                 for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8135:                                     if ($j == $digit) {
                   8136:                                         $recorded{$part_id} .= $scantron_config->{'Qon'};
                   8137:                                     } else {
                   8138:                                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8139:                                     }
                   8140:                                 }
                   8141:                             }
                   8142:                         }
                   8143:                     }
                   8144:                 }
                   8145:             }
                   8146:         }
                   8147:         foreach my $part_id (@{$partids_by_symb->{$symb}}) {
                   8148:             if ($recorded{$part_id} eq '') {
                   8149:                 for (my $i=0; $i<$expected{$part_id}; $i++) {
                   8150:                     for (my $j=0; $j<$scantron_config->{'Qlength'}; $j++) {
                   8151:                         $recorded{$part_id} .= $scantron_config->{'Qoff'};
                   8152:                     }
                   8153:                 }
                   8154:             }
                   8155:             $record .= $recorded{$part_id};
                   8156:         }
                   8157:     }
                   8158:     return ($counter,$record);
                   8159: }
                   8160: 
                   8161: sub letter_to_digits {
                   8162:     my %lettdig = (
                   8163:                     A => 1,
                   8164:                     B => 2,
                   8165:                     C => 3,
                   8166:                     D => 4,
                   8167:                     E => 5,
                   8168:                     F => 6,
                   8169:                     G => 7,
                   8170:                     H => 8,
                   8171:                     I => 9,
                   8172:                     J => 0,
                   8173:                   );
                   8174:     return %lettdig;
                   8175: }
                   8176: 
1.423     albertel 8177: =pod
                   8178: 
                   8179: =back
                   8180: 
                   8181: =cut
                   8182: 
1.75      albertel 8183: #-------- end of section for handling grading scantron forms -------
                   8184: #
                   8185: #-------------------------------------------------------------------
                   8186: 
1.72      ng       8187: #-------------------------- Menu interface -------------------------
                   8188: #
                   8189: #--- Show a Grading Menu button - Calls the next routine ---
                   8190: sub show_grading_menu_form {
1.324     albertel 8191:     my ($symb)=@_;
1.125     ng       8192:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 8193: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 8194: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       8195: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 8196: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       8197: 	'</form>'."\n";
                   8198:     return $result;
                   8199: }
                   8200: 
1.77      ng       8201: # -- Retrieve choices for grading form
                   8202: sub savedState {
                   8203:     my %savedState = ();
1.257     albertel 8204:     if ($env{'form.saveState'}) {
                   8205: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       8206: 	    my ($key,$value) = split(/=/,$_,2);
                   8207: 	    $savedState{$key} = $value;
                   8208: 	}
                   8209:     }
                   8210:     return \%savedState;
                   8211: }
1.76      ng       8212: 
1.443     banghart 8213: sub grading_menu {
                   8214:     my ($request) = @_;
                   8215:     my ($symb)=&get_symb($request);
                   8216:     if (!$symb) {return '';}
                   8217:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   8218:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   8219: 
1.444     banghart 8220:     $request->print($table);
1.443     banghart 8221:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   8222:                   'handgrade'=>$hdgrade,
                   8223:                   'probTitle'=>$probTitle,
                   8224:                   'command'=>'submit_options',
                   8225:                   'saveState'=>"",
                   8226:                   'gradingMenu'=>1,
                   8227:                   'showgrading'=>"yes");
                   8228:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   8229:     my @menu = ({ url => $url,
                   8230:                      name => &mt('Manual Grading/View Submissions'),
                   8231:                      short_description => 
                   8232:     &mt('Start the process of hand grading submissions.'),
                   8233:                  });
                   8234:     $fields{'command'} = 'csvform';
                   8235:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8236:     push(@menu, { url => $url,
1.443     banghart 8237:                    name => &mt('Upload Scores'),
                   8238:                    short_description => 
                   8239:             &mt('Specify a file containing the class scores for current resource.')});
                   8240:     $fields{'command'} = 'processclicker';
                   8241:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8242:     push(@menu, { url => $url,
1.443     banghart 8243:                    name => &mt('Process Clicker'),
                   8244:                    short_description => 
                   8245:             &mt('Specify a file containing the clicker information for this resource.')});
                   8246:     $fields{'command'} = 'scantron_selectphase';
                   8247:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8248:     push(@menu, { url => $url,
1.523     raeburn  8249:                    name => &mt('Grade/Manage/Review Scantron Forms'),
1.454     banghart 8250:                    short_description => 
1.523     raeburn  8251:             &mt('Grade scantron exams, upload/download scantron data files, and review previously graded scantron exams.')});
1.443     banghart 8252:     $fields{'command'} = 'verify';
                   8253:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.524     raeburn  8254:     push(@menu, { url => "",
1.443     banghart 8255:                    name => &mt('Verify Receipt'),
                   8256:                    short_description => 
                   8257:             &mt('')});
                   8258:     #
                   8259:     # Create the menu
                   8260:     my $Str;
1.444     banghart 8261:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 8262:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   8263:     $Str .= '<input type="hidden" name="command" value="" />'.
                   8264:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   8265: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 8266: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 8267: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   8268: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   8269: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8270: 
1.443     banghart 8271:     foreach my $menudata (@menu) {
1.445     banghart 8272:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   8273:             $Str .='    <h3><a '.
                   8274:                 $menudata->{'jscript'}.
                   8275:                 ' href="'.
                   8276:                 $menudata->{'url'}.'" >'.
                   8277:                 $menudata->{'name'}."</a></h3>\n";
                   8278:         } else {
1.511     www      8279:             $Str .='<hr /><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 8280:                 $menudata->{'jscript'}.
1.458     banghart 8281:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
1.511     www      8282:                 ' /> '.
                   8283: 		&Apache::lonnet::recprefix($env{'request.course.id'}).
                   8284:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 8285:         }
1.443     banghart 8286:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   8287:             "\n";
                   8288:     }
1.444     banghart 8289:     $Str .="</form>\n";
1.443     banghart 8290:     $request->print(<<GRADINGMENUJS);
                   8291: <script type="text/javascript" language="javascript">
                   8292:     function checkChoice(formname,val,cmdx) {
                   8293: 	if (val <= 2) {
                   8294: 	    var cmd = radioSelection(formname.radioChoice);
                   8295: 	    var cmdsave = cmd;
                   8296: 	} else {
                   8297: 	    cmd = cmdx;
                   8298: 	    cmdsave = 'submission';
                   8299: 	}
                   8300: 	formname.command.value = cmd;
                   8301: 	if (val < 5) formname.submit();
                   8302: 	if (val == 5) {
1.458     banghart 8303: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   8304: 	        return false;
                   8305: 	    } else {
                   8306: 	        formname.submit();
                   8307: 	    }
1.445     banghart 8308: 	}
                   8309:     }
1.443     banghart 8310: 
                   8311:     function checkReceiptNo(formname,nospace) {
                   8312: 	var receiptNo = formname.receipt.value;
                   8313: 	var checkOpt = false;
                   8314: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8315: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8316: 	if (checkOpt) {
                   8317: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8318: 	    formname.receipt.value = "";
                   8319: 	    formname.receipt.focus();
                   8320: 	    return false;
                   8321: 	}
                   8322: 	return true;
                   8323:     }
                   8324: </script>
                   8325: GRADINGMENUJS
                   8326:     &commonJSfunctions($request);
                   8327:     return $Str;    
                   8328: }
                   8329: 
                   8330: 
                   8331: #--- Displays the submissions first page -------
                   8332: sub submit_options {
1.72      ng       8333:     my ($request) = @_;
1.324     albertel 8334:     my ($symb)=&get_symb($request);
1.72      ng       8335:     if (!$symb) {return '';}
1.76      ng       8336:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       8337: 
                   8338:     $request->print(<<GRADINGMENUJS);
                   8339: <script type="text/javascript" language="javascript">
1.116     ng       8340:     function checkChoice(formname,val,cmdx) {
                   8341: 	if (val <= 2) {
                   8342: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       8343: 	    var cmdsave = cmd;
1.116     ng       8344: 	} else {
                   8345: 	    cmd = cmdx;
1.118     ng       8346: 	    cmdsave = 'submission';
1.116     ng       8347: 	}
                   8348: 	formname.command.value = cmd;
1.118     ng       8349: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 8350: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       8351: 	if (val < 5) formname.submit();
                   8352: 	if (val == 5) {
1.72      ng       8353: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   8354: 	    formname.submit();
                   8355: 	}
1.238     albertel 8356: 	if (val < 7) formname.submit();
1.72      ng       8357:     }
                   8358: 
                   8359:     function checkReceiptNo(formname,nospace) {
                   8360: 	var receiptNo = formname.receipt.value;
                   8361: 	var checkOpt = false;
                   8362: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   8363: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   8364: 	if (checkOpt) {
                   8365: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   8366: 	    formname.receipt.value = "";
                   8367: 	    formname.receipt.focus();
                   8368: 	    return false;
                   8369: 	}
                   8370: 	return true;
                   8371:     }
                   8372: </script>
                   8373: GRADINGMENUJS
1.118     ng       8374:     &commonJSfunctions($request);
1.324     albertel 8375:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 8376:     my $result;
1.76      ng       8377:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       8378:     my $savedState = &savedState();
1.118     ng       8379:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       8380:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       8381:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       8382:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       8383: 
                   8384:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 8385: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       8386: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   8387: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       8388: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       8389: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       8390: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       8391: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   8392: 
1.472     albertel 8393:     $result.='
                   8394:     <div class="LC_grade_select_mode">
1.473     albertel 8395:       <div class="LC_grade_select_mode_current">
                   8396:         <h2>
                   8397:           '.&mt('Grade Current Resource').'
                   8398:         </h2>
                   8399:         <div class="LC_grade_select_mode_body">
                   8400:           <div class="LC_grades_resource_info">
                   8401:            '.$table.'
                   8402:           </div>
                   8403:           <div class="LC_grade_select_mode_selector">
                   8404:              <div class="LC_grade_select_mode_selector_header">
                   8405:                 '.&mt('Sections').'
                   8406:              </div>
                   8407:              <div class="LC_grade_select_mode_selector_body">
                   8408: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       8409:     if (ref($sections)) {
1.524     raeburn  8410: 	foreach my $section (sort(@$sections)) {
1.472     albertel 8411: 	    $result.='<option value="'.$section.'" '.
                   8412: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 8413: 	}
1.116     ng       8414:     }
1.401     albertel 8415:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 8416:     $result.='
1.473     albertel 8417:              </div>
                   8418:           </div>
                   8419:           <div class="LC_grade_select_mode_selector">
                   8420:              <div class="LC_grade_select_mode_selector_header">
                   8421:                 '.&mt('Groups').'
                   8422:              </div>
                   8423:              <div class="LC_grade_select_mode_selector_body">
                   8424:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   8425:              </div>
1.472     albertel 8426:           </div>
1.473     albertel 8427:           <div class="LC_grade_select_mode_selector">
                   8428:              <div class="LC_grade_select_mode_selector_header">
                   8429:                 '.&mt('Access Status').'
                   8430:              </div>
                   8431:              <div class="LC_grade_select_mode_selector_body">
                   8432:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   8433:              </div>
1.472     albertel 8434:           </div>
1.473     albertel 8435:           <div class="LC_grade_select_mode_selector">
                   8436:              <div class="LC_grade_select_mode_selector_header">
                   8437:                 '.&mt('Submission Status').'
                   8438:              </div>
                   8439:              <div class="LC_grade_select_mode_selector_body">
                   8440:                <select name="submitonly" size="5">
                   8441: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   8442: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   8443: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   8444: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   8445:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   8446:                </select>
                   8447:              </div>
1.472     albertel 8448:           </div>
1.473     albertel 8449:           <div class="LC_grade_select_mode_type_body">
                   8450:             <div class="LC_grade_select_mode_type">
                   8451:               <label>
                   8452:                 <input type="radio" name="radioChoice" value="submission" '.
                   8453:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   8454:              &mt('Select individual students to grade and view submissions.').'
                   8455: 	      </label> 
                   8456:             </div>
                   8457:             <div class="LC_grade_select_mode_type">
                   8458: 	      <label>
                   8459:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   8460:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   8461:                     &mt('Grade all selected students in a grading table.').'
                   8462:               </label>
                   8463:             </div>
                   8464:             <div class="LC_grade_select_mode_type">
                   8465: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8466:             </div>
1.472     albertel 8467:           </div>
1.473     albertel 8468:         </div>
                   8469:       </div>
                   8470:       <div class="LC_grade_select_mode_page">
                   8471:         <h2>
                   8472:          '.&mt('Grade Complete Folder for One Student').'
                   8473:         </h2>
                   8474:         <div class="LC_grades_select_mode_body">
                   8475:           <div class="LC_grade_select_mode_type_body">
                   8476:             <div class="LC_grade_select_mode_type">
                   8477:               <label>
                   8478:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   8479: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   8480:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   8481:               </label>
                   8482:             </div>
                   8483:             <div class="LC_grade_select_mode_type">
                   8484: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   8485:             </div>
1.472     albertel 8486:           </div>
                   8487:         </div>
                   8488:       </div>
                   8489:     </div>
                   8490:   </form>';
1.499     albertel 8491:     $result .= &show_grading_menu_form($symb);
1.44      ng       8492:     return $result;
1.2       albertel 8493: }
                   8494: 
1.285     albertel 8495: sub reset_perm {
                   8496:     undef(%perm);
                   8497: }
                   8498: 
                   8499: sub init_perm {
                   8500:     &reset_perm();
1.300     albertel 8501:     foreach my $test_perm ('vgr','mgr','opa') {
                   8502: 
                   8503: 	my $scope = $env{'request.course.id'};
                   8504: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   8505: 
                   8506: 	    $scope .= '/'.$env{'request.course.sec'};
                   8507: 	    if ( $perm{$test_perm}=
                   8508: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   8509: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   8510: 	    } else {
                   8511: 		delete($perm{$test_perm});
                   8512: 	    }
1.285     albertel 8513: 	}
                   8514:     }
                   8515: }
                   8516: 
1.400     www      8517: sub gather_clicker_ids {
1.408     albertel 8518:     my %clicker_ids;
1.400     www      8519: 
                   8520:     my $classlist = &Apache::loncoursedata::get_classlist();
                   8521: 
                   8522:     # Set up a couple variables.
1.407     albertel 8523:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   8524:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      8525:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      8526: 
1.407     albertel 8527:     foreach my $student (keys(%$classlist)) {
1.438     www      8528:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 8529:         my $username = $classlist->{$student}->[$username_idx];
                   8530:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      8531:         my $clickers =
1.408     albertel 8532: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      8533:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      8534:             $id=~s/^[\#0]+//;
1.421     www      8535:             $id=~s/[\-\:]//g;
1.407     albertel 8536:             if (exists($clicker_ids{$id})) {
1.408     albertel 8537: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      8538:             } else {
1.408     albertel 8539: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      8540:             }
                   8541:         }
                   8542:     }
1.407     albertel 8543:     return %clicker_ids;
1.400     www      8544: }
                   8545: 
1.402     www      8546: sub gather_adv_clicker_ids {
1.408     albertel 8547:     my %clicker_ids;
1.402     www      8548:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8549:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   8550:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 8551:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      8552:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   8553:             my ($puname,$pudom)=split(/\:/,$person);
                   8554:             my $clickers =
1.408     albertel 8555: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      8556:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      8557: 		$id=~s/^[\#0]+//;
1.421     www      8558:                 $id=~s/[\-\:]//g;
1.408     albertel 8559: 		if (exists($clicker_ids{$id})) {
                   8560: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   8561: 		} else {
                   8562: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   8563: 		}
1.405     www      8564:             }
1.402     www      8565:         }
                   8566:     }
1.407     albertel 8567:     return %clicker_ids;
1.402     www      8568: }
                   8569: 
1.413     www      8570: sub clicker_grading_parameters {
                   8571:     return ('gradingmechanism' => 'scalar',
                   8572:             'upfiletype' => 'scalar',
                   8573:             'specificid' => 'scalar',
                   8574:             'pcorrect' => 'scalar',
                   8575:             'pincorrect' => 'scalar');
                   8576: }
                   8577: 
1.400     www      8578: sub process_clicker {
                   8579:     my ($r)=@_;
                   8580:     my ($symb)=&get_symb($r);
                   8581:     if (!$symb) {return '';}
                   8582:     my $result=&checkforfile_js();
                   8583:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   8584:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   8585:     $result.=$table;
                   8586:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   8587:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   8588:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   8589:         '.</b></td></tr>'."\n";
                   8590:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      8591: # Attempt to restore parameters from last session, set defaults if not present
                   8592:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8593:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   8594:                                                  \%Saveable_Parameters);
                   8595:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   8596:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   8597:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   8598:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   8599: 
                   8600:     my %checked;
1.521     www      8601:     foreach my $gradingmechanism ('attendance','personnel','specific','given') {
1.413     www      8602:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   8603:           $checked{$gradingmechanism}="checked='checked'";
                   8604:        }
                   8605:     }
                   8606: 
1.400     www      8607:     my $upload=&mt("Upload File");
                   8608:     my $type=&mt("Type");
1.402     www      8609:     my $attendance=&mt("Award points just for participation");
                   8610:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      8611:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.521     www      8612:     my $given=&mt("Correctness determined from given list of answers").' '.
                   8613:               '<font size="-2"><tt>('.&mt("Provide comma-separated list. Use '*' for any answer correct, '-' for skip").')</tt></font>';
1.402     www      8614:     my $pcorrect=&mt("Percentage points for correct solution");
                   8615:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      8616:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      8617: 						   ('iclicker' => 'i>clicker',
                   8618:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 8619:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      8620:     $result.=<<ENDUPFORM;
1.402     www      8621: <script type="text/javascript">
                   8622: function sanitycheck() {
                   8623: // Accept only integer percentages
                   8624:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   8625:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   8626: // Find out grading choice
                   8627:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8628:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   8629:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   8630:       }
                   8631:    }
                   8632: // By default, new choice equals user selection
                   8633:    newgradingchoice=gradingchoice;
                   8634: // Not good to give more points for false answers than correct ones
                   8635:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   8636:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   8637:    }
                   8638: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   8639:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   8640:       document.forms.gradesupload.pcorrect.value=100;
                   8641:       document.forms.gradesupload.pincorrect.value=100;
                   8642:    }
                   8643: // If the values are different, cannot be attendance only
                   8644:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   8645:        (gradingchoice=='attendance')) {
                   8646:        newgradingchoice='personnel';
                   8647:    }
                   8648: // Change grading choice to new one
                   8649:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   8650:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   8651:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   8652:       } else {
                   8653:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   8654:       }
                   8655:    }
                   8656: // Remember the old state
                   8657:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   8658: }
                   8659: </script>
1.400     www      8660: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   8661: <input type="hidden" name="symb" value="$symb" />
                   8662: <input type="hidden" name="command" value="processclickerfile" />
                   8663: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8664: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   8665: <input type="file" name="upfile" size="50" />
                   8666: <br /><label>$type: $selectform</label>
1.451     albertel 8667: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   8668: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   8669: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      8670: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.521     www      8671: <br /><label><input type="radio" name="gradingmechanism" value="given" $checked{'given'} onClick="sanitycheck()" />$given </label>
                   8672: <br />&nbsp;&nbsp;&nbsp;
                   8673: <input type="text" name="givenanswer" size="50" />
1.413     www      8674: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   8675: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   8676: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      8677: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   8678: </form>
                   8679: ENDUPFORM
                   8680:     $result.='</td></tr></table>'."\n".
                   8681:              '</td></tr></table><br /><br />'."\n";
                   8682:     $result.=&show_grading_menu_form($symb);
                   8683:     return $result;
                   8684: }
                   8685: 
                   8686: sub process_clicker_file {
                   8687:     my ($r)=@_;
                   8688:     my ($symb)=&get_symb($r);
                   8689:     if (!$symb) {return '';}
1.413     www      8690: 
                   8691:     my %Saveable_Parameters=&clicker_grading_parameters();
                   8692:     &Apache::loncommon::store_course_settings('grades_clicker',
                   8693:                                               \%Saveable_Parameters);
                   8694: 
1.400     www      8695:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      8696:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 8697: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   8698: 	return $result.&show_grading_menu_form($symb);
1.404     www      8699:     }
1.522     www      8700:     if (($env{'form.gradingmechanism'} eq 'given') && ($env{'form.givenanswer'}!~/\S/)) {
1.521     www      8701:         $result.='<span class="LC_error">'.&mt('You need to specify the correct answer').'</span>';
                   8702:         return $result.&show_grading_menu_form($symb);
                   8703:     }
1.522     www      8704:     my $foundgiven=0;
1.521     www      8705:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8706:         $env{'form.givenanswer'}=~s/^\s*//gs;
                   8707:         $env{'form.givenanswer'}=~s/\s*$//gs;
                   8708:         $env{'form.givenanswer'}=~s/[^a-zA-Z0-9\.\*\-]+/\,/g;
                   8709:         $env{'form.givenanswer'}=uc($env{'form.givenanswer'});
1.522     www      8710:         my @answers=split(/\,/,$env{'form.givenanswer'});
                   8711:         $foundgiven=$#answers+1;
1.521     www      8712:     }
1.407     albertel 8713:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 8714:     my %correct_ids;
1.404     www      8715:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 8716: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      8717:     }
                   8718:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      8719: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   8720: 	   $correct_id=~tr/a-z/A-Z/;
                   8721: 	   $correct_id=~s/\s//gs;
                   8722: 	   $correct_id=~s/^[\#0]+//;
1.421     www      8723:            $correct_id=~s/[\-\:]//g;
1.414     www      8724:            if ($correct_id) {
                   8725: 	      $correct_ids{$correct_id}='specified';
                   8726:            }
                   8727:         }
1.400     www      8728:     }
1.404     www      8729:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 8730: 	$result.=&mt('Score based on attendance only');
1.521     www      8731:     } elsif ($env{'form.gradingmechanism'} eq 'given') {
1.522     www      8732:         $result.=&mt('Score based on [_1] ([_2] answers)','<tt>'.$env{'form.givenanswer'}.'</tt>',$foundgiven);
1.404     www      8733:     } else {
1.408     albertel 8734: 	my $number=0;
1.411     www      8735: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 8736: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      8737: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 8738: 	    if ($correct_ids{$id} eq 'specified') {
                   8739: 		$result.=&mt('specified');
                   8740: 	    } else {
                   8741: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   8742: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   8743: 	    }
                   8744: 	    $number++;
                   8745: 	}
1.411     www      8746:         $result.="</p>\n";
1.408     albertel 8747: 	if ($number==0) {
                   8748: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   8749: 	    return $result.&show_grading_menu_form($symb);
                   8750: 	}
1.404     www      8751:     }
1.405     www      8752:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 8753:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   8754: 		     '<span class="LC_error">',
                   8755: 		     '</span>',
                   8756: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      8757:         return $result.&show_grading_menu_form($symb);
                   8758:     }
1.410     www      8759: 
                   8760: # Were able to get all the info needed, now analyze the file
                   8761: 
1.411     www      8762:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 8763:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      8764:     my $heading=&mt('Scanning clicker file');
                   8765:     $result.=(<<ENDHEADER);
                   8766: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8767: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8768: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8769: <form method="post" action="/adm/grades" name="clickeranalysis">
                   8770: <input type="hidden" name="symb" value="$symb" />
                   8771: <input type="hidden" name="command" value="assignclickergrades" />
                   8772: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   8773: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      8774: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   8775: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   8776: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      8777: ENDHEADER
1.522     www      8778:     if ($env{'form.gradingmechanism'} eq 'given') {
                   8779:        $result.='<input type="hidden" name="correct:given" value="'.$env{'form.givenanswer'}.'" />';
                   8780:     } 
1.408     albertel 8781:     my %responses;
                   8782:     my @questiontitles;
1.405     www      8783:     my $errormsg='';
                   8784:     my $number=0;
                   8785:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 8786: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      8787:     }
1.419     www      8788:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   8789:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   8790:     }
1.411     www      8791:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   8792:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   8793:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   8794:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   8795:              '<br />';
1.522     www      8796:     if (($env{'form.gradingmechanism'} eq 'given') && ($number!=$foundgiven)) {
                   8797:        $result.='<span class="LC_error">'.&mt('Number of given answers does not agree with number of questions in file.').'</span>';
                   8798:        return $result.&show_grading_menu_form($symb);
                   8799:     } 
1.414     www      8800: # Remember Question Titles
                   8801: # FIXME: Possibly need delimiter other than ":"
                   8802:     for (my $i=0;$i<$number;$i++) {
                   8803:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   8804:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   8805:     }
1.411     www      8806:     my $correct_count=0;
                   8807:     my $student_count=0;
                   8808:     my $unknown_count=0;
1.414     www      8809: # Match answers with usernames
                   8810: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 8811:     foreach my $id (keys(%responses)) {
1.410     www      8812:        if ($correct_ids{$id}) {
1.414     www      8813:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      8814:           $correct_count++;
1.410     www      8815:        } elsif ($clicker_ids{$id}) {
1.437     www      8816:           if ($clicker_ids{$id}=~/\,/) {
                   8817: # More than one user with the same clicker!
                   8818:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   8819:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8820:                            "<select name='multi".$id."'>";
                   8821:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   8822:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   8823:              }
                   8824:              $result.='</select>';
                   8825:              $unknown_count++;
                   8826:           } else {
                   8827: # Good: found one and only one user with the right clicker
                   8828:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   8829:              $student_count++;
                   8830:           }
1.410     www      8831:        } else {
1.411     www      8832:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   8833:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   8834:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   8835:                    "\n".&mt("Domain").": ".
                   8836:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   8837:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   8838:           $unknown_count++;
1.410     www      8839:        }
1.405     www      8840:     }
1.412     www      8841:     $result.='<hr />'.
                   8842:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
1.521     www      8843:     if (($env{'form.gradingmechanism'} ne 'attendance') && ($env{'form.gradingmechanism'} ne 'given')) {
1.412     www      8844:        if ($correct_count==0) {
                   8845:           $errormsg.="Found no correct answers answers for grading!";
                   8846:        } elsif ($correct_count>1) {
1.414     www      8847:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8848:        }
                   8849:     }
1.428     www      8850:     if ($number<1) {
                   8851:        $errormsg.="Found no questions.";
                   8852:     }
1.412     www      8853:     if ($errormsg) {
                   8854:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8855:     } else {
                   8856:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8857:     }
                   8858:     $result.='</form></td></tr></table>'."\n".
1.410     www      8859:              '</td></tr></table><br /><br />'."\n";
1.404     www      8860:     return $result.&show_grading_menu_form($symb);
1.400     www      8861: }
                   8862: 
1.405     www      8863: sub iclicker_eval {
1.406     www      8864:     my ($questiontitles,$responses)=@_;
1.405     www      8865:     my $number=0;
                   8866:     my $errormsg='';
                   8867:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8868:         my %components=&Apache::loncommon::record_sep($line);
                   8869:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8870: 	if ($entries[0] eq 'Question') {
                   8871: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8872: 		$$questiontitles[$number]=$entries[$i];
                   8873: 		$number++;
                   8874: 	    }
                   8875: 	}
                   8876: 	if ($entries[0]=~/^\#/) {
                   8877: 	    my $id=$entries[0];
                   8878: 	    my @idresponses;
                   8879: 	    $id=~s/^[\#0]+//;
                   8880: 	    for (my $i=0;$i<$number;$i++) {
                   8881: 		my $idx=3+$i*6;
                   8882: 		push(@idresponses,$entries[$idx]);
                   8883: 	    }
                   8884: 	    $$responses{$id}=join(',',@idresponses);
                   8885: 	}
1.405     www      8886:     }
                   8887:     return ($errormsg,$number);
                   8888: }
                   8889: 
1.419     www      8890: sub interwrite_eval {
                   8891:     my ($questiontitles,$responses)=@_;
                   8892:     my $number=0;
                   8893:     my $errormsg='';
1.420     www      8894:     my $skipline=1;
                   8895:     my $questionnumber=0;
                   8896:     my %idresponses=();
1.419     www      8897:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8898:         my %components=&Apache::loncommon::record_sep($line);
                   8899:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8900:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8901:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8902:         next if $skipline;
                   8903:         if ($entries[0]!=$questionnumber) {
                   8904:            $questionnumber=$entries[0];
                   8905:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8906:            $number++;
1.419     www      8907:         }
1.420     www      8908:         my $id=$entries[4];
                   8909:         $id=~s/^[\#0]+//;
1.421     www      8910:         $id=~s/^v\d*\://i;
                   8911:         $id=~s/[\-\:]//g;
1.420     www      8912:         $idresponses{$id}[$number]=$entries[6];
                   8913:     }
1.524     raeburn  8914:     foreach my $id (keys(%idresponses)) {
1.420     www      8915:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8916:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8917:     }
                   8918:     return ($errormsg,$number);
                   8919: }
                   8920: 
1.414     www      8921: sub assign_clicker_grades {
                   8922:     my ($r)=@_;
                   8923:     my ($symb)=&get_symb($r);
                   8924:     if (!$symb) {return '';}
1.416     www      8925: # See which part we are saving to
                   8926:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8927: # FIXME: This should probably look for the first handgradeable part
                   8928:     my $part=$$partlist[0];
                   8929: # Start screen output
1.414     www      8930:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8931: 
1.414     www      8932:     my $heading=&mt('Assigning grades based on clicker file');
                   8933:     $result.=(<<ENDHEADER);
                   8934: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8935: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8936: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8937: ENDHEADER
                   8938: # Get correct result
                   8939: # FIXME: Possibly need delimiter other than ":"
                   8940:     my @correct=();
1.415     www      8941:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8942:     my $number=$env{'form.number'};
                   8943:     if ($gradingmechanism ne 'attendance') {
1.414     www      8944:        foreach my $key (keys(%env)) {
                   8945:           if ($key=~/^form\.correct\:/) {
                   8946:              my @input=split(/\,/,$env{$key});
                   8947:              for (my $i=0;$i<=$#input;$i++) {
                   8948:                  if (($correct[$i]) && ($input[$i]) &&
                   8949:                      ($correct[$i] ne $input[$i])) {
                   8950:                     $result.='<br /><span class="LC_warning">'.
                   8951:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8952:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8953:                  } elsif ($input[$i]) {
                   8954:                     $correct[$i]=$input[$i];
                   8955:                  }
                   8956:              }
                   8957:           }
                   8958:        }
1.415     www      8959:        for (my $i=0;$i<$number;$i++) {
1.414     www      8960:           if (!$correct[$i]) {
                   8961:              $result.='<br /><span class="LC_error">'.
                   8962:                       &mt('No correct result given for question "[_1]"!',
                   8963:                           $env{'form.question:'.$i}).'</span>';
                   8964:           }
                   8965:        }
                   8966:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8967:     }
                   8968: # Start grading
1.415     www      8969:     my $pcorrect=$env{'form.pcorrect'};
                   8970:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8971:     my $storecount=0;
1.415     www      8972:     foreach my $key (keys(%env)) {
1.420     www      8973:        my $user='';
1.415     www      8974:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8975:           $user=$1;
                   8976:        }
                   8977:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8978:           my $id=$1;
                   8979:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8980:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8981:           } elsif ($env{'form.multi'.$id}) {
                   8982:              $user=$env{'form.multi'.$id};
1.420     www      8983:           }
                   8984:        }
                   8985:        if ($user) { 
1.415     www      8986:           my @answer=split(/\,/,$env{$key});
                   8987:           my $sum=0;
1.522     www      8988:           my $realnumber=$number;
1.415     www      8989:           for (my $i=0;$i<$number;$i++) {
                   8990:              if ($answer[$i]) {
                   8991:                 if ($gradingmechanism eq 'attendance') {
                   8992:                    $sum+=$pcorrect;
1.522     www      8993:                 } elsif ($answer[$i] eq '*') {
                   8994:                    $sum+=$pcorrect;
                   8995:                 } elsif ($answer[$i] eq '-') {
                   8996:                    $realnumber--;
1.415     www      8997:                 } else {
                   8998:                    if ($answer[$i] eq $correct[$i]) {
                   8999:                       $sum+=$pcorrect;
                   9000:                    } else {
                   9001:                       $sum+=$pincorrect;
                   9002:                    }
                   9003:                 }
                   9004:              }
                   9005:           }
1.522     www      9006:           my $ave=$sum/(100*$realnumber);
1.416     www      9007: # Store
                   9008:           my ($username,$domain)=split(/\:/,$user);
                   9009:           my %grades=();
                   9010:           $grades{"resource.$part.solved"}='correct_by_override';
                   9011:           $grades{"resource.$part.awarded"}=$ave;
                   9012:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   9013:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   9014:                                                  $env{'request.course.id'},
                   9015:                                                  $domain,$username);
                   9016:           if ($returncode ne 'ok') {
                   9017:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   9018:           } else {
                   9019:              $storecount++;
                   9020:           }
1.415     www      9021:        }
                   9022:     }
                   9023: # We are done
1.416     www      9024:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   9025:              '</td></tr></table>'."\n".
1.414     www      9026:              '</td></tr></table><br /><br />'."\n";
                   9027:     return $result.&show_grading_menu_form($symb);
                   9028: }
                   9029: 
1.1       albertel 9030: sub handler {
1.41      ng       9031:     my $request=$_[0];
1.434     albertel 9032:     &reset_caches();
1.257     albertel 9033:     if ($env{'browser.mathml'}) {
1.141     www      9034: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       9035:     } else {
1.141     www      9036: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       9037:     }
                   9038:     $request->send_http_header;
1.44      ng       9039:     return '' if $request->header_only;
1.41      ng       9040:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 9041:     my $symb=&get_symb($request,1);
1.160     albertel 9042:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   9043:     my $command=$commands[0];
1.447     foxr     9044: 
1.160     albertel 9045:     if ($#commands > 0) {
                   9046: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   9047:     }
1.447     foxr     9048: 
1.513     foxr     9049:     $ssi_error = 0;
1.353     albertel 9050:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 9051:     if ($symb eq '' && $command eq '') {
1.257     albertel 9052: 	if ($env{'user.adv'}) {
                   9053: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   9054: 		($env{'form.codethree'})) {
                   9055: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   9056: 		    $env{'form.codethree'};
1.41      ng       9057: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   9058: 		    &Apache::lonnet::checkin($token);
                   9059: 		if ($tsymb) {
1.137     albertel 9060: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       9061: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.513     foxr     9062: 			$request->print(&ssi_with_retries('/res/'.$url, $ssi_retries,
1.99      albertel 9063: 					  ('grade_username' => $tuname,
                   9064: 					   'grade_domain' => $tudom,
                   9065: 					   'grade_courseid' => $tcrsid,
                   9066: 					   'grade_symb' => $tsymb)));
1.41      ng       9067: 		    } else {
1.45      ng       9068: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 9069: 		    }
1.41      ng       9070: 		} else {
1.45      ng       9071: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       9072: 		}
1.14      www      9073: 	    } else {
1.41      ng       9074: 		$request->print(&Apache::lonxml::tokeninputfield());
                   9075: 	    }
                   9076: 	}
                   9077:     } else {
1.285     albertel 9078: 	&init_perm();
1.104     albertel 9079: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 9080: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 9081: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       9082: 	    &pickStudentPage($request);
1.103     albertel 9083: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       9084: 	    &displayPage($request);
1.104     albertel 9085: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       9086: 	    &updateGradeByPage($request);
1.104     albertel 9087: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       9088: 	    &processGroup($request);
1.104     albertel 9089: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 9090: 	    $request->print(&grading_menu($request));
                   9091: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   9092: 	    $request->print(&submit_options($request));
1.104     albertel 9093: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       9094: 	    $request->print(&viewgrades($request));
1.104     albertel 9095: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       9096: 	    $request->print(&processHandGrade($request));
1.106     albertel 9097: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       9098: 	    $request->print(&editgrades($request));
1.106     albertel 9099: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       9100: 	    $request->print(&verifyreceipt($request));
1.400     www      9101:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   9102:             $request->print(&process_clicker($request));
                   9103:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   9104:             $request->print(&process_clicker_file($request));
1.414     www      9105:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   9106:             $request->print(&assign_clicker_grades($request));
1.106     albertel 9107: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       9108: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 9109: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       9110: 	    $request->print(&csvupload($request));
1.106     albertel 9111: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       9112: 	    $request->print(&csvuploadmap($request));
1.246     albertel 9113: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 9114: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 9115: 		$request->print(&csvuploadoptions($request));
1.41      ng       9116: 	    } else {
1.257     albertel 9117: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   9118: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       9119: 		} else {
1.257     albertel 9120: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       9121: 		}
                   9122: 		$request->print(&csvuploadmap($request));
                   9123: 	    }
1.246     albertel 9124: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   9125: 	    $request->print(&csvuploadassign($request));
1.106     albertel 9126: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 9127: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 9128:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   9129:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 9130: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   9131: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 9132: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 9133: 	    $request->print(&scantron_process_students($request));
1.157     albertel 9134:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 9135:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9136: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 9137:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 9138:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 9139:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   9140: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 9141:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 9142:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 9143: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 9144:  	    $request->print(&scantron_download_scantron_data($request));
1.523     raeburn  9145:         } elsif ($command eq 'checksubmissions' && $perm{'vgr'}) {
                   9146:             $request->print(&checkscantron_results($request));     
1.106     albertel 9147: 	} elsif ($command) {
1.157     albertel 9148: 	    $request->print("Access Denied ($command)");
1.26      albertel 9149: 	}
1.2       albertel 9150:     }
1.513     foxr     9151:     if ($ssi_error) {
                   9152: 	&ssi_print_error($request);
                   9153:     }
1.353     albertel 9154:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 9155:     &reset_caches();
1.44      ng       9156:     return '';
                   9157: }
                   9158: 
1.1       albertel 9159: 1;
                   9160: 
1.13      albertel 9161: __END__;

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