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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.493   ! albertel    4: # $Id: grades.pm,v 1.492 2007/11/16 07:56:15 albertel 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: 
                     50: my %perm=();
1.447     foxr       51: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       52:                                    # index is "symb.part_id"
                     53: 
1.447     foxr       54: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     55: 
                     56: # Save and restore the bubble lines array to the form env.
                     57: 
                     58: 
                     59: sub save_bubble_lines {
                     60:     foreach my $line (keys(%bubble_lines_per_response)) {
                     61: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     62: 	$env{"form.scantron.first_bubble_line.$line"} =
                     63: 	    $first_bubble_line{$line};
                     64:     }
                     65: }
                     66: 
                     67: 
                     68: sub restore_bubble_lines {
                     69:     my $line = 0;
                     70:     %bubble_lines_per_response = ();
                     71:     while ($env{"form.scantron.bubblelines.$line"}) {
                     72: 	my $value = $env{"form.scantron.bubblelines.$line"};
                     73: 	$bubble_lines_per_response{$line} = $value;
                     74: 	$first_bubble_line{$line}  =
                     75: 	    $env{"form.scantron.first_bubble_line.$line"};
                     76: 	$line++;
                     77:     }
                     78: 
                     79: }
                     80: 
                     81: #  Given the parsed scanline, get the response for 
                     82: #  'answer' number n:
                     83: 
                     84: sub get_response_bubbles {
                     85:     my ($parsed_line, $response)  = @_;
                     86: 
1.460     foxr       87: 
                     88:     my $bubble_line = $first_bubble_line{$response-1} +1;
                     89:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                     90:     
1.447     foxr       91:     my $selected = "";
                     92: 
                     93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
1.461     foxr       94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
1.447     foxr       95: 	$bubble_line++;
                     96:     }
                     97:     return $selected;
                     98: }
                     99: 
1.1       albertel  100: 
1.68      ng        101: # ----- These first few routines are general use routines.----
1.447     foxr      102: 
                    103: # Return the number of occurences of a pattern in a string.
                    104: 
                    105: sub occurence_count {
                    106:     my ($string, $pattern) = @_;
                    107: 
                    108:     my @matches = ($string =~ /$pattern/g);
                    109: 
                    110:     return scalar(@matches);
                    111: }
                    112: 
                    113: 
                    114: # Take a string known to have digits and convert all the
                    115: # digits into letters in the range J,A..I.
                    116: 
                    117: sub digits_to_letters {
                    118:     my ($input) = @_;
                    119: 
                    120:     my @alphabet = ('J', 'A'..'I');
                    121: 
                    122:     my @input    = split(//, $input);
                    123:     my $output ='';
                    124:     for (my $i = 0; $i < scalar(@input); $i++) {
                    125: 	if ($input[$i] =~ /\d/) {
                    126: 	    $output .= $alphabet[$input[$i]];
                    127: 	} else {
                    128: 	    $output .= $input[$i];
                    129: 	}
                    130:     }
                    131:     return $output;
                    132: }
                    133: 
1.44      ng        134: #
1.146     albertel  135: # --- Retrieve the parts from the metadata file.---
1.44      ng        136: sub getpartlist {
1.324     albertel  137:     my ($symb) = @_;
1.439     albertel  138: 
                    139:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    140:     my $res      = $navmap->getBySymb($symb);
                    141:     my $partlist = $res->parts();
                    142:     my $url      = $res->src();
                    143:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    144: 
1.146     albertel  145:     my @stores;
1.439     albertel  146:     foreach my $part (@{ $partlist }) {
1.146     albertel  147: 	foreach my $key (@metakeys) {
                    148: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    149: 	}
                    150:     }
                    151:     return @stores;
1.2       albertel  152: }
                    153: 
1.44      ng        154: # --- Get the symbolic name of a problem and the url
1.324     albertel  155: sub get_symb {
1.173     albertel  156:     my ($request,$silent) = @_;
1.257     albertel  157:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  159:     if ($symb eq '') { 
                    160: 	if (!$silent) {
                    161: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    162: 	    return ();
                    163: 	}
                    164:     }
1.418     albertel  165:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  166:     return ($symb);
1.32      ng        167: }
                    168: 
1.129     ng        169: #--- Format fullname, username:domain if different for display
                    170: #--- Use anywhere where the student names are listed
                    171: sub nameUserString {
                    172:     my ($type,$fullname,$uname,$udom) = @_;
                    173:     if ($type eq 'header') {
1.485     albertel  174: 	return '<b>&nbsp;'.&mt('Fullname').'&nbsp;</b><span class="LC_internal_info">('.&mt('Username').')</span>';
1.129     ng        175:     } else {
1.398     albertel  176: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    177: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        178:     }
                    179: }
                    180: 
1.44      ng        181: #--- Get the partlist and the response type for a given problem. ---
                    182: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        183: sub response_type {
1.324     albertel  184:     my ($symb) = shift;
1.377     albertel  185: 
                    186:     my $navmap = Apache::lonnavmaps::navmap->new();
                    187:     my $res = $navmap->getBySymb($symb);
                    188:     my $partlist = $res->parts();
1.392     albertel  189:     my %vPart = 
                    190: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  191:     my (%response_types,%handgrade);
                    192:     foreach my $part (@{ $partlist }) {
1.392     albertel  193: 	next if (%vPart && !exists($vPart{$part}));
                    194: 
1.377     albertel  195: 	my @types = $res->responseType($part);
                    196: 	my @ids = $res->responseIds($part);
                    197: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    198: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    199: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    200: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    201: 				     '.handgrade',$symb);
1.41      ng        202: 	}
                    203:     }
1.377     albertel  204:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        205: }
                    206: 
1.375     albertel  207: sub flatten_responseType {
                    208:     my ($responseType) = @_;
                    209:     my @part_response_id =
                    210: 	map { 
                    211: 	    my $part = $_;
                    212: 	    map {
                    213: 		[$part,$_]
                    214: 		} sort(keys(%{ $responseType->{$part} }));
                    215: 	} sort(keys(%$responseType));
                    216:     return @part_response_id;
                    217: }
                    218: 
1.207     albertel  219: sub get_display_part {
1.324     albertel  220:     my ($partID,$symb)=@_;
1.207     albertel  221:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    222:     if (defined($display) and $display ne '') {
1.398     albertel  223: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  224:     } else {
                    225: 	$display=$partID;
                    226:     }
                    227:     return $display;
                    228: }
1.269     raeburn   229: 
1.118     ng        230: #--- Show resource title
                    231: #--- and parts and response type
                    232: sub showResourceInfo {
1.324     albertel  233:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  234:     my $col=3;
                    235:     if ($checkboxes) { $col=4; }
1.398     albertel  236:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    237:     $result .='<table border="0">';
1.324     albertel  238:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        239:     my %resptype = ();
1.122     ng        240:     my $hdgrade='no';
1.154     albertel  241:     my %partsseen;
1.375     albertel  242:     foreach my $partID (sort keys(%$responseType)) {
                    243: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    244: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    245: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    246: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    247: 	    $result.='<tr>';
                    248: 	    if ($checkboxes) {
                    249: 		if (exists($partsseen{$partID})) {
                    250: 		    $result.="<td>&nbsp;</td>";
                    251: 		} else {
1.401     albertel  252: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  253: 		}
                    254: 		$partsseen{$partID}=1;
1.154     albertel  255: 	    }
1.375     albertel  256: 	    my $display_part=&get_display_part($partID,$symb);
1.485     albertel  257: 	    $result.='<td>'.&mt('<b>Part: </b>[_1]',$display_part).' <span class="LC_internal_info">'.
1.398     albertel  258: 		$resID.'</span></td>'.
1.485     albertel  259: 		'<td>'.&mt('<b>Type: </b>[_1]',$responsetype).'</td></tr>';
                    260: #	    '<td>'.&mt('<b>Handgrade: </b>[_1]',$handgrade).'</td></tr>';
1.154     albertel  261: 	}
1.118     ng        262:     }
                    263:     $result.='</table>'."\n";
1.147     albertel  264:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        265: }
                    266: 
1.434     albertel  267: sub reset_caches {
                    268:     &reset_analyze_cache();
                    269:     &reset_perm();
                    270: }
                    271: 
                    272: {
                    273:     my %analyze_cache;
1.148     albertel  274: 
1.434     albertel  275:     sub reset_analyze_cache {
                    276: 	undef(%analyze_cache);
                    277:     }
                    278: 
                    279:     sub get_analyze {
                    280: 	my ($symb,$uname,$udom)=@_;
                    281: 	my $key = "$symb\0$uname\0$udom";
                    282: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    283: 
                    284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    285: 	$url=&Apache::lonnet::clutter($url);
                    286: 	my $subresult=&Apache::lonnet::ssi($url,
                    287: 					   ('grade_target' => 'analyze'),
                    288: 					   ('grade_domain' => $udom),
                    289: 					   ('grade_symb' => $symb),
                    290: 					   ('grade_courseid' => 
                    291: 					    $env{'request.course.id'}),
                    292: 					   ('grade_username' => $uname));
                    293: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    294: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    295: 	return $analyze_cache{$key} = \%analyze;
                    296:     }
                    297: 
                    298:     sub get_order {
                    299: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    300: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    301: 	return $analyze->{"$partid.$respid.shown"};
                    302:     }
                    303: 
                    304:     sub get_radiobutton_correct_foil {
                    305: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    306: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    307: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    308: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    309: 		return $foil;
                    310: 	    }
                    311: 	}
                    312:     }
1.148     albertel  313: }
1.434     albertel  314: 
1.118     ng        315: #--- Clean response type for display
1.335     albertel  316: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    317: #        response types only.
1.118     ng        318: sub cleanRecord {
1.336     albertel  319:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    320: 	$uname,$udom) = @_;
1.398     albertel  321:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  322:     if ($response =~ /^(option|rank)$/) {
                    323: 	my %answer=&Apache::lonnet::str2hash($answer);
                    324: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    325: 	my ($toprow,$bottomrow);
                    326: 	foreach my $foil (@$order) {
                    327: 	    if ($grading{$foil} == 1) {
                    328: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    329: 	    } else {
                    330: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    331: 	    }
1.398     albertel  332: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  333: 	}
                    334: 	return '<blockquote><table border="1">'.
1.466     albertel  335: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    336: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  337: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    338:     } elsif ($response eq 'match') {
                    339: 	my %answer=&Apache::lonnet::str2hash($answer);
                    340: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    341: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    342: 	my ($toprow,$middlerow,$bottomrow);
                    343: 	foreach my $foil (@$order) {
                    344: 	    my $item=shift(@items);
                    345: 	    if ($grading{$foil} == 1) {
                    346: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  347: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  348: 	    } else {
                    349: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  350: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  351: 	    }
1.398     albertel  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        353: 	}
1.126     ng        354: 	return '<blockquote><table border="1">'.
1.466     albertel  355: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    356: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  357: 	    $middlerow.'</tr>'.
1.466     albertel  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  359: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    360:     } elsif ($response eq 'radiobutton') {
                    361: 	my %answer=&Apache::lonnet::str2hash($answer);
                    362: 	my ($toprow,$bottomrow);
1.434     albertel  363: 	my $correct = 
                    364: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    365: 	foreach my $foil (@$order) {
1.148     albertel  366: 	    if (exists($answer{$foil})) {
1.434     albertel  367: 		if ($foil eq $correct) {
1.466     albertel  368: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  369: 		} else {
1.466     albertel  370: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  371: 		}
                    372: 	    } else {
1.466     albertel  373: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  374: 	    }
1.398     albertel  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  376: 	}
                    377: 	return '<blockquote><table border="1">'.
1.466     albertel  378: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    379: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    381:     } elsif ($response eq 'essay') {
1.257     albertel  382: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        386: 
1.257     albertel  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    392: 	    $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        393: 	}
1.166     albertel  394: 	$answer =~ s-\n-<br />-g;
                    395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  396:     } elsif ( $response eq 'organic') {
                    397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    400: 	return $result;
1.335     albertel  401:     } elsif ( $response eq 'Task') {
                    402: 	if ( $answer eq 'SUBMITTED') {
                    403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  405: 	    return $result;
                    406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    408: 			       keys(%{$record}));
                    409: 	    return join('<br />',($version,@matches));
                    410: 			       
                    411: 			       
                    412: 	} else {
                    413: 	    my $result =
                    414: 		'<p>'
                    415: 		.&mt('Overall result: [_1]',
                    416: 		     $record->{$version."resource.$respid.$partid.status"})
                    417: 		.'</p>';
                    418: 	    
                    419: 	    $result .= '<ul>';
                    420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    421: 			     keys(%{$record}));
                    422: 	    foreach my $grade (sort(@grade)) {
                    423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    425: 				     $dim, $record->{$grade}).
                    426: 			  '</li>';
                    427: 	    }
                    428: 	    $result.='</ul>';
                    429: 	    return $result;
                    430: 	}
1.440     albertel  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    432: 	$answer = 
                    433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    434: 							      $answer);
1.122     ng        435:     }
1.118     ng        436:     return $answer;
                    437: }
                    438: 
                    439: #-- A couple of common js functions
                    440: sub commonJSfunctions {
                    441:     my $request = shift;
                    442:     $request->print(<<COMMONJSFUNCTIONS);
                    443: <script type="text/javascript" language="javascript">
                    444:     function radioSelection(radioButton) {
                    445: 	var selection=null;
                    446: 	if (radioButton.length > 1) {
                    447: 	    for (var i=0; i<radioButton.length; i++) {
                    448: 		if (radioButton[i].checked) {
                    449: 		    return radioButton[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
                    453: 	    if (radioButton.checked) return radioButton.value;
                    454: 	}
                    455: 	return selection;
                    456:     }
                    457: 
                    458:     function pullDownSelection(selectOne) {
                    459: 	var selection="";
                    460: 	if (selectOne.length > 1) {
                    461: 	    for (var i=0; i<selectOne.length; i++) {
                    462: 		if (selectOne[i].selected) {
                    463: 		    return selectOne[i].value;
                    464: 		}
                    465: 	    }
                    466: 	} else {
1.138     albertel  467:             // only one value it must be the selected one
                    468: 	    return selectOne.value;
1.118     ng        469: 	}
                    470:     }
                    471: </script>
                    472: COMMONJSFUNCTIONS
                    473: }
                    474: 
1.44      ng        475: #--- Dumps the class list with usernames,list of sections,
                    476: #--- section, ids and fullnames for each user.
                    477: sub getclasslist {
1.449     banghart  478:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  479:     my @getsec;
1.450     banghart  480:     my @getgroup;
1.442     banghart  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  482:     if (!ref($getsec)) {
                    483: 	if ($getsec ne '' && $getsec ne 'all') {
                    484: 	    @getsec=($getsec);
                    485: 	}
                    486:     } else {
                    487: 	@getsec=@{$getsec};
                    488:     }
                    489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  490:     if (!ref($getgroup)) {
                    491: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    492: 	    @getgroup=($getgroup);
                    493: 	}
                    494:     } else {
                    495: 	@getgroup=@{$getgroup};
                    496:     }
                    497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  498: 
1.449     banghart  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  500:     # Bail out if we were unable to get the classlist
1.56      matthew   501:     return if (! defined($classlist));
1.449     banghart  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   503:     #
                    504:     my %sections;
                    505:     my %fullnames;
1.205     matthew   506:     foreach my $student (keys(%$classlist)) {
                    507:         my $end      = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    509:         my $start    = 
                    510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    511:         my $id       = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    513:         my $section  = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    515:         my $fullname = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    517:         my $status   = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  519:         my $group   = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        521: 	# filter students according to status selected
1.442     banghart  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    523: 	    if (!($stu_status =~ $status)) {
1.450     banghart  524: 		delete($classlist->{$student});
1.76      ng        525: 		next;
                    526: 	    }
                    527: 	}
1.450     banghart  528: 	# filter students according to groups selected
1.453     banghart  529: 	my @stu_groups = split(/,/,$group);
1.450     banghart  530: 	if (@getgroup) {
                    531: 	    my $exclude = 1;
1.454     banghart  532: 	    foreach my $grp (@getgroup) {
                    533: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  534: 	            if ($stu_group eq $grp) {
                    535: 	                $exclude = 0;
                    536:     	            } 
1.450     banghart  537: 	        }
1.453     banghart  538:     	        if (($grp eq 'none') && !$group) {
                    539:         	        $exclude = 0;
                    540:         	}
1.450     banghart  541: 	    }
                    542: 	    if ($exclude) {
                    543: 	        delete($classlist->{$student});
                    544: 	    }
                    545: 	}
1.205     matthew   546: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  547: 	if (&canview($section)) {
1.291     albertel  548: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  549: 		$sections{$section}++;
1.450     banghart  550: 		if ($classlist->{$student}) {
                    551: 		    $fullnames{$student}=$fullname;
                    552: 		}
1.103     albertel  553: 	    } else {
1.205     matthew   554: 		delete($classlist->{$student});
1.103     albertel  555: 	    }
                    556: 	} else {
1.205     matthew   557: 	    delete($classlist->{$student});
1.103     albertel  558: 	}
1.44      ng        559:     }
                    560:     my %seen = ();
1.56      matthew   561:     my @sections = sort(keys(%sections));
                    562:     return ($classlist,\@sections,\%fullnames);
1.44      ng        563: }
                    564: 
1.103     albertel  565: sub canmodify {
                    566:     my ($sec)=@_;
                    567:     if ($perm{'mgr'}) {
                    568: 	if (!defined($perm{'mgr_section'})) {
                    569: 	    # can modify whole class
                    570: 	    return 1;
                    571: 	} else {
                    572: 	    if ($sec eq $perm{'mgr_section'}) {
                    573: 		#can modify the requested section
                    574: 		return 1;
                    575: 	    } else {
                    576: 		# can't modify the request section
                    577: 		return 0;
                    578: 	    }
                    579: 	}
                    580:     }
                    581:     #can't modify
                    582:     return 0;
                    583: }
                    584: 
                    585: sub canview {
                    586:     my ($sec)=@_;
                    587:     if ($perm{'vgr'}) {
                    588: 	if (!defined($perm{'vgr_section'})) {
                    589: 	    # can modify whole class
                    590: 	    return 1;
                    591: 	} else {
                    592: 	    if ($sec eq $perm{'vgr_section'}) {
                    593: 		#can modify the requested section
                    594: 		return 1;
                    595: 	    } else {
                    596: 		# can't modify the request section
                    597: 		return 0;
                    598: 	    }
                    599: 	}
                    600:     }
                    601:     #can't modify
                    602:     return 0;
                    603: }
                    604: 
1.44      ng        605: #--- Retrieve the grade status of a student for all the parts
                    606: sub student_gradeStatus {
1.324     albertel  607:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  608:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        609:     my %partstatus = ();
                    610:     foreach (@$partlist) {
1.128     ng        611: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        612: 	$status              = 'nothing' if ($status eq '');
                    613: 	$partstatus{$_}      = $status;
                    614: 	my $subkey           = "resource.$_.submitted_by";
                    615: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    616:     }
                    617:     return %partstatus;
                    618: }
                    619: 
1.45      ng        620: # hidden form and javascript that calls the form
                    621: # Use by verifyscript and viewgrades
                    622: # Shows a student's view of problem and submission
                    623: sub jscriptNform {
1.324     albertel  624:     my ($symb) = @_;
1.442     banghart  625:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        626:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    627: 	'    function viewOneStudent(user,domain) {'."\n".
                    628: 	'	document.onestudent.student.value = user;'."\n".
                    629: 	'	document.onestudent.userdom.value = domain;'."\n".
                    630: 	'	document.onestudent.submit();'."\n".
                    631: 	'    }'."\n".
                    632: 	'</script>'."\n";
                    633:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  634: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  635: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    636: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  637: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        638: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    639: 	'<input type="hidden" name="student" value="" />'."\n".
                    640: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    641: 	'</form>'."\n";
                    642:     return $jscript;
                    643: }
1.39      ng        644: 
1.447     foxr      645: 
                    646: 
1.315     bowersj2  647: # Given the score (as a number [0-1] and the weight) what is the final
                    648: # point value? This function will round to the nearest tenth, third,
                    649: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  650: sub compute_points {
1.315     bowersj2  651:     my ($score, $weight) = @_;
                    652:     
                    653:     my $tolerance = .00001;
                    654:     my $points = $score * $weight;
                    655: 
                    656:     # Check for nearness to 1/x.
                    657:     my $check_for_nearness = sub {
                    658:         my ($factor) = @_;
                    659:         my $num = ($points * $factor) + $tolerance;
                    660:         my $floored_num = floor($num);
1.316     albertel  661:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  662:             return $floored_num / $factor;
                    663:         }
                    664:         return $points;
                    665:     };
                    666: 
                    667:     $points = $check_for_nearness->(10);
                    668:     $points = $check_for_nearness->(3);
                    669:     $points = $check_for_nearness->(4);
                    670:     
                    671:     return $points;
                    672: }
                    673: 
1.44      ng        674: #------------------ End of general use routines --------------------
1.87      www       675: 
                    676: #
                    677: # Find most similar essay
                    678: #
                    679: 
                    680: sub most_similar {
1.426     albertel  681:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       682: 
                    683: # ignore spaces and punctuation
                    684: 
                    685:     $uessay=~s/\W+/ /gs;
                    686: 
1.282     www       687: # ignore empty submissions (occuring when only files are sent)
                    688: 
                    689:     unless ($uessay=~/\w+/) { return ''; }
                    690: 
1.87      www       691: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       692:     my $limit=0.6;
1.87      www       693:     my $sname='';
                    694:     my $sdom='';
                    695:     my $scrsid='';
                    696:     my $sessay='';
                    697: # go through all essays ...
1.426     albertel  698:     foreach my $tkey (keys(%$old_essays)) {
                    699: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       700: # ... except the same student
1.426     albertel  701:         next if (($tname eq $uname) && ($tdom eq $udom));
                    702: 	my $tessay=$old_essays->{$tkey};
                    703: 	$tessay=~s/\W+/ /gs;
1.87      www       704: # String similarity gives up if not even limit
1.426     albertel  705: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       706: # Found one
1.426     albertel  707: 	if ($tsimilar>$limit) {
                    708: 	    $limit=$tsimilar;
                    709: 	    $sname=$tname;
                    710: 	    $sdom=$tdom;
                    711: 	    $scrsid=$tcrsid;
                    712: 	    $sessay=$old_essays->{$tkey};
                    713: 	}
1.87      www       714:     }
1.88      www       715:     if ($limit>0.6) {
1.87      www       716:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    717:     } else {
                    718:        return ('','','','',0);
                    719:     }
                    720: }
                    721: 
1.44      ng        722: #-------------------------------------------------------------------
                    723: 
                    724: #------------------------------------ Receipt Verification Routines
1.45      ng        725: #
1.44      ng        726: #--- Check whether a receipt number is valid.---
                    727: sub verifyreceipt {
                    728:     my $request  = shift;
                    729: 
1.257     albertel  730:     my $courseid = $env{'request.course.id'};
1.184     www       731:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  732: 	$env{'form.receipt'};
1.44      ng        733:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  734:     my ($symb)   = &get_symb($request);
1.44      ng        735: 
1.487     albertel  736:     my $title.=
                    737: 	'<h3><span class="LC_info">'.
                    738: 	&mt('Verifying Submission Receipt [_1]',$receipt).
                    739: 	'</span></h3>'."\n".
                    740: 	'<h4>'.&mt('<b>Resource: </b>[_1]',$env{'form.probTitle'}).
                    741: 	'</h4>'."\n";
1.44      ng        742: 
                    743:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   744:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  745:     
                    746:     my $receiptparts=0;
1.390     albertel  747:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    748: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  749:     my $parts=['0'];
1.324     albertel  750:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.486     albertel  751:     
                    752:     my $header = 
                    753: 	&Apache::loncommon::start_data_table().
                    754: 	&Apache::loncommon::start_data_table_header_row().
1.487     albertel  755: 	'<th>&nbsp;'.&mt('Fullname').'&nbsp;</th>'."\n".
                    756: 	'<th>&nbsp;'.&mt('Username').'&nbsp;</th>'."\n".
                    757: 	'<th>&nbsp;'.&mt('Domain').'&nbsp;</th>';
1.486     albertel  758:     if ($receiptparts) {
1.487     albertel  759: 	$header.='<th>&nbsp;'.&mt('Problem Part').'&nbsp;</th>';
1.486     albertel  760:     }
                    761:     $header.=
                    762: 	&Apache::loncommon::end_data_table_header_row();
                    763: 
1.294     albertel  764:     foreach (sort 
                    765: 	     {
                    766: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    767: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    768: 		 }
                    769: 		 return $a cmp $b;
                    770: 	     } (keys(%$fullname))) {
1.44      ng        771: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  772: 	foreach my $part (@$parts) {
                    773: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486     albertel  774: 		$contents.=
                    775: 		    &Apache::loncommon::start_data_table_row().
                    776: 		    '<td>&nbsp;'."\n".
1.177     albertel  777: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  778: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  779: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    780: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    781: 		if ($receiptparts) {
                    782: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    783: 		}
1.486     albertel  784: 		$contents.= 
                    785: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  786: 		
                    787: 		$matches++;
                    788: 	    }
1.44      ng        789: 	}
                    790:     }
                    791:     if ($matches == 0) {
1.487     albertel  792: 	$string = $title.&mt('No match found for the above receipt.');
1.44      ng        793:     } else {
1.324     albertel  794: 	$string = &jscriptNform($symb).$title.
1.487     albertel  795: 	    '<p>'.
                    796: 	    &mt('The above receipt matches the following [numerate,_1,student].',$matches).
                    797: 	    '</p>'.
1.486     albertel  798: 	    $header.
                    799: 	    $contents.
                    800: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        801:     }
1.324     albertel  802:     return $string.&show_grading_menu_form($symb);
1.44      ng        803: }
                    804: 
                    805: #--- This is called by a number of programs.
                    806: #--- Called from the Grading Menu - View/Grade an individual student
                    807: #--- Also called directly when one clicks on the subm button 
                    808: #    on the problem page.
1.30      ng        809: sub listStudents {
1.41      ng        810:     my ($request) = shift;
1.49      albertel  811: 
1.324     albertel  812:     my ($symb) = &get_symb($request);
1.257     albertel  813:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    814:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    815:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  816:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  817:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    818:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    819:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    820: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  821: 
1.485     albertel  822:     my $result='<h3><span class="LC_info">&nbsp;'.
                    823: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    824: 	.'</span></h3>';
1.118     ng        825: 
1.324     albertel  826:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  827: 
1.485     albertel  828:     my %lt = ( 'multiple' =>
                    829: 	       "Please select a student or group of students before clicking on the Next button.",
                    830: 	       'single'   =>
                    831: 	       "Please select the student before clicking on the Next button.",
                    832: 	       );
                    833:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        834:     $request->print(<<LISTJAVASCRIPT);
                    835: <script type="text/javascript" language="javascript">
1.110     ng        836:     function checkSelect(checkBox) {
                    837: 	var ctr=0;
                    838: 	var sense="";
                    839: 	if (checkBox.length > 1) {
                    840: 	    for (var i=0; i<checkBox.length; i++) {
                    841: 		if (checkBox[i].checked) {
                    842: 		    ctr++;
                    843: 		}
                    844: 	    }
1.485     albertel  845: 	    sense = '$lt{'multiple'}';
1.110     ng        846: 	} else {
                    847: 	    if (checkBox.checked) {
                    848: 		ctr = 1;
                    849: 	    }
1.485     albertel  850: 	    sense = '$lt{'single'}';
1.110     ng        851: 	}
                    852: 	if (ctr == 0) {
1.485     albertel  853: 	    alert(sense);
1.110     ng        854: 	    return false;
                    855: 	}
                    856: 	document.gradesub.submit();
                    857:     }
                    858: 
                    859:     function reLoadList(formname) {
1.112     ng        860: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        861: 	formname.command.value = 'submission';
                    862: 	formname.submit();
                    863:     }
1.45      ng        864: </script>
                    865: LISTJAVASCRIPT
                    866: 
1.118     ng        867:     &commonJSfunctions($request);
1.41      ng        868:     $request->print($result);
1.39      ng        869: 
1.401     albertel  870:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    871:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  872:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  873: 	"\n".$table;
                    874: 	
                    875:     $gradeTable .= 
                    876: 	'&nbsp;'.
                    877: 	&mt('<b>View Problem Text: </b>[_1]',
                    878: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    879: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                    880: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                    881:     $gradeTable .= 
                    882: 	'&nbsp;'.
                    883: 	&mt('<b>View Answer: </b>[_1]',
                    884: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    885: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                    886: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                    887: 
                    888:     my $submission_options;
1.257     albertel  889:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  890: 	$submission_options.=
                    891: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  892:     }
1.442     banghart  893:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    894:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  895:     $env{'form.Status'} = $saveStatus;
1.485     albertel  896:     $submission_options.=
                    897: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    898: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    899: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    900: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    901:     $gradeTable .= 
                    902: 	'&nbsp;'.
                    903: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                    904: 
                    905:     $gradeTable .= 
                    906:         '&nbsp;'.
                    907: 	&mt('<b>Grading Increments:</b> [_1]',
                    908: 	    '<select name="increment">'.
                    909: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    910: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    911: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    912: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                    913: 	    '</select>');
                    914:     
                    915:     $gradeTable .= 
1.432     banghart  916:         &build_section_inputs().
1.45      ng        917: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  918: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    919: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    920: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    921: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  922: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        923: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    924: 
1.257     albertel  925:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  926: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        927:     } else {
1.485     albertel  928: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    929: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        930:     }
1.112     ng        931: 
1.485     albertel  932:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    933: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        934: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  935: 
                    936: # checkall buttons
                    937:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        938:     $gradeTable.='<input type="button" '."\n".
1.45      ng        939: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel  940: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  941:     $gradeTable.=&check_buttons();
1.485     albertel  942:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  943:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  944:     $gradeTable.= &Apache::loncommon::start_data_table().
                    945: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        946:     my $loop = 0;
                    947:     while ($loop < 2) {
1.485     albertel  948: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    949: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  950: 	if ($env{'form.showgrading'} eq 'yes' 
                    951: 	    && $submitonly ne 'queued'
                    952: 	    && $submitonly ne 'all') {
1.485     albertel  953: 	    foreach my $part (sort(@$partlist)) {
                    954: 		my $display_part=
                    955: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    956: 		$gradeTable.=
                    957: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        958: 	    }
1.301     albertel  959: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  960: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        961: 	}
                    962: 	$loop++;
1.126     ng        963: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        964:     }
1.474     albertel  965:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        966: 
1.45      ng        967:     my $ctr = 0;
1.294     albertel  968:     foreach my $student (sort 
                    969: 			 {
                    970: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    971: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    972: 			     }
                    973: 			     return $a cmp $b;
                    974: 			 }
                    975: 			 (keys(%$fullname))) {
1.41      ng        976: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  977: 
1.110     ng        978: 	my %status = ();
1.301     albertel  979: 
                    980: 	if ($submitonly eq 'queued') {
                    981: 	    my %queue_status = 
                    982: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    983: 							$udom,$uname);
                    984: 	    next if (!defined($queue_status{'gradingqueue'}));
                    985: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    986: 	}
                    987: 
                    988: 	if ($env{'form.showgrading'} eq 'yes' 
                    989: 	    && $submitonly ne 'queued'
                    990: 	    && $submitonly ne 'all') {
1.324     albertel  991: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  992: 	    my $submitted = 0;
1.164     albertel  993: 	    my $graded = 0;
1.248     albertel  994: 	    my $incorrect = 0;
1.110     ng        995: 	    foreach (keys(%status)) {
1.145     albertel  996: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  997: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    998: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    999: 		
1.110     ng       1000: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   1001: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel 1002: 		    $submitted = 0;
1.150     albertel 1003: 		    my ($part)=split(/\./,$partid);
1.110     ng       1004: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1005: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1006: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1007: 		}
1.41      ng       1008: 	    }
1.248     albertel 1009: 	    
1.156     albertel 1010: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1011: 				     $submitonly eq 'incorrect' ||
                   1012: 				     $submitonly eq 'graded'));
1.248     albertel 1013: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1014: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1015: 	}
1.34      ng       1016: 
1.45      ng       1017: 	$ctr++;
1.249     albertel 1018: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1019:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1020: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1021: 	    if ($ctr%2 ==1) {
                   1022: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1023: 	    }
1.126     ng       1024: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1025:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1026:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1027: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1028: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1029: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1030: 
1.257     albertel 1031: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng       1032: 		foreach (sort keys(%status)) {
1.485     albertel 1033: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1034: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1035: 		}
1.41      ng       1036: 	    }
1.126     ng       1037: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1038: 	    if ($ctr%2 ==0) {
                   1039: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1040: 	    }
1.41      ng       1041: 	}
                   1042:     }
1.110     ng       1043:     if ($ctr%2 ==1) {
1.126     ng       1044: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1045: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1046: 		&& $submitonly ne 'queued'
                   1047: 		&& $submitonly ne 'all') {
1.110     ng       1048: 		foreach (@$partlist) {
                   1049: 		    $gradeTable.='<td>&nbsp;</td>';
                   1050: 		}
1.301     albertel 1051: 	    } elsif ($submitonly eq 'queued') {
                   1052: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1053: 	    }
1.474     albertel 1054: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1055:     }
                   1056: 
1.474     albertel 1057:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1058: 	'<input type="button" '.
                   1059: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1060: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1061:     if ($ctr == 0) {
1.96      albertel 1062: 	my $num_students=(scalar(keys(%$fullname)));
                   1063: 	if ($num_students eq 0) {
1.485     albertel 1064: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1065: 	} else {
1.171     albertel 1066: 	    my $submissions='submissions';
                   1067: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1068: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1069: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1070: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1071: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1072: 		    $num_students).
                   1073: 		'</span><br />';
1.96      albertel 1074: 	}
1.46      ng       1075:     } elsif ($ctr == 1) {
1.474     albertel 1076: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1077:     }
1.324     albertel 1078:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1079:     $request->print($gradeTable);
1.44      ng       1080:     return '';
1.10      ng       1081: }
                   1082: 
1.44      ng       1083: #---- Called from the listStudents routine
1.249     albertel 1084: 
                   1085: sub check_script {
                   1086:     my ($form, $type)=@_;
                   1087:     my $chkallscript='<script type="text/javascript">
                   1088:     function checkall() {
                   1089:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1090:             ele = document.forms.'.$form.'.elements[i];
                   1091:             if (ele.name == "'.$type.'") {
                   1092:             document.forms.'.$form.'.elements[i].checked=true;
                   1093:                                        }
                   1094:         }
                   1095:     }
                   1096: 
                   1097:     function checksec() {
                   1098:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1099:             ele = document.forms.'.$form.'.elements[i];
                   1100:            string = document.forms.'.$form.'.chksec.value;
                   1101:            if
                   1102:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1103:               document.forms.'.$form.'.elements[i].checked=true;
                   1104:             }
                   1105:         }
                   1106:     }
                   1107: 
                   1108: 
                   1109:     function uncheckall() {
                   1110:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1111:             ele = document.forms.'.$form.'.elements[i];
                   1112:             if (ele.name == "'.$type.'") {
                   1113:             document.forms.'.$form.'.elements[i].checked=false;
                   1114:                                        }
                   1115:         }
                   1116:     }
                   1117: 
                   1118: </script>'."\n";
                   1119:     return $chkallscript;
                   1120: }
                   1121: 
                   1122: sub check_buttons {
1.485     albertel 1123:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1124:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1125:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1126:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1127:     return $buttons;
                   1128: }
                   1129: 
1.44      ng       1130: #     Displays the submissions for one student or a group of students
1.34      ng       1131: sub processGroup {
1.41      ng       1132:     my ($request)  = shift;
                   1133:     my $ctr        = 0;
1.155     albertel 1134:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1135:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1136: 
1.396     banghart 1137:     foreach my $student (@stuchecked) {
                   1138: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1139: 	$env{'form.student'}        = $uname;
                   1140: 	$env{'form.userdom'}        = $udom;
                   1141: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1142: 	&submission($request,$ctr,$total);
                   1143: 	$ctr++;
                   1144:     }
                   1145:     return '';
1.35      ng       1146: }
1.34      ng       1147: 
1.44      ng       1148: #------------------------------------------------------------------------------------
                   1149: #
                   1150: #-------------------------- Next few routines handles grading by student, essentially
                   1151: #                           handles essay response type problem/part
                   1152: #
                   1153: #--- Javascript to handle the submission page functionality ---
                   1154: sub sub_page_js {
                   1155:     my $request = shift;
                   1156:     $request->print(<<SUBJAVASCRIPT);
                   1157: <script type="text/javascript" language="javascript">
1.71      ng       1158:     function updateRadio(formname,id,weight) {
1.125     ng       1159: 	var gradeBox = formname["GD_BOX"+id];
                   1160: 	var radioButton = formname["RADVAL"+id];
                   1161: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1162: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1163: 	gradeBox.value = pts;
                   1164: 	var resetbox = false;
                   1165: 	if (isNaN(pts) || pts < 0) {
                   1166: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1167: 	    for (var i=0; i<radioButton.length; i++) {
                   1168: 		if (radioButton[i].checked) {
                   1169: 		    gradeBox.value = i;
                   1170: 		    resetbox = true;
                   1171: 		}
                   1172: 	    }
                   1173: 	    if (!resetbox) {
                   1174: 		formtextbox.value = "";
                   1175: 	    }
                   1176: 	    return;
1.44      ng       1177: 	}
1.71      ng       1178: 
                   1179: 	if (pts > weight) {
                   1180: 	    var resp = confirm("You entered a value ("+pts+
                   1181: 			       ") greater than the weight for the part. Accept?");
                   1182: 	    if (resp == false) {
1.125     ng       1183: 		gradeBox.value = oldpts;
1.71      ng       1184: 		return;
                   1185: 	    }
1.44      ng       1186: 	}
1.13      albertel 1187: 
1.71      ng       1188: 	for (var i=0; i<radioButton.length; i++) {
                   1189: 	    radioButton[i].checked=false;
                   1190: 	    if (pts == i && pts != "") {
                   1191: 		radioButton[i].checked=true;
                   1192: 	    }
                   1193: 	}
                   1194: 	updateSelect(formname,id);
1.125     ng       1195: 	formname["stores"+id].value = "0";
1.41      ng       1196:     }
1.5       albertel 1197: 
1.72      ng       1198:     function writeBox(formname,id,pts) {
1.125     ng       1199: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1200: 	if (checkSolved(formname,id) == 'update') {
                   1201: 	    gradeBox.value = pts;
                   1202: 	} else {
1.125     ng       1203: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1204: 	    gradeBox.value = oldpts;
1.125     ng       1205: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1206: 	    for (var i=0; i<radioButton.length; i++) {
                   1207: 		radioButton[i].checked=false;
1.72      ng       1208: 		if (i == oldpts) {
1.71      ng       1209: 		    radioButton[i].checked=true;
                   1210: 		}
                   1211: 	    }
1.41      ng       1212: 	}
1.125     ng       1213: 	formname["stores"+id].value = "0";
1.71      ng       1214: 	updateSelect(formname,id);
                   1215: 	return;
1.41      ng       1216:     }
1.44      ng       1217: 
1.71      ng       1218:     function clearRadBox(formname,id) {
                   1219: 	if (checkSolved(formname,id) == 'noupdate') {
                   1220: 	    updateSelect(formname,id);
                   1221: 	    return;
                   1222: 	}
1.125     ng       1223: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1224: 	for (var i=0; i<gradeSelect.length; i++) {
                   1225: 	    if (gradeSelect[i].selected) {
                   1226: 		var selectx=i;
                   1227: 	    }
                   1228: 	}
1.125     ng       1229: 	var stores = formname["stores"+id];
1.71      ng       1230: 	if (selectx == stores.value) { return };
1.125     ng       1231: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1232: 	gradeBox.value = "";
1.125     ng       1233: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1234: 	for (var i=0; i<radioButton.length; i++) {
                   1235: 	    radioButton[i].checked=false;
                   1236: 	}
                   1237: 	stores.value = selectx;
                   1238:     }
1.5       albertel 1239: 
1.71      ng       1240:     function checkSolved(formname,id) {
1.125     ng       1241: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1242: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1243: 	    if (!reply) {return "noupdate";}
1.120     ng       1244: 	    formname.overRideScore.value = 'yes';
1.41      ng       1245: 	}
1.71      ng       1246: 	return "update";
1.13      albertel 1247:     }
1.71      ng       1248: 
                   1249:     function updateSelect(formname,id) {
1.125     ng       1250: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1251: 	return;
1.41      ng       1252:     }
1.33      ng       1253: 
1.121     ng       1254: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1255:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1256: 	formname.gradeOpt.value = val;
1.71      ng       1257: 	if (val == "Save & Next") {
                   1258: 	    for (i=0;i<=total;i++) {
                   1259: 		for (j=0;j<parttot;j++) {
1.125     ng       1260: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1261: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1262: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1263: 			if (points == "") {
1.125     ng       1264: 			    var name = formname["name"+i].value;
1.129     ng       1265: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1266: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1267: 					       ", part "+partid+". Continue?");
1.71      ng       1268: 			    if (resp == false) {
1.125     ng       1269: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1270: 				return false;
                   1271: 			    }
                   1272: 			}
                   1273: 		    }
                   1274: 		    
                   1275: 		}
                   1276: 	    }
                   1277: 	    
                   1278: 	}
1.121     ng       1279: 	if (val == "Grade Student") {
                   1280: 	    formname.showgrading.value = "yes";
                   1281: 	    if (formname.Status.value == "") {
                   1282: 		formname.Status.value = "Active";
                   1283: 	    }
                   1284: 	    formname.studentNo.value = total;
                   1285: 	}
1.120     ng       1286: 	formname.submit();
                   1287:     }
                   1288: 
1.71      ng       1289: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1290:     function checkSubmitPage(formname,total) {
                   1291: 	noscore = new Array(100);
                   1292: 	var ptr = 0;
                   1293: 	for (i=1;i<total;i++) {
1.125     ng       1294: 	    var partid = formname["q_"+i].value;
1.127     ng       1295: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1296: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1297: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1298: 		if (points == "" && status != "correct_by_student") {
                   1299: 		    noscore[ptr] = i;
                   1300: 		    ptr++;
                   1301: 		}
                   1302: 	    }
                   1303: 	}
                   1304: 	if (ptr != 0) {
                   1305: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1306: 	    var prolist = "";
                   1307: 	    if (ptr == 1) {
                   1308: 		prolist = noscore[0];
                   1309: 	    } else {
                   1310: 		var i = 0;
                   1311: 		while (i < ptr-1) {
                   1312: 		    prolist += noscore[i]+", ";
                   1313: 		    i++;
                   1314: 		}
                   1315: 		prolist += "and "+noscore[i];
                   1316: 	    }
                   1317: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1318: 	    if (resp == false) {
                   1319: 		return false;
                   1320: 	    }
                   1321: 	}
1.45      ng       1322: 
1.71      ng       1323: 	formname.submit();
                   1324:     }
                   1325: </script>
                   1326: SUBJAVASCRIPT
                   1327: }
1.45      ng       1328: 
1.71      ng       1329: #--- javascript for essay type problem --
                   1330: sub sub_page_kw_js {
                   1331:     my $request = shift;
1.80      ng       1332:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1333:     &commonJSfunctions($request);
1.350     albertel 1334: 
1.351     albertel 1335:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1336:     <script text="text/javascript">
                   1337:     function checkInput() {
                   1338:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1339:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1340:       var usrctr = document.msgcenter.usrctr.value;
                   1341:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1342:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1343: 
                   1344:       var msgchk = "";
                   1345:       if (document.msgcenter.subchk.checked) {
                   1346:          msgchk = "msgsub,";
                   1347:       }
                   1348:       var includemsg = 0;
                   1349:       for (var i=1; i<=nmsg; i++) {
                   1350:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1351:           var frmmsg = document.msgcenter["msg"+i];
                   1352:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1353:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1354:           showflg.value = "1";
                   1355:           var chkbox = document.msgcenter["msgn"+i];
                   1356:           if (chkbox.checked) {
                   1357:              msgchk += "savemsg"+i+",";
                   1358:              includemsg = 1;
                   1359:           }
                   1360:       }
                   1361:       if (document.msgcenter.newmsgchk.checked) {
                   1362:          msgchk += "newmsg"+usrctr;
                   1363:          includemsg = 1;
                   1364:       }
                   1365:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1366:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1367:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1368:       includemsg.value = msgchk;
                   1369: 
                   1370:       self.close()
                   1371: 
                   1372:     }
                   1373:     </script>
                   1374: INNERJS
                   1375: 
1.351     albertel 1376:     my $inner_js_highlight_central=<<INNERJS;
                   1377:  <script type="text/javascript">
                   1378:     function updateChoice(flag) {
                   1379:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1380:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1381:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1382:       opener.document.SCORE.refresh.value = "on";
                   1383:       if (opener.document.SCORE.keywords.value!=""){
                   1384:          opener.document.SCORE.submit();
                   1385:       }
                   1386:       self.close()
                   1387:     }
                   1388: </script>
                   1389: INNERJS
                   1390: 
                   1391:     my $start_page_msg_central = 
                   1392:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1393: 				       {'js_ready'  => 1,
                   1394: 					'only_body' => 1,
                   1395: 					'bgcolor'   =>'#FFFFFF',});
                   1396:     my $end_page_msg_central = 
                   1397: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1398: 
                   1399: 
                   1400:     my $start_page_highlight_central = 
                   1401:         &Apache::loncommon::start_page('Highlight Central',
                   1402: 				       $inner_js_highlight_central,
1.350     albertel 1403: 				       {'js_ready'  => 1,
                   1404: 					'only_body' => 1,
                   1405: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1406:     my $end_page_highlight_central = 
1.350     albertel 1407: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1408: 
1.219     www      1409:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1410:     $docopen=~s/^document\.//;
1.71      ng       1411:     $request->print(<<SUBJAVASCRIPT);
                   1412: <script type="text/javascript" language="javascript">
1.45      ng       1413: 
1.44      ng       1414: //===================== Show list of keywords ====================
1.122     ng       1415:   function keywords(formname) {
                   1416:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1417:     if (nret==null) return;
1.122     ng       1418:     formname.keywords.value = nret;
1.44      ng       1419: 
1.122     ng       1420:     if (formname.keywords.value != "") {
1.128     ng       1421: 	formname.refresh.value = "on";
1.122     ng       1422: 	formname.submit();
1.44      ng       1423:     }
                   1424:     return;
                   1425:   }
                   1426: 
                   1427: //===================== Script to view submitted by ==================
                   1428:   function viewSubmitter(submitter) {
                   1429:     document.SCORE.refresh.value = "on";
                   1430:     document.SCORE.NCT.value = "1";
                   1431:     document.SCORE.unamedom0.value = submitter;
                   1432:     document.SCORE.submit();
                   1433:     return;
                   1434:   }
                   1435: 
                   1436: //===================== Script to add keyword(s) ==================
                   1437:   function getSel() {
                   1438:     if (document.getSelection) txt = document.getSelection();
                   1439:     else if (document.selection) txt = document.selection.createRange().text;
                   1440:     else return;
                   1441:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1442:     if (cleantxt=="") {
1.46      ng       1443: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1444: 	return;
                   1445:     }
                   1446:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1447:     if (nret==null) return;
1.127     ng       1448:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1449:     if (document.SCORE.keywords.value != "") {
1.127     ng       1450: 	document.SCORE.refresh.value = "on";
1.44      ng       1451: 	document.SCORE.submit();
                   1452:     }
                   1453:     return;
                   1454:   }
                   1455: 
                   1456: //====================== Script for composing message ==============
1.80      ng       1457:    // preload images
                   1458:    img1 = new Image();
                   1459:    img1.src = "$iconpath/mailbkgrd.gif";
                   1460:    img2 = new Image();
                   1461:    img2.src = "$iconpath/mailto.gif";
                   1462: 
1.44      ng       1463:   function msgCenter(msgform,usrctr,fullname) {
                   1464:     var Nmsg  = msgform.savemsgN.value;
                   1465:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1466:     var subject = msgform.msgsub.value;
1.127     ng       1467:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1468:     re = /msgsub/;
                   1469:     var shwsel = "";
                   1470:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1471:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1472:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1473:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1474: 	var testmsg = "savemsg"+i+",";
                   1475: 	re = new RegExp(testmsg,"g");
1.44      ng       1476: 	shwsel = "";
                   1477: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1478: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1479: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1480: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1481: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1482:     }
1.125     ng       1483:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1484:     shwsel = "";
                   1485:     re = /newmsg/;
                   1486:     if (re.test(msgchk)) { shwsel = "checked" }
                   1487:     newMsg(newmsg,shwsel);
                   1488:     msgTail(); 
                   1489:     return;
                   1490:   }
                   1491: 
1.123     ng       1492:   function checkEntities(strx) {
                   1493:     if (strx.length == 0) return strx;
                   1494:     var orgStr = ["&", "<", ">", '"']; 
                   1495:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1496:     var counter = 0;
                   1497:     while (counter < 4) {
                   1498: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1499: 	counter++;
                   1500:     }
                   1501:     return strx;
                   1502:   }
                   1503: 
                   1504:   function strReplace(strx, orgStr, newStr) {
                   1505:     return strx.split(orgStr).join(newStr);
                   1506:   }
                   1507: 
1.44      ng       1508:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1509:     var height = 70*Nmsg+250;
1.44      ng       1510:     var scrollbar = "no";
                   1511:     if (height > 600) {
                   1512: 	height = 600;
                   1513: 	scrollbar = "yes";
                   1514:     }
1.118     ng       1515:     var xpos = (screen.width-600)/2;
                   1516:     xpos = (xpos < 0) ? '0' : xpos;
                   1517:     var ypos = (screen.height-height)/2-30;
                   1518:     ypos = (ypos < 0) ? '0' : ypos;
                   1519: 
1.206     albertel 1520:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1521:     pWin.focus();
                   1522:     pDoc = pWin.document;
1.219     www      1523:     pDoc.$docopen;
1.351     albertel 1524:     pDoc.write('$start_page_msg_central');
1.76      ng       1525: 
                   1526:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1527:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1528:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1529: 
                   1530:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1531:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1532:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1533: }
                   1534:     function displaySubject(msg,shwsel) {
1.76      ng       1535:     pDoc = pWin.document;
                   1536:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1537:     pDoc.write("<td>Subject<\\/td>");
                   1538:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1539:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1540: }
                   1541: 
1.72      ng       1542:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1543:     pDoc = pWin.document;
                   1544:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1545:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1546:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1547:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1548: }
                   1549: 
                   1550:   function newMsg(newmsg,shwsel) {
1.76      ng       1551:     pDoc = pWin.document;
                   1552:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1553:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1554:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1555:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1556: }
                   1557: 
                   1558:   function msgTail() {
1.76      ng       1559:     pDoc = pWin.document;
1.465     albertel 1560:     pDoc.write("<\\/table>");
                   1561:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1562:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1563:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1564:     pDoc.write("<\\/form>");
1.351     albertel 1565:     pDoc.write('$end_page_msg_central');
1.128     ng       1566:     pDoc.close();
1.44      ng       1567: }
                   1568: 
                   1569: //====================== Script for keyword highlight options ==============
                   1570:   function kwhighlight() {
                   1571:     var kwclr    = document.SCORE.kwclr.value;
                   1572:     var kwsize   = document.SCORE.kwsize.value;
                   1573:     var kwstyle  = document.SCORE.kwstyle.value;
                   1574:     var redsel = "";
                   1575:     var grnsel = "";
                   1576:     var blusel = "";
                   1577:     if (kwclr=="red")   {var redsel="checked"};
                   1578:     if (kwclr=="green") {var grnsel="checked"};
                   1579:     if (kwclr=="blue")  {var blusel="checked"};
                   1580:     var sznsel = "";
                   1581:     var sz1sel = "";
                   1582:     var sz2sel = "";
                   1583:     if (kwsize=="0")  {var sznsel="checked"};
                   1584:     if (kwsize=="+1") {var sz1sel="checked"};
                   1585:     if (kwsize=="+2") {var sz2sel="checked"};
                   1586:     var synsel = "";
                   1587:     var syisel = "";
                   1588:     var sybsel = "";
                   1589:     if (kwstyle=="")    {var synsel="checked"};
                   1590:     if (kwstyle=="<i>") {var syisel="checked"};
                   1591:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1592:     highlightCentral();
                   1593:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1594:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1595:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1596:     highlightend();
                   1597:     return;
                   1598:   }
                   1599: 
                   1600:   function highlightCentral() {
1.76      ng       1601: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1602:     var xpos = (screen.width-400)/2;
                   1603:     xpos = (xpos < 0) ? '0' : xpos;
                   1604:     var ypos = (screen.height-330)/2-30;
                   1605:     ypos = (ypos < 0) ? '0' : ypos;
                   1606: 
1.206     albertel 1607:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1608:     hwdWin.focus();
                   1609:     var hDoc = hwdWin.document;
1.219     www      1610:     hDoc.$docopen;
1.351     albertel 1611:     hDoc.write('$start_page_highlight_central');
1.76      ng       1612:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1613:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1614: 
                   1615:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1616:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1617:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1618:   }
                   1619: 
                   1620:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1621:     var hDoc = hwdWin.document;
                   1622:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1623:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1624:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1625:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1626:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1627:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1628:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1629:     hDoc.write("<\\/tr>");
1.44      ng       1630:   }
                   1631: 
                   1632:   function highlightend() { 
1.76      ng       1633:     var hDoc = hwdWin.document;
1.465     albertel 1634:     hDoc.write("<\\/table>");
                   1635:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1636:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1637:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1638:     hDoc.write("<\\/form>");
1.351     albertel 1639:     hDoc.write('$end_page_highlight_central');
1.128     ng       1640:     hDoc.close();
1.44      ng       1641:   }
                   1642: 
                   1643: </script>
                   1644: SUBJAVASCRIPT
                   1645: }
                   1646: 
1.349     albertel 1647: sub get_increment {
1.348     bowersj2 1648:     my $increment = $env{'form.increment'};
                   1649:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1650:         $increment != .1) {
                   1651:         $increment = 1;
                   1652:     }
                   1653:     return $increment;
                   1654: }
                   1655: 
1.71      ng       1656: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1657: sub gradeBox {
1.322     albertel 1658:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1659:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1660: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1661:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1662:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1663:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1664:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1665:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1666: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1667:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1668:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1669:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1670: 				       [$partid]);
                   1671:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1672:     if ($last_resets{$partid}) {
                   1673:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1674:     }
1.485     albertel 1675:     $result.='<table border="0"><tr>';
1.71      ng       1676:     my $ctr = 0;
1.348     bowersj2 1677:     my $thisweight = 0;
1.349     albertel 1678:     my $increment = &get_increment();
1.485     albertel 1679: 
                   1680:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1681:     while ($thisweight<=$wgt) {
1.485     albertel 1682: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1683: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1684: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1685: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1686: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1687:         $thisweight += $increment;
1.71      ng       1688: 	$ctr++;
                   1689:     }
1.485     albertel 1690:     $radio.='</tr></table>';
                   1691: 
                   1692:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1693: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1694: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1695: 	$wgt.')" /></td>'."\n";
1.485     albertel 1696:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1697: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1698: 	' </td><td>'."\n";
1.485     albertel 1699:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1700: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1701:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1702: 	$line.='<option></option>'.
                   1703: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1704:     } else {
1.485     albertel 1705: 	$line.='<option selected="selected"></option>'.
                   1706: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1707:     }
1.485     albertel 1708:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1709: 
                   1710: 
                   1711:     $result .= 
                   1712: 	&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);
                   1713: 
                   1714:     
                   1715:     $result.='</tr></table>'."\n";
1.71      ng       1716:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1717: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1718: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1719: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1720:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1721:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1722:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1723:         $aggtries.'" />'."\n";
1.323     banghart 1724:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1725:     return $result;
                   1726: }
1.322     albertel 1727: 
                   1728: sub handback_box {
1.323     banghart 1729:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1730:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1731:     my (@respids);
1.375     albertel 1732:      my @part_response_id = &flatten_responseType($responseType);
                   1733:     foreach my $part_response_id (@part_response_id) {
                   1734:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1735:         if ($part eq $partid) {
1.375     albertel 1736:             push(@respids,$resp);
1.323     banghart 1737:         }
                   1738:     }
1.318     banghart 1739:     my $result;
1.323     banghart 1740:     foreach my $respid (@respids) {
1.322     albertel 1741: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1742: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1743: 	next if (!@$files);
                   1744: 	my $file_counter = 1;
1.313     banghart 1745: 	foreach my $file (@$files) {
1.368     banghart 1746: 	    if ($file =~ /\/portfolio\//) {
                   1747:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1748:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1749:     	        $file_disp = "$name.$ext";
                   1750:     	        $file = $file_path.$file_disp;
                   1751:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1752:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1753:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1754:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1755:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1756:     	        $file_counter++;
                   1757: 	    }
1.322     albertel 1758: 	}
1.313     banghart 1759:     }
1.318     banghart 1760:     return $result;    
1.71      ng       1761: }
1.44      ng       1762: 
1.58      albertel 1763: sub show_problem {
1.382     albertel 1764:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1765:     my $rendered;
1.382     albertel 1766:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1767:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1768:     if ($mode eq 'both' or $mode eq 'text') {
                   1769: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1770: 						       $env{'request.course.id'},
                   1771: 						       undef,\%form);
1.144     albertel 1772:     }
1.58      albertel 1773:     if ($removeform) {
                   1774: 	$rendered=~s|<form(.*?)>||g;
                   1775: 	$rendered=~s|</form>||g;
1.374     albertel 1776: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1777:     }
1.144     albertel 1778:     my $companswer;
                   1779:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1780: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1781: 	$companswer=
                   1782: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1783: 						    $env{'request.course.id'},
                   1784: 						    %form);
1.144     albertel 1785:     }
1.58      albertel 1786:     if ($removeform) {
                   1787: 	$companswer=~s|<form(.*?)>||g;
                   1788: 	$companswer=~s|</form>||g;
1.144     albertel 1789: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1790:     }
1.468     albertel 1791:     $rendered=
                   1792: 	'<div class="LC_grade_show_problem_header">'.
                   1793: 	&mt('View of the problem').
                   1794: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1795: 	$rendered.
                   1796: 	'</div>';
                   1797:     $companswer=
                   1798: 	'<div class="LC_grade_show_problem_header">'.
                   1799: 	&mt('Correct answer').
                   1800: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1801: 	$companswer.
                   1802: 	'</div>';
                   1803:     my $result;
1.144     albertel 1804:     if ($mode eq 'both') {
1.468     albertel 1805: 	$result=$rendered.$companswer;
1.144     albertel 1806:     } elsif ($mode eq 'text') {
1.468     albertel 1807: 	$result=$rendered;
1.144     albertel 1808:     } elsif ($mode eq 'answer') {
1.468     albertel 1809: 	$result=$companswer;
1.144     albertel 1810:     }
1.468     albertel 1811:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1812:     return $result;
1.58      albertel 1813: }
1.397     albertel 1814: 
1.396     banghart 1815: sub files_exist {
                   1816:     my ($r, $symb) = @_;
                   1817:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1818: 
1.396     banghart 1819:     foreach my $student (@students) {
                   1820:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1821:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1822: 					      $udom,$uname);
1.396     banghart 1823:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1824:         foreach my $submission (@$string) {
                   1825:             my ($partid,$respid) =
                   1826: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1827:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1828: 					   \%record);
                   1829:             return 1 if (@$files);
1.396     banghart 1830:         }
                   1831:     }
1.397     albertel 1832:     return 0;
1.396     banghart 1833: }
1.397     albertel 1834: 
1.394     banghart 1835: sub download_all_link {
                   1836:     my ($r,$symb) = @_;
1.395     albertel 1837:     my $all_students = 
                   1838: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1839: 
                   1840:     my $parts =
                   1841: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1842: 
1.394     banghart 1843:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1844:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1845:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1846:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1847:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1848: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1849:     return
                   1850: }
1.395     albertel 1851: 
1.432     banghart 1852: sub build_section_inputs {
                   1853:     my $section_inputs;
                   1854:     if ($env{'form.section'} eq '') {
                   1855:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1856:     } else {
                   1857:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1858:         foreach my $section (@sections) {
1.432     banghart 1859:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1860:         }
                   1861:     }
                   1862:     return $section_inputs;
                   1863: }
                   1864: 
1.44      ng       1865: # --------------------------- show submissions of a student, option to grade 
                   1866: sub submission {
                   1867:     my ($request,$counter,$total) = @_;
1.257     albertel 1868:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1869:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1870:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1871:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1872:     my $symb = &get_symb($request); 
                   1873:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1874: 
                   1875:     if (!&canview($usec)) {
1.398     albertel 1876: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1877: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1878: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1879: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1880: 	return;
                   1881:     }
                   1882: 
1.257     albertel 1883:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1884:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1885:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1886:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1887:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1888: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1889: 	'/check.gif" height="16" border="0" />';
1.41      ng       1890: 
1.426     albertel 1891:     my %old_essays;
1.41      ng       1892:     # header info
                   1893:     if ($counter == 0) {
                   1894: 	&sub_page_js($request);
1.257     albertel 1895: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1896: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1897: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1898: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1899: 	    &download_all_link($request, $symb);
                   1900: 	}
1.485     albertel 1901: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1902: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1903: 
1.44      ng       1904: 	# option to display problem, only once else it cause problems 
                   1905:         # with the form later since the problem has a form.
1.257     albertel 1906: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1907: 	    my $mode;
1.257     albertel 1908: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1909: 		$mode='both';
1.257     albertel 1910: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1911: 		$mode='text';
1.257     albertel 1912: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1913: 		$mode='answer';
                   1914: 	    }
1.329     albertel 1915: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1916: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1917: 	}
1.441     www      1918: 
1.44      ng       1919: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1920:         # if this subroutine has been called once.
1.41      ng       1921: 	my %keyhash = ();
1.257     albertel 1922: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1923: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1924: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1925: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1926: 
1.257     albertel 1927: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1928: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1929: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1930: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1931: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1932: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1933: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1934: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1935: 	}
1.257     albertel 1936: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1937: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1938: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1939: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1940: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1941: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1942: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1943: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1944: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1945: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1946: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1947: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1948: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1949: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1950: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1951: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1952: 			&build_section_inputs().
1.326     albertel 1953: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1954: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1955: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1956: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1957: 	if ($env{'form.handgrade'} eq 'yes') {
                   1958: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1959: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1960: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1961: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1962: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1963: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1964: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1965: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1966: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1967: 	    }
1.123     ng       1968: 	}
1.41      ng       1969: 	
                   1970: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1971: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1972: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1973: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1974: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1975: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1976: 		'" />'."\n".
                   1977: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1978: 	    $cts++;
                   1979: 	}
                   1980: 	$request->print($prnmsg);
1.32      ng       1981: 
1.257     albertel 1982: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1983: #
                   1984: # Print out the keyword options line
                   1985: #
1.41      ng       1986: 	    $request->print(<<KEYWORDS);
1.38      ng       1987: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1988: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1989: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1990:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1991: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1992: KEYWORDS
1.88      www      1993: #
                   1994: # Load the other essays for similarity check
                   1995: #
1.324     albertel 1996:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1997: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1998: 	    $apath=&escape($apath);
1.88      www      1999: 	    $apath=~s/\W/\_/gs;
1.426     albertel 2000: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       2001:         }
                   2002:     }
1.44      ng       2003: 
1.441     www      2004: # This is where output for one specific student would start
1.468     albertel 2005:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2006:     $request->print("\n\n".
1.468     albertel 2007:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2008: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2009: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2010: 
1.257     albertel 2011:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2012: 	my $mode;
1.257     albertel 2013: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2014: 	    $mode='both';
1.257     albertel 2015: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2016: 	    $mode='text';
1.257     albertel 2017: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2018: 	    $mode='answer';
                   2019: 	}
1.329     albertel 2020: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2021: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2022:     }
1.144     albertel 2023: 
1.257     albertel 2024:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2025:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2026: 
1.44      ng       2027:     # Display student info
1.41      ng       2028:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2029:     my $result='<div class="LC_grade_submissions">';
                   2030:     
                   2031:     $result.='<div class="LC_grade_submissions_header">';
                   2032:     $result.= &mt('Submissions');
1.45      ng       2033:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2034: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2035:     if ($env{'form.handgrade'} eq 'no') {
                   2036: 	$result.='<span class="LC_grade_check_note">'.
                   2037: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2038: 
                   2039:     }
                   2040: 
                   2041: 
1.41      ng       2042: 
1.118     ng       2043:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2044:     my $fullname;
                   2045:     my $col_fullnames = [];
1.257     albertel 2046:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2047: 	(my $sub_result,$fullname,$col_fullnames)=
                   2048: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2049: 				 $counter);
                   2050: 	$result.=$sub_result;
1.41      ng       2051:     }
1.44      ng       2052:     $request->print($result."\n");
1.468     albertel 2053:     $request->print('</div>'."\n");
1.44      ng       2054:     # print student answer/submission
                   2055:     # Options are (1) Handgaded submission only
                   2056:     #             (2) Last submission, includes submission that is not handgraded 
                   2057:     #                  (for multi-response type part)
                   2058:     #             (3) Last submission plus the parts info
                   2059:     #             (4) The whole record for this student
1.257     albertel 2060:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2061: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2062: 	
                   2063: 	my $lastsubonly;
                   2064: 
1.151     albertel 2065: 	if ($$timestamp eq '') {
1.468     albertel 2066: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2067: 	} else {
1.468     albertel 2068: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2069: 
1.151     albertel 2070: 	    my %seenparts;
1.375     albertel 2071: 	    my @part_response_id = &flatten_responseType($responseType);
                   2072: 	    foreach my $part (@part_response_id) {
1.393     albertel 2073: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2074: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2075: 
1.375     albertel 2076: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2077: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2078: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2079: 		    if (exists($seenparts{$partid})) { next; }
                   2080: 		    $seenparts{$partid}=1;
1.207     albertel 2081: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2082: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2083: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2084: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2085: 			'\');" target="_self">'.
1.257     albertel 2086: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2087: 		    $request->print($submitby);
                   2088: 		    next;
                   2089: 		}
                   2090: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2091: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2092: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2093: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2094: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2095: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2096: 		    next;
                   2097: 		}
1.468     albertel 2098: 		foreach my $submission (@$string) {
                   2099: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2100: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2101: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2102: 		    # Similarity check
                   2103: 		    my $similar='';
1.257     albertel 2104: 		    if($env{'form.checkPlag'}){
1.151     albertel 2105: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2106: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2107: 			if ($osim) {
                   2108: 			    $osim=int($osim*100.0);
1.426     albertel 2109: 			    my %old_course_desc = 
                   2110: 				&Apache::lonnet::coursedescription($ocrsid,
                   2111: 								   {'one_time' => 1});
                   2112: 
                   2113: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2114: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2115: 				    $osim,
                   2116: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2117: 				    $oname,$odom,
1.426     albertel 2118: 				    $old_course_desc{'description'},
1.427     albertel 2119: 				    $old_course_desc{'num'},
1.426     albertel 2120: 				    $old_course_desc{'domain'}).
1.398     albertel 2121: 				'</span></h3><blockquote><i>'.
1.151     albertel 2122: 				&keywords_highlight($oessay).
                   2123: 				'</i></blockquote><hr />';
                   2124: 			}
1.150     albertel 2125: 		    }
1.151     albertel 2126: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2127: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2128: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2129: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2130: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2131: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2132: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2133: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2134: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2135: 			if (@$files) {
1.468     albertel 2136: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2137: 			    my $file_counter = 0;
1.313     banghart 2138: 			    foreach my $file (@$files) {
1.468     albertel 2139: 			        $file_counter++;
1.232     albertel 2140: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2141: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2142: 			    }
1.236     albertel 2143: 			    $lastsubonly.='<br />';
1.41      ng       2144: 			}
1.468     albertel 2145: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2146: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2147: 					 $respid,\%record,$order);
                   2148: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2149: 			$lastsubonly.='</div>';
1.41      ng       2150: 		    }
                   2151: 		}
                   2152: 	    }
1.468     albertel 2153: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2154: 	}
                   2155: 	$request->print($lastsubonly);
1.468     albertel 2156:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2157: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2158: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2159:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2160: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2161: 								 $env{'request.course.id'},
1.44      ng       2162: 								 $last,'.submission',
                   2163: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2164:     }
1.120     ng       2165: 
1.121     ng       2166:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2167: 	.$udom.'" />'."\n");
1.44      ng       2168:     # return if view submission with no grading option
1.257     albertel 2169:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2170: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2171: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2172: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2173: 	$toGrade.='</div>'."\n";
1.257     albertel 2174: 	if (($env{'form.command'} eq 'submission') || 
                   2175: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2176: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2177: 	}
1.180     albertel 2178: 	$request->print($toGrade);
1.41      ng       2179: 	return;
1.180     albertel 2180:     } else {
1.468     albertel 2181: 	$request->print('</div>'."\n");
1.41      ng       2182:     }
1.33      ng       2183: 
1.121     ng       2184:     # essay grading message center
1.257     albertel 2185:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2186: 	my $result='<div class="LC_grade_message_center">';
                   2187:     
                   2188: 	$result.='<div class="LC_grade_message_center_header">'.
                   2189: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2190: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2191: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2192: 	if (scalar(@$col_fullnames) > 0) {
                   2193: 	    my $lastone = pop(@$col_fullnames);
                   2194: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2195: 	}
                   2196: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2197: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2198: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2199: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2200: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2201: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2202: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2203: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2204: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2205: 	    '<br />&nbsp;('.
1.468     albertel 2206: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2207: 	$result.='</div></div>';
1.121     ng       2208: 	$request->print($result);
1.118     ng       2209:     }
1.41      ng       2210: 
                   2211:     my %seen = ();
                   2212:     my @partlist;
1.129     ng       2213:     my @gradePartRespid;
1.375     albertel 2214:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2215:     $request->print('<div class="LC_grade_assign">'.
                   2216: 		    
                   2217: 		    '<div class="LC_grade_assign_header">'.
                   2218: 		    &mt('Assign Grades').'</div>'.
                   2219: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2220:     foreach my $part_response_id (@part_response_id) {
                   2221:     	my ($partid,$respid) = @{ $part_response_id };
                   2222: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2223: 	next if ($seen{$partid} > 0);
1.41      ng       2224: 	$seen{$partid}++;
1.393     albertel 2225: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2226: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2227: 	push @partlist,$partid;
1.129     ng       2228: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2229: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2230:     }
1.468     albertel 2231:     $request->print('</div></div>');
                   2232: 
                   2233:     $request->print('<div class="LC_grade_info_links">');
                   2234:     if ($perm{'vgr'}) {
                   2235: 	$request->print(
                   2236: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2237: 						   $uname,$udom,'check'));
                   2238:     }
                   2239:     if ($perm{'opa'}) {
                   2240: 	$request->print(
                   2241: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2242: 					 $uname,$udom,$symb,'check'));
                   2243:     }
                   2244:     $request->print('</div>');
                   2245: 
1.45      ng       2246:     $result='<input type="hidden" name="partlist'.$counter.
                   2247: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2248:     $result.='<input type="hidden" name="gradePartRespid'.
                   2249: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2250:     my $ctr = 0;
                   2251:     while ($ctr < scalar(@partlist)) {
                   2252: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2253: 	    $partlist[$ctr].'" />'."\n";
                   2254: 	$ctr++;
                   2255:     }
1.468     albertel 2256:     $request->print($result.''."\n");
1.41      ng       2257: 
1.441     www      2258: # Done with printing info for one student
                   2259: 
1.468     albertel 2260:     $request->print('</div>');#LC_grade_show_user_body
                   2261:     $request->print('</div>');#LC_grade_show_user
1.441     www      2262: 
                   2263: 
1.41      ng       2264:     # print end of form
                   2265:     if ($counter == $total) {
1.297     www      2266: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2267: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2268: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2269: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2270: 	my $ntstu ='<select name="NTSTU">'.
                   2271: 	    '<option>1</option><option>2</option>'.
                   2272: 	    '<option>3</option><option>5</option>'.
                   2273: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2274: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2275: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2276: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2277: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2278: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2279: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2280: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2281: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2282:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2283:             "' name='increment' />";
1.485     albertel 2284: 	$endform.='</td></tr></table></form>';
1.324     albertel 2285: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2286: 	$request->print($endform);
                   2287:     }
                   2288:     return '';
1.38      ng       2289: }
                   2290: 
1.464     albertel 2291: sub check_collaborators {
                   2292:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2293:     my ($result,@col_fullnames);
                   2294:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2295:     foreach my $part (keys(%$handgrade)) {
                   2296: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2297: 					'.maxcollaborators',
                   2298: 					$symb,$udom,$uname);
                   2299: 	next if ($ncol <= 0);
                   2300: 	$part =~ s/\_/\./g;
                   2301: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2302: 	my (@good_collaborators, @bad_collaborators);
                   2303: 	foreach my $possible_collaborator
                   2304: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2305: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2306: 	    next if ($possible_collaborator eq '');
                   2307: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2308: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2309: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2310: 	    # Doing this grep allows 'fuzzy' specification
                   2311: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2312: 			       keys(%$classlist));
                   2313: 	    if (! scalar(@matches)) {
                   2314: 		push(@bad_collaborators, $possible_collaborator);
                   2315: 	    } else {
                   2316: 		push(@good_collaborators, @matches);
                   2317: 	    }
                   2318: 	}
                   2319: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2320: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2321: 	    foreach my $name (@good_collaborators) {
                   2322: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2323: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2324: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2325: 	    }
                   2326: 	    $result.='<br />'."\n";
1.466     albertel 2327: 	    my ($part)=split(/\./,$part);
1.464     albertel 2328: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2329: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2330: 		"\n";
                   2331: 	}
                   2332: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2333: 	    $result.='<div class="LC_warning">';
1.464     albertel 2334: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2335: 	    $result .= '</div>';
                   2336: 	}         
                   2337: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2338: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2339: 	    $result .= &mt('This student has submitted too many '.
                   2340: 		'collaborators.  Maximum is [_1].',$ncol);
                   2341: 	    $result .= '</div>';
                   2342: 	}
                   2343:     }
                   2344:     return ($result,$fullname,\@col_fullnames);
                   2345: }
                   2346: 
1.44      ng       2347: #--- Retrieve the last submission for all the parts
1.38      ng       2348: sub get_last_submission {
1.119     ng       2349:     my ($returnhash)=@_;
1.46      ng       2350:     my (@string,$timestamp);
1.119     ng       2351:     if ($$returnhash{'version'}) {
1.46      ng       2352: 	my %lasthash=();
                   2353: 	my ($version);
1.119     ng       2354: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2355: 	    foreach my $key (sort(split(/\:/,
                   2356: 					$$returnhash{$version.':keys'}))) {
                   2357: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2358: 		$timestamp = 
                   2359: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2360: 	    }
                   2361: 	}
1.397     albertel 2362: 	foreach my $key (keys(%lasthash)) {
                   2363: 	    next if ($key !~ /\.submission$/);
                   2364: 
                   2365: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2366: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2367: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2368: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2369: 	}
                   2370:     }
1.397     albertel 2371:     if (!@string) {
                   2372: 	$string[0] =
1.398     albertel 2373: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2374:     }
                   2375:     return (\@string,\$timestamp);
1.38      ng       2376: }
1.35      ng       2377: 
1.44      ng       2378: #--- High light keywords, with style choosen by user.
1.38      ng       2379: sub keywords_highlight {
1.44      ng       2380:     my $string    = shift;
1.257     albertel 2381:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2382:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2383:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2384:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2385:     foreach my $keyword (@keylist) {
                   2386: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2387:     }
                   2388:     return $string;
1.38      ng       2389: }
1.36      ng       2390: 
1.44      ng       2391: #--- Called from submission routine
1.38      ng       2392: sub processHandGrade {
1.41      ng       2393:     my ($request) = shift;
1.324     albertel 2394:     my $symb   = &get_symb($request);
                   2395:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2396:     my $button = $env{'form.gradeOpt'};
                   2397:     my $ngrade = $env{'form.NCT'};
                   2398:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2399:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2400:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2401: 
1.44      ng       2402:     if ($button eq 'Save & Next') {
                   2403: 	my $ctr = 0;
                   2404: 	while ($ctr < $ngrade) {
1.257     albertel 2405: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2406: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2407: 	    if ($errorflag eq 'no_score') {
                   2408: 		$ctr++;
                   2409: 		next;
                   2410: 	    }
1.104     albertel 2411: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2412: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2413: 		$ctr++;
                   2414: 		next;
                   2415: 	    }
1.257     albertel 2416: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2417: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2418: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2419:             my ($feedurl,$showsymb) =
                   2420: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2421: 	    my $messagetail;
1.62      albertel 2422: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2423: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2424: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2425: 		$subject.=' ['.$restitle.']';
1.44      ng       2426: 		my (@msgnum) = split(/,/,$includemsg);
                   2427: 		foreach (@msgnum) {
1.257     albertel 2428: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2429: 		}
1.80      ng       2430: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2431: 		if ($env{'form.withgrades'.$ctr}) {
                   2432: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2433: 		    $messagetail = " for <a href=\"".
1.418     albertel 2434: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2435: 		}
                   2436: 		$msgstatus = 
                   2437:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2438: 						     $message.$messagetail,
1.418     albertel 2439:                                                      undef,$feedurl,undef,
1.386     raeburn  2440:                                                      undef,undef,$showsymb,
                   2441:                                                      $restitle);
                   2442: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2443: 				$msgstatus);
1.44      ng       2444: 	    }
1.257     albertel 2445: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2446: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2447: 		foreach my $collabstr (@collabstrs) {
                   2448: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2449: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2450: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2451: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2452: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2453: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2454: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2455: 			    next;
1.418     albertel 2456: 			} elsif ($message ne '') {
                   2457: 			    my ($baseurl,$showsymb) = 
                   2458: 				&get_feedurl_and_symb($symb,$collaborator,
                   2459: 						      $udom);
                   2460: 			    if ($env{'form.withgrades'.$ctr}) {
                   2461: 				$messagetail = " for <a href=\"".
1.386     raeburn  2462:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2463: 			    }
1.418     albertel 2464: 			    $msgstatus = 
                   2465: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2466: 			}
1.44      ng       2467: 		    }
                   2468: 		}
                   2469: 	    }
                   2470: 	    $ctr++;
                   2471: 	}
                   2472:     }
                   2473: 
1.257     albertel 2474:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2475: 	# Keywords sorted in alphabatical order
1.257     albertel 2476: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2477: 	my %keyhash = ();
1.257     albertel 2478: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2479: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2480: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2481: 	$env{'form.keywords'} = join(' ',@keywords);
                   2482: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2483: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2484: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2485: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2486: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2487: 
                   2488: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2489: 	# New messages are saved in env for the next student.
1.119     ng       2490: 	# All messages are saved in nohist_handgrade.db
                   2491: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2492: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2493: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2494: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2495: 		$idx++;
                   2496: 	    }
                   2497: 	    $ctr++;
1.41      ng       2498: 	}
1.119     ng       2499: 	$ctr = 0;
                   2500: 	while ($ctr < $ngrade) {
1.257     albertel 2501: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2502: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2503: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2504: 		$idx++;
                   2505: 	    }
                   2506: 	    $ctr++;
1.41      ng       2507: 	}
1.257     albertel 2508: 	$env{'form.savemsgN'} = --$idx;
                   2509: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2510: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2511: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2512:     }
1.44      ng       2513:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2514:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2515:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2516: 	my ($ctr,$total) = (0,0);
                   2517: 	while ($ctr < $ngrade) {
1.257     albertel 2518: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2519: 	    $ctr++;
                   2520: 	}
1.257     albertel 2521: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2522: 	$ctr = 0;
                   2523: 	while ($ctr < $total) {
1.257     albertel 2524: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2525: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2526: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2527: 	    &submission($request,$ctr,$total-1);
1.41      ng       2528: 	    $ctr++;
                   2529: 	}
                   2530: 	return '';
                   2531:     }
1.36      ng       2532: 
1.121     ng       2533: # Go directly to grade student - from submission or link from chart page
1.120     ng       2534:     if ($button eq 'Grade Student') {
1.324     albertel 2535: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2536: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2537: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2538: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2539: 	&submission($request,0,0);
                   2540: 	return '';
                   2541:     }
                   2542: 
1.44      ng       2543:     # Get the next/previous one or group of students
1.257     albertel 2544:     my $firststu = $env{'form.unamedom0'};
                   2545:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2546:     my $ctr = 2;
1.41      ng       2547:     while ($laststu eq '') {
1.257     albertel 2548: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2549: 	$ctr++;
                   2550: 	$laststu = $firststu if ($ctr > $ngrade);
                   2551:     }
1.44      ng       2552: 
1.41      ng       2553:     my (@parsedlist,@nextlist);
                   2554:     my ($nextflg) = 0;
1.294     albertel 2555:     foreach (sort 
                   2556: 	     {
                   2557: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2558: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2559: 		 }
                   2560: 		 return $a cmp $b;
                   2561: 	     } (keys(%$fullname))) {
1.41      ng       2562: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2563: 	    push @parsedlist,$_;
                   2564: 	}
                   2565: 	$nextflg = 1 if ($_ eq $laststu);
                   2566: 	if ($button eq 'Previous') {
                   2567: 	    last if ($_ eq $firststu);
                   2568: 	    push @parsedlist,$_;
                   2569: 	}
                   2570:     }
                   2571:     $ctr = 0;
                   2572:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2573:     my ($partlist) = &response_type($symb);
1.41      ng       2574:     foreach my $student (@parsedlist) {
1.257     albertel 2575: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2576: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2577: 	
                   2578: 	if ($submitonly eq 'queued') {
                   2579: 	    my %queue_status = 
                   2580: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2581: 							$udom,$uname);
                   2582: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2583: 	}
                   2584: 
1.156     albertel 2585: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2586: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2587: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2588: 	    my $submitted = 0;
1.248     albertel 2589: 	    my $ungraded = 0;
                   2590: 	    my $incorrect = 0;
1.145     albertel 2591: 	    foreach (keys(%status)) {
                   2592: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2593: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2594: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2595: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2596: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2597: 		    $submitted = 0;
                   2598: 		}
1.41      ng       2599: 	    }
1.156     albertel 2600: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2601: 				     $submitonly eq 'incorrect' ||
                   2602: 				     $submitonly eq 'graded'));
1.248     albertel 2603: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2604: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2605: 	}
                   2606: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2607: 	last if ($ctr == $ntstu);
1.41      ng       2608: 	$ctr++;
                   2609:     }
1.36      ng       2610: 
1.41      ng       2611:     $ctr = 0;
                   2612:     my $total = scalar(@nextlist)-1;
1.39      ng       2613: 
1.41      ng       2614:     foreach (sort @nextlist) {
                   2615: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2616: 	$env{'form.student'}  = $uname;
                   2617: 	$env{'form.userdom'}  = $udom;
                   2618: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2619: 	&submission($request,$ctr,$total);
                   2620: 	$ctr++;
                   2621:     }
                   2622:     if ($total < 0) {
1.485     albertel 2623: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2624: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2625: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2626: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2627: 	$request->print($the_end);
                   2628:     }
                   2629:     return '';
1.38      ng       2630: }
1.36      ng       2631: 
1.44      ng       2632: #---- Save the score and award for each student, if changed
1.38      ng       2633: sub saveHandGrade {
1.324     albertel 2634:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2635:     my @version_parts;
1.104     albertel 2636:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2637: 					   $env{'request.course.id'});
1.104     albertel 2638:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2639:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2640:     my @parts_graded;
1.77      ng       2641:     my %newrecord  = ();
                   2642:     my ($pts,$wgt) = ('','');
1.269     raeburn  2643:     my %aggregate = ();
                   2644:     my $aggregateflag = 0;
1.301     albertel 2645:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2646:     foreach my $new_part (@parts) {
1.337     banghart 2647: 	#collaborator ($submi may vary for different parts
1.259     banghart 2648: 	if ($submitter && $new_part ne $part) { next; }
                   2649: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2650: 	if ($dropMenu eq 'excused') {
1.259     banghart 2651: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2652: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2653: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2654: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2655: 		}
1.364     banghart 2656: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2657: 	    }
1.125     ng       2658: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2659: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2660: 	    foreach my $key (keys (%record)) {
1.259     banghart 2661: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2662: 	    }
1.259     banghart 2663: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2664: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2665:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2666: 
                   2667:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2668: 					       [$new_part]);
                   2669:             my $aggtries =$totaltries;
1.269     raeburn  2670:             if ($last_resets{$new_part}) {
1.270     albertel 2671:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2672: 					   $new_part);
1.269     raeburn  2673:             }
1.270     albertel 2674: 
                   2675:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2676:             if ($aggtries > 0) {
1.327     albertel 2677:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2678:                 $aggregateflag = 1;
                   2679:             }
1.125     ng       2680: 	} elsif ($dropMenu eq '') {
1.259     banghart 2681: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2682: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2683: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2684: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2685: 		next;
                   2686: 	    }
1.259     banghart 2687: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2688: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2689: 	    my $partial= $pts/$wgt;
1.259     banghart 2690: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2691: 		#do not update score for part if not changed.
1.346     banghart 2692:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2693: 		next;
1.251     banghart 2694: 	    } else {
1.259     banghart 2695: 	        push @parts_graded, $new_part;
1.153     albertel 2696: 	    }
1.259     banghart 2697: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2698: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2699: 	    }
1.259     banghart 2700: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2701: 	    if ($partial == 0) {
1.153     albertel 2702: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2703: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2704: 		}
1.41      ng       2705: 	    } else {
1.153     albertel 2706: 		if ($record{$reckey} ne 'correct_by_override') {
                   2707: 		    $newrecord{$reckey} = 'correct_by_override';
                   2708: 		}
                   2709: 	    }	    
                   2710: 	    if ($submitter && 
1.259     banghart 2711: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2712: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2713: 	    }
1.259     banghart 2714: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2715: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2716: 	}
1.259     banghart 2717: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2718: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2719: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2720: 	        $dropMenu eq 'reset status')
                   2721: 	   {
1.342     banghart 2722: 	    push (@version_parts,$new_part);
1.259     banghart 2723: 	}
1.41      ng       2724:     }
1.301     albertel 2725:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2726:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2727: 
1.344     albertel 2728:     if (%newrecord) {
                   2729:         if (@version_parts) {
1.364     banghart 2730:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2731:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2732: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2733: 	    foreach my $new_part (@version_parts) {
                   2734: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2735: 				$new_part,\%newrecord);
                   2736: 	    }
1.259     banghart 2737:         }
1.44      ng       2738: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2739: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2740: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2741: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2742:     }
1.269     raeburn  2743:     if ($aggregateflag) {
                   2744:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2745: 			      $cdom,$cnum);
1.269     raeburn  2746:     }
1.301     albertel 2747:     return ('',$pts,$wgt);
1.36      ng       2748: }
1.322     albertel 2749: 
1.380     albertel 2750: sub check_and_remove_from_queue {
                   2751:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2752:     my @ungraded_parts;
                   2753:     foreach my $part (@{$parts}) {
                   2754: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2755: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2756: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2757: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2758: 		) {
                   2759: 	    push(@ungraded_parts, $part);
                   2760: 	}
                   2761:     }
                   2762:     if ( !@ungraded_parts ) {
                   2763: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2764: 					       $cnum,$domain,$stuname);
                   2765:     }
                   2766: }
                   2767: 
1.337     banghart 2768: sub handback_files {
                   2769:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2770:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2771:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2772: 
                   2773:     my @part_response_id = &flatten_responseType($responseType);
                   2774:     foreach my $part_response_id (@part_response_id) {
                   2775:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2776: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2777:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2778:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2779:                 my $file_counter = 1;
1.367     albertel 2780: 		my $file_msg;
1.337     banghart 2781:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2782:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2783:                     my ($directory,$answer_file) = 
                   2784:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2785:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2786: 		        &file_name_version_ext($answer_file);
1.355     banghart 2787: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2788: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2789: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2790:                     # fix file name
                   2791:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2792:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2793:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2794:             	                                $save_file_name);
1.337     banghart 2795:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2796:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2797:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2798:                     } else {
1.360     banghart 2799:                         # mark the file as read only
                   2800:                         my @files = ($save_file_name);
1.372     albertel 2801:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2802:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2803: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2804: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2805: 			}
                   2806:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2807: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2808: 
1.337     banghart 2809:                     }
                   2810:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2811:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2812:                     $file_counter++;
                   2813:                 }
1.367     albertel 2814: 		my $subject = "File Handed Back by Instructor ";
                   2815: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2816: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2817: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2818: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2819: 		my ($feedurl,$showsymb) = 
                   2820: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2821:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2822: 		my $msgstatus = 
                   2823:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2824: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2825:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2826:             }
                   2827:         }
1.338     banghart 2828:     return;
1.337     banghart 2829: }
                   2830: 
1.418     albertel 2831: sub get_feedurl_and_symb {
                   2832:     my ($symb,$uname,$udom) = @_;
                   2833:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2834:     $url = &Apache::lonnet::clutter($url);
                   2835:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2836: 					$symb,$udom,$uname);
                   2837:     if ($encrypturl =~ /^yes$/i) {
                   2838: 	&Apache::lonenc::encrypted(\$url,1);
                   2839: 	&Apache::lonenc::encrypted(\$symb,1);
                   2840:     }
                   2841:     return ($url,$symb);
                   2842: }
                   2843: 
1.313     banghart 2844: sub get_submitted_files {
                   2845:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2846:     my @files;
                   2847:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2848:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2849:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2850:     	    push(@files,$file_url.$file);
                   2851:         }
                   2852:     }
                   2853:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2854:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2855:     }
                   2856:     return (\@files);
                   2857: }
1.322     albertel 2858: 
1.269     raeburn  2859: # ----------- Provides number of tries since last reset.
                   2860: sub get_num_tries {
                   2861:     my ($record,$last_reset,$part) = @_;
                   2862:     my $timestamp = '';
                   2863:     my $num_tries = 0;
                   2864:     if ($$record{'version'}) {
                   2865:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2866:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2867:                 $timestamp = $$record{$version.':timestamp'};
                   2868:                 if ($timestamp > $last_reset) {
                   2869:                     $num_tries ++;
                   2870:                 } else {
                   2871:                     last;
                   2872:                 }
                   2873:             }
                   2874:         }
                   2875:     }
                   2876:     return $num_tries;
                   2877: }
                   2878: 
                   2879: # ----------- Determine decrements required in aggregate totals 
                   2880: sub decrement_aggs {
                   2881:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2882:     my %decrement = (
                   2883:                         attempts => 0,
                   2884:                         users => 0,
                   2885:                         correct => 0
                   2886:                     );
                   2887:     $decrement{'attempts'} = $aggtries;
                   2888:     if ($solvedstatus =~ /^correct/) {
                   2889:         $decrement{'correct'} = 1;
                   2890:     }
                   2891:     if ($aggtries == $totaltries) {
                   2892:         $decrement{'users'} = 1;
                   2893:     }
                   2894:     foreach my $type (keys (%decrement)) {
                   2895:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2896:     }
                   2897:     return;
                   2898: }
                   2899: 
                   2900: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2901: sub get_last_resets {
1.270     albertel 2902:     my ($symb,$courseid,$partids) =@_;
                   2903:     my %last_resets;
1.269     raeburn  2904:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2905:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2906:     my @keys;
                   2907:     foreach my $part (@{$partids}) {
                   2908: 	push(@keys,"$symb\0$part\0resettime");
                   2909:     }
                   2910:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2911: 				     $cdom,$cname);
                   2912:     foreach my $part (@{$partids}) {
                   2913: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2914:     }
1.270     albertel 2915:     return %last_resets;
1.269     raeburn  2916: }
                   2917: 
1.251     banghart 2918: # ----------- Handles creating versions for portfolio files as answers
                   2919: sub version_portfiles {
1.343     banghart 2920:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2921:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2922:     my @returned_keys;
1.255     banghart 2923:     my $parts = join('|', @$parts_graded);
1.359     www      2924:     my $portfolio_root = &propath($domain,$stu_name).
                   2925: 	'/userfiles/portfolio';
1.277     albertel 2926:     foreach my $key (keys(%$record)) {
1.259     banghart 2927:         my $new_portfiles;
1.263     banghart 2928:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2929:             my @versioned_portfiles;
1.367     albertel 2930:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2931:             foreach my $file (@portfiles) {
1.306     banghart 2932:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2933:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2934: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2935: 		    &file_name_version_ext($answer_file);
1.306     banghart 2936:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2937:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2938:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2939:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2940:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2941:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2942:                         [$directory.$new_answer],
1.306     banghart 2943:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2944:                 }
1.252     banghart 2945:             }
1.343     banghart 2946:             $$record{$key} = join(',',@versioned_portfiles);
                   2947:             push(@returned_keys,$key);
1.251     banghart 2948:         }
                   2949:     } 
1.343     banghart 2950:     return (@returned_keys);   
1.305     banghart 2951: }
                   2952: 
1.307     banghart 2953: sub get_next_version {
1.341     banghart 2954:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2955:     my $version;
                   2956:     foreach my $row (@$dir_list) {
                   2957:         my ($file) = split(/\&/,$row,2);
                   2958:         my ($file_name,$file_version,$file_ext) =
                   2959: 	    &file_name_version_ext($file);
                   2960:         if (($file_name eq $answer_name) && 
                   2961: 	    ($file_ext eq $answer_ext)) {
                   2962:                 # gets here if filename and extension match, regardless of version
                   2963:                 if ($file_version ne '') {
                   2964:                 # a versioned file is found  so save it for later
                   2965:                 if ($file_version > $version) {
                   2966: 		    $version = $file_version;
                   2967: 	        }
                   2968:             }
                   2969:         }
                   2970:     } 
                   2971:     $version ++;
                   2972:     return($version);
                   2973: }
                   2974: 
1.305     banghart 2975: sub version_selected_portfile {
1.306     banghart 2976:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2977:     my ($answer_name,$answer_ver,$answer_ext) =
                   2978:         &file_name_version_ext($file_name);
                   2979:     my $new_answer;
                   2980:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2981:     if($env{'form.copy'} eq '-1') {
                   2982:         $new_answer = 'problem getting file';
                   2983:     } else {
                   2984:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2985:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2986:                             $stu_name,$domain,'copy',
                   2987: 		        '/portfolio'.$directory.$new_answer);
                   2988:     }    
                   2989:     return ($new_answer);
1.251     banghart 2990: }
                   2991: 
1.304     albertel 2992: sub file_name_version_ext {
                   2993:     my ($file)=@_;
                   2994:     my @file_parts = split(/\./, $file);
                   2995:     my ($name,$version,$ext);
                   2996:     if (@file_parts > 1) {
                   2997: 	$ext=pop(@file_parts);
                   2998: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2999: 	    $version=pop(@file_parts);
                   3000: 	}
                   3001: 	$name=join('.',@file_parts);
                   3002:     } else {
                   3003: 	$name=join('.',@file_parts);
                   3004:     }
                   3005:     return($name,$version,$ext);
                   3006: }
                   3007: 
1.44      ng       3008: #--------------------------------------------------------------------------------------
                   3009: #
                   3010: #-------------------------- Next few routines handles grading by section or whole class
                   3011: #
                   3012: #--- Javascript to handle grading by section or whole class
1.42      ng       3013: sub viewgrades_js {
                   3014:     my ($request) = shift;
                   3015: 
1.41      ng       3016:     $request->print(<<VIEWJAVASCRIPT);
                   3017: <script type="text/javascript" language="javascript">
1.45      ng       3018:    function writePoint(partid,weight,point) {
1.125     ng       3019: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3020: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3021: 	if (point == "textval") {
1.125     ng       3022: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3023: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3024: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3025: 		var resetbox = false;
                   3026: 		for (var i=0; i<radioButton.length; i++) {
                   3027: 		    if (radioButton[i].checked) {
                   3028: 			textbox.value = i;
                   3029: 			resetbox = true;
                   3030: 		    }
                   3031: 		}
                   3032: 		if (!resetbox) {
                   3033: 		    textbox.value = "";
                   3034: 		}
                   3035: 		return;
                   3036: 	    }
1.109     matthew  3037: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3038: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3039: 				   ") greater than the weight for the part. Accept?");
                   3040: 		if (resp == false) {
                   3041: 		    textbox.value = "";
                   3042: 		    return;
                   3043: 		}
                   3044: 	    }
1.42      ng       3045: 	    for (var i=0; i<radioButton.length; i++) {
                   3046: 		radioButton[i].checked=false;
1.109     matthew  3047: 		if (parseFloat(point) == i) {
1.42      ng       3048: 		    radioButton[i].checked=true;
                   3049: 		}
                   3050: 	    }
1.41      ng       3051: 
1.42      ng       3052: 	} else {
1.125     ng       3053: 	    textbox.value = parseFloat(point);
1.42      ng       3054: 	}
1.41      ng       3055: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3056: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3057: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3058: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3059: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3060: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3061: 	    if (saveval != "correct") {
                   3062: 		scorename.value = point;
1.43      ng       3063: 		if (selname[0].selected != true) {
                   3064: 		    selname[0].selected = true;
                   3065: 		}
1.42      ng       3066: 	    }
                   3067: 	}
1.125     ng       3068: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3069:     }
                   3070: 
                   3071:     function writeRadText(partid,weight) {
1.125     ng       3072: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3073: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3074:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3075: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3076: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3077: 	    for (var i=0; i<radioButton.length; i++) {
                   3078: 		radioButton[i].checked=false;
                   3079: 
                   3080: 	    }
                   3081: 	    textbox.value = "";
                   3082: 
                   3083: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3084: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3085: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3086: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3087: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3088: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3089: 		if ((saveval != "correct") || override) {
1.42      ng       3090: 		    scorename.value = "";
1.125     ng       3091: 		    if (selval[1].selected) {
                   3092: 			selname[1].selected = true;
                   3093: 		    } else {
                   3094: 			selname[2].selected = true;
                   3095: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3096: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3097: 		    }
1.42      ng       3098: 		}
                   3099: 	    }
1.43      ng       3100: 	} else {
                   3101: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3102: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3103: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3104: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3105: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3106: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3107: 		if ((saveval != "correct") || override) {
1.125     ng       3108: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3109: 		    selname[0].selected = true;
                   3110: 		}
                   3111: 	    }
                   3112: 	}	    
1.42      ng       3113:     }
                   3114: 
                   3115:     function changeSelect(partid,user) {
1.125     ng       3116: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3117: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3118: 	var point  = textbox.value;
1.125     ng       3119: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3120: 
1.109     matthew  3121: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3122: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3123: 	    textbox.value = "";
                   3124: 	    return;
                   3125: 	}
1.109     matthew  3126: 	if (parseFloat(point) > parseFloat(weight)) {
                   3127: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3128: 			       ") greater than the weight of the part. Accept?");
                   3129: 	    if (resp == false) {
                   3130: 		textbox.value = "";
                   3131: 		return;
                   3132: 	    }
                   3133: 	}
1.42      ng       3134: 	selval[0].selected = true;
                   3135:     }
                   3136: 
                   3137:     function changeOneScore(partid,user) {
1.125     ng       3138: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3139: 	if (selval[1].selected || selval[2].selected) {
                   3140: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3141: 	    if (selval[2].selected) {
                   3142: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3143: 	    }
1.269     raeburn  3144:         }
1.42      ng       3145:     }
                   3146: 
                   3147:     function resetEntry(numpart) {
                   3148: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3149: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3150: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3151: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3152: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3153: 	    for (var i=0; i<radioButton.length; i++) {
                   3154: 		radioButton[i].checked=false;
                   3155: 
                   3156: 	    }
                   3157: 	    textbox.value = "";
                   3158: 	    selval[0].selected = true;
                   3159: 
                   3160: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3161: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3162: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3163: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3164: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3165: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3166: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3167: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3168: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3169: 		if (saveselval == "excused") {
1.43      ng       3170: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3171: 		} else {
1.43      ng       3172: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3173: 		}
                   3174: 	    }
1.41      ng       3175: 	}
1.42      ng       3176:     }
                   3177: 
1.41      ng       3178: </script>
                   3179: VIEWJAVASCRIPT
1.42      ng       3180: }
                   3181: 
1.44      ng       3182: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3183: sub viewgrades {
                   3184:     my ($request) = shift;
                   3185:     &viewgrades_js($request);
1.41      ng       3186: 
1.324     albertel 3187:     my ($symb) = &get_symb($request);
1.168     albertel 3188:     #need to make sure we have the correct data for later EXT calls, 
                   3189:     #thus invalidate the cache
                   3190:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3191:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3192:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3193:     &Apache::lonnet::clear_EXT_cache_status();
                   3194: 
1.398     albertel 3195:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3196:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3197: 
                   3198:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3199:     $result.=&jscriptNform($symb);
1.41      ng       3200: 
1.44      ng       3201:     #beginning of class grading form
1.442     banghart 3202:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3203:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3204: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3205: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3206: 	&build_section_inputs().
1.257     albertel 3207: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3208: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3209: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3210: 
1.126     ng       3211:     my $sectionClass;
1.430     banghart 3212:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3213:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3214: 	$sectionClass='Class';
1.257     albertel 3215:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3216: 	$sectionClass='Students in no Section';
1.52      albertel 3217:     } else {
1.485     albertel 3218: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3219:     }
1.485     albertel 3220:     $result.=
                   3221: 	'<h3>'.
                   3222: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3223:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3224:     #radio buttons/text box for assigning points for a section or class.
                   3225:     #handles different parts of a problem
1.375     albertel 3226:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3227:     my %weight = ();
                   3228:     my $ctsparts = 0;
1.45      ng       3229:     my %seen = ();
1.375     albertel 3230:     my @part_response_id = &flatten_responseType($responseType);
                   3231:     foreach my $part_response_id (@part_response_id) {
                   3232:     	my ($partid,$respid) = @{ $part_response_id };
                   3233: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3234: 	next if $seen{$partid};
                   3235: 	$seen{$partid}++;
1.375     albertel 3236: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3237: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3238: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3239: 
1.324     albertel 3240: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3241: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3242: 	my $ctr = 0;
1.42      ng       3243: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3244: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3245: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3246: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3247: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3248: 	    $ctr++;
                   3249: 	}
1.485     albertel 3250: 	$radio.='</tr></table>';
                   3251: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3252: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3253: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3254: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3255: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3256: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3257: 		$weight{$partid}.')"> '.
1.401     albertel 3258: 	    '<option selected="selected"> </option>'.
1.485     albertel 3259: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3260: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3261: 	    '</select></td>'.
                   3262:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3263: 	$line.='<input type="hidden" name="partid_'.
                   3264: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3265: 	$line.='<input type="hidden" name="weight_'.
                   3266: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3267: 
                   3268: 	$result.=
                   3269: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3270: 	    &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).
                   3271: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3272: 	$ctsparts++;
1.41      ng       3273:     }
1.474     albertel 3274:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3275: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3276:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3277: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3278: 
1.44      ng       3279:     #table listing all the students in a section/class
                   3280:     #header of table
1.485     albertel 3281:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3282: 			 $section_display).'</h3>';
1.474     albertel 3283:     $result.= &Apache::loncommon::start_data_table().
                   3284: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3285: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3286: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3287:     my (@parts) = sort(&getpartlist($symb));
                   3288:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3289:     my @partids = ();
1.41      ng       3290:     foreach my $part (@parts) {
                   3291: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3292: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3293: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3294: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3295:         push(@partids, $partid);
1.324     albertel 3296: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3297: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3298: 	    $result.='<th>'.
                   3299: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3300: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3301: 	    next;
1.485     albertel 3302: 	    
1.207     albertel 3303: 	} else {
1.485     albertel 3304: 	    if ($display =~ /Problem Status/) {
                   3305: 		my $grade_status_mt = &mt('Grade Status');
                   3306: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3307: 	    }
                   3308: 	    my $part_mt = &mt('Part:');
                   3309: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3310: 	}
1.485     albertel 3311: 
1.474     albertel 3312: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3313:     }
1.474     albertel 3314:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3315: 
1.270     albertel 3316:     my %last_resets = 
                   3317: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3318: 
1.41      ng       3319:     #get info for each student
1.44      ng       3320:     #list all the students - with points and grade status
1.257     albertel 3321:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3322:     my $ctr = 0;
1.294     albertel 3323:     foreach (sort 
                   3324: 	     {
                   3325: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3326: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3327: 		 }
                   3328: 		 return $a cmp $b;
                   3329: 	     } (keys(%$fullname))) {
1.126     ng       3330: 	$ctr++;
1.324     albertel 3331: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3332: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3333:     }
1.474     albertel 3334:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3335:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3336:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3337: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3338:     if (scalar(%$fullname) eq 0) {
                   3339: 	my $colspan=3+scalar(@parts);
1.433     banghart 3340: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3341:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3342: 	$result='<span class="LC_warning">'.
1.485     albertel 3343: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3344: 	        $section_display, $stu_status).
1.433     banghart 3345: 	    '</span>';
1.96      albertel 3346:     }
1.324     albertel 3347:     $result.=&show_grading_menu_form($symb);
1.41      ng       3348:     return $result;
                   3349: }
                   3350: 
1.44      ng       3351: #--- call by previous routine to display each student
1.41      ng       3352: sub viewstudentgrade {
1.324     albertel 3353:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3354:     my ($uname,$udom) = split(/:/,$student);
                   3355:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3356:     my %aggregates = (); 
1.474     albertel 3357:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3358: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3359: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3360: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3361: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3362: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3363:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3364:     foreach my $apart (@$parts) {
                   3365: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3366: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3367:         $result.='<td align="center">';
1.269     raeburn  3368:         my ($aggtries,$totaltries);
                   3369:         unless (exists($aggregates{$part})) {
1.270     albertel 3370: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3371: 
                   3372: 	    $aggtries = $totaltries;
1.269     raeburn  3373:             if ($$last_resets{$part}) {  
1.270     albertel 3374:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3375: 					   $part);
                   3376:             }
1.269     raeburn  3377:             $result.='<input type="hidden" name="'.
                   3378:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3379:             $result.='<input type="hidden" name="'.
                   3380:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3381:             $aggregates{$part} = 1;
                   3382:         }
1.41      ng       3383: 	if ($type eq 'awarded') {
1.320     albertel 3384: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3385: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3386: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3387: 	    $result.='<input type="text" name="'.
1.89      albertel 3388: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3389: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3390: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3391: 	} elsif ($type eq 'solved') {
                   3392: 	    my ($status,$foo)=split(/_/,$score,2);
                   3393: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3394: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3395: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3396: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3397: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3398: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3399: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3400: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3401: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3402: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3403: 	} else {
                   3404: 	    $result.='<input type="hidden" name="'.
                   3405: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3406: 		    "\n";
1.233     albertel 3407: 	    $result.='<input type="text" name="'.
1.122     ng       3408: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3409: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3410: 	}
                   3411:     }
1.474     albertel 3412:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3413:     return $result;
1.38      ng       3414: }
                   3415: 
1.44      ng       3416: #--- change scores for all the students in a section/class
                   3417: #    record does not get update if unchanged
1.38      ng       3418: sub editgrades {
1.41      ng       3419:     my ($request) = @_;
                   3420: 
1.324     albertel 3421:     my $symb=&get_symb($request);
1.433     banghart 3422:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3423:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3424:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3425:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3426: 
1.477     albertel 3427:     my $result= &Apache::loncommon::start_data_table().
                   3428: 	&Apache::loncommon::start_data_table_header_row().
                   3429: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3430: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3431:     my %scoreptr = (
                   3432: 		    'correct'  =>'correct_by_override',
                   3433: 		    'incorrect'=>'incorrect_by_override',
                   3434: 		    'excused'  =>'excused',
                   3435: 		    'ungraded' =>'ungraded_attempted',
                   3436: 		    'nothing'  => '',
                   3437: 		    );
1.257     albertel 3438:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3439: 
1.44      ng       3440:     my (@partid);
                   3441:     my %weight = ();
1.54      albertel 3442:     my %columns = ();
1.44      ng       3443:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3444: 
1.324     albertel 3445:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3446:     my $header;
1.257     albertel 3447:     while ($ctr < $env{'form.totalparts'}) {
                   3448: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3449: 	push @partid,$partid;
1.257     albertel 3450: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3451: 	$ctr++;
1.54      albertel 3452:     }
1.324     albertel 3453:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3454:     foreach my $partid (@partid) {
1.478     albertel 3455: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3456: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3457: 	$columns{$partid}=2;
                   3458: 	foreach my $stores (@parts) {
                   3459: 	    my ($part,$type) = &split_part_type($stores);
                   3460: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3461: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3462: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3463: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3464: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3465: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3466: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3467: 	    $columns{$partid}+=2;
                   3468: 	}
                   3469:     }
                   3470:     foreach my $partid (@partid) {
1.324     albertel 3471: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3472: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3473: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3474: 	    '</th>';
1.54      albertel 3475: 
1.44      ng       3476:     }
1.477     albertel 3477:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3478: 	&Apache::loncommon::start_data_table_header_row().
                   3479: 	$header.
                   3480: 	&Apache::loncommon::end_data_table_header_row();
                   3481:     my @noupdate;
1.126     ng       3482:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3483:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3484: 	my $line;
1.257     albertel 3485: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3486: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3487: 	my %newrecord;
                   3488: 	my $updateflag = 0;
1.281     albertel 3489: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3490: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3491: 	if (!&canmodify($usec)) {
1.126     ng       3492: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3493: 	    push(@noupdate,
1.478     albertel 3494: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3495: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3496: 	    next;
                   3497: 	}
1.269     raeburn  3498:         my %aggregate = ();
                   3499:         my $aggregateflag = 0;
1.281     albertel 3500: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3501: 	foreach (@partid) {
1.257     albertel 3502: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3503: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3504: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3505: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3506: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3507: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3508: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3509: 	    my $score;
                   3510: 	    if ($partial eq '') {
1.257     albertel 3511: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3512: 	    } elsif ($partial > 0) {
                   3513: 		$score = 'correct_by_override';
                   3514: 	    } elsif ($partial == 0) {
                   3515: 		$score = 'incorrect_by_override';
                   3516: 	    }
1.257     albertel 3517: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3518: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3519: 
1.292     albertel 3520: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3521: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3522: 	    if ($dropMenu eq 'reset status' &&
                   3523: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3524: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3525: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3526: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3527: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3528: 		$updateflag = 1;
1.269     raeburn  3529:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3530:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3531:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3532:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3533:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3534:                     $aggregateflag = 1;
                   3535:                 }
1.139     albertel 3536: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3537: 		$updateflag = 1;
                   3538: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3539: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3540: 		$rec_update++;
1.125     ng       3541: 	    }
                   3542: 
1.93      albertel 3543: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3544: 		'<td align="center">'.$awarded.
                   3545: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3546: 
1.54      albertel 3547: 
                   3548: 	    my $partid=$_;
                   3549: 	    foreach my $stores (@parts) {
                   3550: 		my ($part,$type) = &split_part_type($stores);
                   3551: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3552: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3553: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3554: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3555: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3556: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3557: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3558: 		    $updateflag=1;
                   3559: 		}
1.93      albertel 3560: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3561: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3562: 	    }
1.44      ng       3563: 	}
1.477     albertel 3564: 	$line.="\n";
1.301     albertel 3565: 
                   3566: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3567: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3568: 
1.44      ng       3569: 	if ($updateflag) {
                   3570: 	    $count++;
1.257     albertel 3571: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3572: 				    $udom,$uname);
1.301     albertel 3573: 
                   3574: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3575: 					      $cnum,$udom,$uname)) {
                   3576: 		# need to figure out if should be in queue.
                   3577: 		my %record =  
                   3578: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3579: 					     $udom,$uname);
                   3580: 		my $all_graded = 1;
                   3581: 		my $none_graded = 1;
                   3582: 		foreach my $part (@parts) {
                   3583: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3584: 			$all_graded = 0;
                   3585: 		    } else {
                   3586: 			$none_graded = 0;
                   3587: 		    }
                   3588: 		}
                   3589: 
                   3590: 		if ($all_graded || $none_graded) {
                   3591: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3592: 							   $symb,$cdom,$cnum,
                   3593: 							   $udom,$uname);
                   3594: 		}
                   3595: 	    }
                   3596: 
1.477     albertel 3597: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3598: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3599: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3600: 	    $updateCtr++;
1.93      albertel 3601: 	} else {
1.477     albertel 3602: 	    push(@noupdate,
                   3603: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3604: 	    $noupdateCtr++;
1.44      ng       3605: 	}
1.269     raeburn  3606:         if ($aggregateflag) {
                   3607:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3608: 				  $cdom,$cnum);
1.269     raeburn  3609:         }
1.93      albertel 3610:     }
1.477     albertel 3611:     if (@noupdate) {
1.126     ng       3612: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3613: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3614: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3615: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3616: 	    &mt('No Changes Occurred For the Students Below').
                   3617: 	    '</td>'.
1.477     albertel 3618: 	    &Apache::loncommon::end_data_table_row();
                   3619: 	foreach my $line (@noupdate) {
                   3620: 	    $result.=
                   3621: 		&Apache::loncommon::start_data_table_row().
                   3622: 		$line.
                   3623: 		&Apache::loncommon::end_data_table_row();
                   3624: 	}
1.44      ng       3625:     }
1.477     albertel 3626:     $result .= &Apache::loncommon::end_data_table().
                   3627: 	&show_grading_menu_form($symb);
1.478     albertel 3628:     my $msg = '<p><b>'.
                   3629: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3630: 	    $rec_update,$count).'</b><br />'.
                   3631: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3632: 	'</b></p>';
1.44      ng       3633:     return $title.$msg.$result;
1.5       albertel 3634: }
1.54      albertel 3635: 
                   3636: sub split_part_type {
                   3637:     my ($partstr) = @_;
                   3638:     my ($temp,@allparts)=split(/_/,$partstr);
                   3639:     my $type=pop(@allparts);
1.439     albertel 3640:     my $part=join('_',@allparts);
1.54      albertel 3641:     return ($part,$type);
                   3642: }
                   3643: 
1.44      ng       3644: #------------- end of section for handling grading by section/class ---------
                   3645: #
                   3646: #----------------------------------------------------------------------------
                   3647: 
1.5       albertel 3648: 
1.44      ng       3649: #----------------------------------------------------------------------------
                   3650: #
                   3651: #-------------------------- Next few routines handles grading by csv upload
                   3652: #
                   3653: #--- Javascript to handle csv upload
1.27      albertel 3654: sub csvupload_javascript_reverse_associate {
1.246     albertel 3655:     my $error1=&mt('You need to specify the username or ID');
                   3656:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3657:   return(<<ENDPICK);
                   3658:   function verify(vf) {
                   3659:     var foundsomething=0;
                   3660:     var founduname=0;
1.243     albertel 3661:     var foundID=0;
1.27      albertel 3662:     for (i=0;i<=vf.nfields.value;i++) {
                   3663:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3664:       if (i==0 && tw!=0) { foundID=1; }
                   3665:       if (i==1 && tw!=0) { founduname=1; }
                   3666:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3667:     }
1.246     albertel 3668:     if (founduname==0 && foundID==0) {
                   3669: 	alert('$error1');
                   3670: 	return;
1.27      albertel 3671:     }
                   3672:     if (foundsomething==0) {
1.246     albertel 3673: 	alert('$error2');
                   3674: 	return;
1.27      albertel 3675:     }
                   3676:     vf.submit();
                   3677:   }
                   3678:   function flip(vf,tf) {
                   3679:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3680:     var i;
                   3681:     for (i=0;i<=vf.nfields.value;i++) {
                   3682:       //can not pick the same destination field for both name and domain
                   3683:       if (((i ==0)||(i ==1)) && 
                   3684:           ((tf==0)||(tf==1)) && 
                   3685:           (i!=tf) &&
                   3686:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3687:         eval('vf.f'+i+'.selectedIndex=0;')
                   3688:       }
                   3689:     }
                   3690:   }
                   3691: ENDPICK
                   3692: }
                   3693: 
                   3694: sub csvupload_javascript_forward_associate {
1.246     albertel 3695:     my $error1=&mt('You need to specify the username or ID');
                   3696:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3697:   return(<<ENDPICK);
                   3698:   function verify(vf) {
                   3699:     var foundsomething=0;
                   3700:     var founduname=0;
1.243     albertel 3701:     var foundID=0;
1.27      albertel 3702:     for (i=0;i<=vf.nfields.value;i++) {
                   3703:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3704:       if (tw==1) { foundID=1; }
                   3705:       if (tw==2) { founduname=1; }
                   3706:       if (tw>3) { foundsomething=1; }
1.27      albertel 3707:     }
1.246     albertel 3708:     if (founduname==0 && foundID==0) {
                   3709: 	alert('$error1');
                   3710: 	return;
1.27      albertel 3711:     }
                   3712:     if (foundsomething==0) {
1.246     albertel 3713: 	alert('$error2');
                   3714: 	return;
1.27      albertel 3715:     }
                   3716:     vf.submit();
                   3717:   }
                   3718:   function flip(vf,tf) {
                   3719:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3720:     var i;
                   3721:     //can not pick the same destination field twice
                   3722:     for (i=0;i<=vf.nfields.value;i++) {
                   3723:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3724:         eval('vf.f'+i+'.selectedIndex=0;')
                   3725:       }
                   3726:     }
                   3727:   }
                   3728: ENDPICK
                   3729: }
                   3730: 
1.26      albertel 3731: sub csvuploadmap_header {
1.324     albertel 3732:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3733:     my $javascript;
1.257     albertel 3734:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3735: 	$javascript=&csvupload_javascript_reverse_associate();
                   3736:     } else {
                   3737: 	$javascript=&csvupload_javascript_forward_associate();
                   3738:     }
1.45      ng       3739: 
1.324     albertel 3740:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3741:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3742:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3743:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3744:     $request->print(<<ENDPICK);
1.26      albertel 3745: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3746: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3747: $result
1.326     albertel 3748: <hr />
1.26      albertel 3749: <h3>Identify fields</h3>
                   3750: Total number of records found in file: $distotal <hr />
                   3751: Enter as many fields as you can. The system will inform you and bring you back
                   3752: to this page if the data selected is insufficient to run your class.<hr />
                   3753: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3754: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3755: <input type="hidden" name="associate"  value="" />
                   3756: <input type="hidden" name="phase"      value="three" />
                   3757: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3758: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3759: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3760: <input type="hidden" name="upfile_associate" 
1.257     albertel 3761:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3762: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3763: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3764: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3765: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3766: <hr />
                   3767: <script type="text/javascript" language="Javascript">
                   3768: $javascript
                   3769: </script>
                   3770: ENDPICK
1.118     ng       3771:     return '';
1.26      albertel 3772: 
                   3773: }
                   3774: 
                   3775: sub csvupload_fields {
1.324     albertel 3776:     my ($symb) = @_;
                   3777:     my (@parts) = &getpartlist($symb);
1.243     albertel 3778:     my @fields=(['ID','Student ID'],
                   3779: 		['username','Student Username'],
                   3780: 		['domain','Student Domain']);
1.324     albertel 3781:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3782:     foreach my $part (sort(@parts)) {
                   3783: 	my @datum;
                   3784: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3785: 	my $name=$part;
                   3786: 	if  (!$display) { $display = $name; }
                   3787: 	@datum=($name,$display);
1.244     albertel 3788: 	if ($name=~/^stores_(.*)_awarded/) {
                   3789: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3790: 	}
1.41      ng       3791: 	push(@fields,\@datum);
                   3792:     }
                   3793:     return (@fields);
1.26      albertel 3794: }
                   3795: 
                   3796: sub csvuploadmap_footer {
1.41      ng       3797:     my ($request,$i,$keyfields) =@_;
                   3798:     $request->print(<<ENDPICK);
1.26      albertel 3799: </table>
                   3800: <input type="hidden" name="nfields" value="$i" />
                   3801: <input type="hidden" name="keyfields" value="$keyfields" />
                   3802: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3803: </form>
                   3804: ENDPICK
                   3805: }
                   3806: 
1.283     albertel 3807: sub checkforfile_js {
1.86      ng       3808:     my $result =<<CSVFORMJS;
                   3809: <script type="text/javascript" language="javascript">
                   3810:     function checkUpload(formname) {
                   3811: 	if (formname.upfile.value == "") {
                   3812: 	    alert("Please use the browse button to select a file from your local directory.");
                   3813: 	    return false;
                   3814: 	}
                   3815: 	formname.submit();
                   3816:     }
                   3817:     </script>
                   3818: CSVFORMJS
1.283     albertel 3819:     return $result;
                   3820: }
                   3821: 
                   3822: sub upcsvScores_form {
                   3823:     my ($request) = shift;
1.324     albertel 3824:     my ($symb)=&get_symb($request);
1.283     albertel 3825:     if (!$symb) {return '';}
                   3826:     my $result=&checkforfile_js();
1.257     albertel 3827:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3828:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3829:     $result.=$table;
1.326     albertel 3830:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3831:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3832:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3833: 	'.</b></td></tr>'."\n";
                   3834:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3835:     my $upload=&mt("Upload Scores");
1.86      ng       3836:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3837:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3838:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3839:     $result.=<<ENDUPFORM;
1.106     albertel 3840: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3841: <input type="hidden" name="symb" value="$symb" />
                   3842: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3843: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3844: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3845: $upfile_select
1.370     www      3846: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3847: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3848: </form>
                   3849: ENDUPFORM
1.370     www      3850:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3851:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3852:     .'</td></tr></table>'."\n";
1.86      ng       3853:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3854:     $result.=&show_grading_menu_form($symb);
1.86      ng       3855:     return $result;
                   3856: }
                   3857: 
                   3858: 
1.26      albertel 3859: sub csvuploadmap {
1.41      ng       3860:     my ($request)= @_;
1.324     albertel 3861:     my ($symb)=&get_symb($request);
1.41      ng       3862:     if (!$symb) {return '';}
1.72      ng       3863: 
1.41      ng       3864:     my $datatoken;
1.257     albertel 3865:     if (!$env{'form.datatoken'}) {
1.41      ng       3866: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3867:     } else {
1.257     albertel 3868: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3869: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3870:     }
1.41      ng       3871:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3872:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3873:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3874:     my ($i,$keyfields);
                   3875:     if (@records) {
1.324     albertel 3876: 	my @fields=&csvupload_fields($symb);
1.45      ng       3877: 
1.257     albertel 3878: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3879: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3880: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3881: 							  \@fields);
                   3882: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3883: 	    chop($keyfields);
                   3884: 	} else {
                   3885: 	    unshift(@fields,['none','']);
                   3886: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3887: 							    \@fields);
1.311     banghart 3888:             foreach my $rec (@records) {
                   3889:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3890:                 if (%temp) {
                   3891:                     $keyfields=join(',',sort(keys(%temp)));
                   3892:                     last;
                   3893:                 }
                   3894:             }
1.41      ng       3895: 	}
                   3896:     }
                   3897:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3898:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3899: 
1.41      ng       3900:     return '';
1.27      albertel 3901: }
                   3902: 
1.246     albertel 3903: sub csvuploadoptions {
1.41      ng       3904:     my ($request)= @_;
1.324     albertel 3905:     my ($symb)=&get_symb($request);
1.257     albertel 3906:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3907:     my $ignore=&mt('Ignore First Line');
                   3908:     $request->print(<<ENDPICK);
                   3909: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3910: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3911: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3912: <!--
1.246     albertel 3913: <p>
                   3914: <label>
                   3915:    <input type="checkbox" name="show_full_results" />
                   3916:    Show a table of all changes
                   3917: </label>
                   3918: </p>
1.302     albertel 3919: -->
1.246     albertel 3920: <p>
                   3921: <label>
                   3922:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3923:    Overwrite any existing score
                   3924: </label>
                   3925: </p>
                   3926: ENDPICK
                   3927:     my %fields=&get_fields();
                   3928:     if (!defined($fields{'domain'})) {
1.257     albertel 3929: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3930: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3931:     }
1.257     albertel 3932:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3933: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3934: 	my $cleankey=$1;
                   3935: 	if ($cleankey eq 'command') { next; }
                   3936: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3937: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3938:     }
                   3939:     # FIXME do a check for any duplicated user ids...
                   3940:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3941:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3942: <hr /></form>'."\n");
1.324     albertel 3943:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3944:     return '';
                   3945: }
                   3946: 
                   3947: sub get_fields {
                   3948:     my %fields;
1.257     albertel 3949:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3950:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3951: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3952: 	    if ($env{'form.f'.$i} ne 'none') {
                   3953: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3954: 	    }
                   3955: 	} else {
1.257     albertel 3956: 	    if ($env{'form.f'.$i} ne 'none') {
                   3957: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3958: 	    }
                   3959: 	}
1.27      albertel 3960:     }
1.246     albertel 3961:     return %fields;
                   3962: }
                   3963: 
                   3964: sub csvuploadassign {
                   3965:     my ($request)= @_;
1.324     albertel 3966:     my ($symb)=&get_symb($request);
1.246     albertel 3967:     if (!$symb) {return '';}
1.345     bowersj2 3968:     my $error_msg = '';
1.246     albertel 3969:     &Apache::loncommon::load_tmp_file($request);
                   3970:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3971:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3972:     my %fields=&get_fields();
1.41      ng       3973:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3974:     my $courseid=$env{'request.course.id'};
1.97      albertel 3975:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3976:     my @notallowed;
1.41      ng       3977:     my @skipped;
                   3978:     my $countdone=0;
                   3979:     foreach my $grade (@gradedata) {
                   3980: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3981: 	my $domain;
                   3982: 	if ($entries{$fields{'domain'}}) {
                   3983: 	    $domain=$entries{$fields{'domain'}};
                   3984: 	} else {
1.257     albertel 3985: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3986: 	}
1.243     albertel 3987: 	$domain=~s/\s//g;
1.41      ng       3988: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3989: 	$username=~s/\s//g;
1.243     albertel 3990: 	if (!$username) {
                   3991: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3992: 	    $id=~s/\s//g;
1.243     albertel 3993: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3994: 	    $username=$ids{$id};
                   3995: 	}
1.41      ng       3996: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3997: 	    my $id=$entries{$fields{'ID'}};
                   3998: 	    $id=~s/\s//g;
                   3999: 	    if ($id) {
                   4000: 		push(@skipped,"$id:$domain");
                   4001: 	    } else {
                   4002: 		push(@skipped,"$username:$domain");
                   4003: 	    }
1.41      ng       4004: 	    next;
                   4005: 	}
1.108     albertel 4006: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4007: 	if (!&canmodify($usec)) {
                   4008: 	    push(@notallowed,"$username:$domain");
                   4009: 	    next;
                   4010: 	}
1.244     albertel 4011: 	my %points;
1.41      ng       4012: 	my %grades;
                   4013: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4014: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4015: 		$dest eq 'domain') { next; }
                   4016: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4017: 	    if ($dest=~/stores_(.*)_points/) {
                   4018: 		my $part=$1;
                   4019: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4020: 					      $symb,$domain,$username);
1.345     bowersj2 4021:                 if ($wgt) {
                   4022:                     $entries{$fields{$dest}}=~s/\s//g;
                   4023:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4024:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4025:                                           : 'correct_by_override';
1.345     bowersj2 4026:                     $grades{"resource.$part.awarded"}=$pcr;
                   4027:                     $grades{"resource.$part.solved"}=$award;
                   4028:                     $points{$part}=1;
                   4029:                 } else {
                   4030:                     $error_msg = "<br />" .
                   4031:                         &mt("Some point values were assigned"
                   4032:                             ." for problems with a weight "
                   4033:                             ."of zero. These values were "
                   4034:                             ."ignored.");
                   4035:                 }
1.244     albertel 4036: 	    } else {
                   4037: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4038: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4039: 		my $store_key=$dest;
                   4040: 		$store_key=~s/^stores/resource/;
                   4041: 		$store_key=~s/_/\./g;
                   4042: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4043: 	    }
1.41      ng       4044: 	}
1.398     albertel 4045: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 4046: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 4047: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   4048: 					   $env{'request.course.id'},
                   4049: 					   $domain,$username);
                   4050: 	if ($result eq 'ok') {
                   4051: 	    $request->print('.');
                   4052: 	} else {
                   4053: 	    $request->print("<p>
1.398     albertel 4054:                               <span class=\"LC_error\">
                   4055:                                  Failed to save student $username:$domain.
                   4056:                                  Message when trying to save was ($result)
                   4057:                               </span>
1.302     albertel 4058:                              </p>" );
                   4059: 	}
1.41      ng       4060: 	$request->rflush();
                   4061: 	$countdone++;
                   4062:     }
1.398     albertel 4063:     $request->print("<br />Saved $countdone students\n");
1.41      ng       4064:     if (@skipped) {
1.398     albertel 4065: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 4066: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4067:     }
                   4068:     if (@notallowed) {
1.398     albertel 4069: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 4070: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4071:     }
1.106     albertel 4072:     $request->print("<br />\n");
1.324     albertel 4073:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4074:     return $error_msg;
1.26      albertel 4075: }
1.44      ng       4076: #------------- end of section for handling csv file upload ---------
                   4077: #
                   4078: #-------------------------------------------------------------------
                   4079: #
1.122     ng       4080: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4081: #
                   4082: #--- Select a page/sequence and a student to grade
1.68      ng       4083: sub pickStudentPage {
                   4084:     my ($request) = shift;
                   4085: 
                   4086:     $request->print(<<LISTJAVASCRIPT);
                   4087: <script type="text/javascript" language="javascript">
                   4088: 
                   4089: function checkPickOne(formname) {
1.76      ng       4090:     if (radioSelection(formname.student) == null) {
1.68      ng       4091: 	alert("Please select the student you wish to grade.");
                   4092: 	return;
                   4093:     }
1.125     ng       4094:     ptr = pullDownSelection(formname.selectpage);
                   4095:     formname.page.value = formname["page"+ptr].value;
                   4096:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4097:     formname.submit();
                   4098: }
                   4099: 
                   4100: </script>
                   4101: LISTJAVASCRIPT
1.118     ng       4102:     &commonJSfunctions($request);
1.324     albertel 4103:     my ($symb) = &get_symb($request);
1.257     albertel 4104:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4105:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4106:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4107: 
1.398     albertel 4108:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4109: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4110: 
1.80      ng       4111:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4112:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4113:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4114: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4115: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4116:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4117:     my $ctr=0;
1.68      ng       4118:     foreach (@$titles) {
                   4119: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4120: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4121: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4122: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4123: 	$ctr++;
1.68      ng       4124:     }
1.485     albertel 4125:     $select.= '</select>';
                   4126:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4127: 
1.70      ng       4128:     $ctr=0;
                   4129:     foreach (@$titles) {
                   4130: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4131: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4132: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4133: 	$ctr++;
                   4134:     }
1.72      ng       4135:     $result.='<input type="hidden" name="page" />'."\n".
                   4136: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4137: 
1.485     albertel 4138:     my $options =
                   4139: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4140: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4141:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4142: 
                   4143:     $options =
                   4144: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4145: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4146: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4147:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4148:     
                   4149:     $result.=&build_section_inputs();
1.442     banghart 4150:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4151:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4152: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4153: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4154: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4155: 
1.485     albertel 4156:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4157: 			  '<input type="text" name="CODE" value="" />').
                   4158: 			      '<br />'."\n";
1.382     albertel 4159: 
1.80      ng       4160:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4161: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4162: 
1.68      ng       4163:     $request->print($result);
                   4164: 
1.485     albertel 4165:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4166: 	&Apache::loncommon::start_data_table().
                   4167: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4168: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4169: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4170: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4171: 	'<th>'.&nameUserString('header').'</th>'.
                   4172: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4173:  
1.76      ng       4174:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4175:     my $ptr = 1;
1.294     albertel 4176:     foreach my $student (sort 
                   4177: 			 {
                   4178: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4179: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4180: 			     }
                   4181: 			     return $a cmp $b;
                   4182: 			 } (keys(%$fullname))) {
1.68      ng       4183: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4184: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4185:                                   : '</td>');
1.126     ng       4186: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4187: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4188: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4189: 	$studentTable.=
                   4190: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4191:                          : '');
1.68      ng       4192: 	$ptr++;
                   4193:     }
1.484     albertel 4194:     if ($ptr%2 == 0) {
                   4195: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4196: 	    &Apache::loncommon::end_data_table_row();
                   4197:     }
                   4198:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4199:     $studentTable.='<input type="button" '.
1.485     albertel 4200: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4201: 
1.324     albertel 4202:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4203:     $request->print($studentTable);
                   4204: 
                   4205:     return '';
                   4206: }
                   4207: 
                   4208: sub getSymbMap {
1.132     bowersj2 4209:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4210: 
                   4211:     my %symbx = ();
                   4212:     my @titles = ();
1.117     bowersj2 4213:     my $minder = 0;
                   4214: 
                   4215:     # Gather every sequence that has problems.
1.240     albertel 4216:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4217: 					       1,0,1);
1.117     bowersj2 4218:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4219: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4220: 	    my $title = $minder.'.'.
                   4221: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4222: 	    push(@titles, $title); # minder in case two titles are identical
                   4223: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4224: 	    $minder++;
1.241     albertel 4225: 	}
1.68      ng       4226:     }
                   4227:     return \@titles,\%symbx;
                   4228: }
                   4229: 
1.72      ng       4230: #
                   4231: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4232: sub displayPage {
                   4233:     my ($request) = shift;
                   4234: 
1.324     albertel 4235:     my ($symb) = &get_symb($request);
1.257     albertel 4236:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4237:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4238:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4239:     my $pageTitle = $env{'form.page'};
1.103     albertel 4240:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4241:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4242:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4243: 
                   4244:     #need to make sure we have the correct data for later EXT calls, 
                   4245:     #thus invalidate the cache
                   4246:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4247:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4248:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4249:     &Apache::lonnet::clear_EXT_cache_status();
                   4250: 
1.103     albertel 4251:     if (!&canview($usec)) {
1.485     albertel 4252: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4253: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4254: 	return;
                   4255:     }
1.398     albertel 4256:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4257:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4258: 	'</h3>'."\n";
1.382     albertel 4259:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
1.485     albertel 4260: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4261:     } else {
                   4262: 	delete($env{'form.CODE'});
                   4263:     }
1.71      ng       4264:     &sub_page_js($request);
                   4265:     $request->print($result);
                   4266: 
1.132     bowersj2 4267:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4268:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4269:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4270:     if (!$map) {
1.485     albertel 4271: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4272: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4273: 	return; 
                   4274:     }
1.68      ng       4275:     my $iterator = $navmap->getIterator($map->map_start(),
                   4276: 					$map->map_finish());
                   4277: 
1.71      ng       4278:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4279: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4280: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4281: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4282: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4283: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4284: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4285: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4286: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4287: 
1.382     albertel 4288:     if (defined($env{'form.CODE'})) {
                   4289: 	$studentTable.=
                   4290: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4291:     }
1.381     albertel 4292:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4293: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4294: 
1.485     albertel 4295:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4296: 	&Apache::loncommon::start_data_table().
                   4297: 	&Apache::loncommon::start_data_table_header_row().
                   4298: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4299: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4300: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4301: 
1.329     albertel 4302:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4303:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4304:     $iterator->next(); # skip the first BEGIN_MAP
                   4305:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4306:     while ($depth > 0) {
1.68      ng       4307:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4308:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4309: 
1.385     albertel 4310:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4311: 	    my $parts = $curRes->parts();
1.68      ng       4312:             my $title = $curRes->compTitle();
1.71      ng       4313: 	    my $symbx = $curRes->symb();
1.484     albertel 4314: 	    $studentTable.=
                   4315: 		&Apache::loncommon::start_data_table_row().
                   4316: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4317: 		(scalar(@{$parts}) == 1 ? '' 
                   4318: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4319: 							scalar(@{$parts}))
                   4320: 		 ).
                   4321: 		 '</td>';
1.71      ng       4322: 	    $studentTable.='<td valign="top">';
1.382     albertel 4323: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4324: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4325: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4326: 					     undef,'both',\%form);
1.71      ng       4327: 	    } else {
1.382     albertel 4328: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4329: 		$companswer =~ s|<form(.*?)>||g;
                   4330: 		$companswer =~ s|</form>||g;
1.71      ng       4331: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4332: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4333: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4334: #		}
1.116     ng       4335: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4336: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4337: 	    }
                   4338: 
1.257     albertel 4339: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4340: 
1.257     albertel 4341: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4342: 		if ($record{'version'} eq '') {
1.485     albertel 4343: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4344: 		} else {
1.116     ng       4345: 		    my %responseType = ();
                   4346: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4347: 			my @responseIds =$curRes->responseIds($partid);
                   4348: 			my @responseType =$curRes->responseType($partid);
                   4349: 			my %responseIds;
                   4350: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4351: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4352: 			}
                   4353: 			$responseType{$partid} = \%responseIds;
1.116     ng       4354: 		    }
1.148     albertel 4355: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4356: 
1.71      ng       4357: 		}
1.257     albertel 4358: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4359: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4360: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4361: 									$env{'request.course.id'},
1.71      ng       4362: 									'','.submission');
                   4363:  
                   4364: 	    }
1.103     albertel 4365: 	    if (&canmodify($usec)) {
                   4366: 		foreach my $partid (@{$parts}) {
                   4367: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4368: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4369: 		    $question++;
                   4370: 		}
1.196     albertel 4371: 		$prob++;
1.71      ng       4372: 	    }
                   4373: 	    $studentTable.='</td></tr>';
1.68      ng       4374: 
1.103     albertel 4375: 	}
1.68      ng       4376:         $curRes = $iterator->next();
                   4377:     }
                   4378: 
1.485     albertel 4379:     $studentTable.='</table>'."\n".
                   4380: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4381: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4382: 	'</form>'."\n";
1.324     albertel 4383:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4384:     $request->print($studentTable);
                   4385: 
                   4386:     return '';
1.119     ng       4387: }
                   4388: 
                   4389: sub displaySubByDates {
1.148     albertel 4390:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4391:     my $isCODE=0;
1.335     albertel 4392:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4393:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4394:     my $studentTable=&Apache::loncommon::start_data_table().
                   4395: 	&Apache::loncommon::start_data_table_header_row().
                   4396: 	'<th>'.&mt('Date/Time').'</th>'.
                   4397: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4398: 	'<th>'.&mt('Submission').'</th>'.
                   4399: 	'<th>'.&mt('Status').'</th>'.
                   4400: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4401:     my ($version);
                   4402:     my %mark;
1.148     albertel 4403:     my %orders;
1.119     ng       4404:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4405:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4406: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4407:     }
1.335     albertel 4408: 
                   4409:     my $interaction;
1.119     ng       4410:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4411: 	my $timestamp = 
                   4412: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4413: 	if (exists($$record{$version.':resource.0.version'})) {
                   4414: 	    $interaction = $$record{$version.':resource.0.version'};
                   4415: 	}
                   4416: 
                   4417: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4418: 		             : "$version:resource");
1.467     albertel 4419: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4420: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4421: 	if ($isCODE) {
                   4422: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4423: 	}
1.119     ng       4424: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4425: 	my @displaySub = ();
                   4426: 	foreach my $partid (@{$parts}) {
1.335     albertel 4427: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4428: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4429: 	    
                   4430: 
1.122     ng       4431: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4432: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4433: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4434: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4435: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4436: 
                   4437: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4438: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4439: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4440: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4441: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4442: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4443: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4444: 		    } else {
1.467     albertel 4445: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4446: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4447: 		    }
1.335     albertel 4448: 		    my $responseType=($isTask ? 'Task'
                   4449:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4450: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4451: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4452: 			$orders{$partid}->{$responseId}=
                   4453: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4454: 		    }
1.147     albertel 4455: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4456: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4457: 		}
                   4458: 	    }
1.335     albertel 4459: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4460: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4461: 				    $$record{"$where.$partid.checkedin"},
                   4462: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4463: 					'<br />';
1.335     albertel 4464: 	    }
                   4465: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4466: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4467: 		    lc($$record{"$where.$partid.award"}).' '.
                   4468: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4469: 		    '<br />';
                   4470: 	    }
1.335     albertel 4471: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4472: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4473: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4474: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4475: 		$displaySub[2].=
                   4476: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4477: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4478: 	    }
                   4479: 	}
                   4480: 	# needed because old essay regrader has not parts info
                   4481: 	if (exists $$record{"$version:resource.regrader"}) {
                   4482: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4483: 	}
                   4484: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4485: 	if ($displaySub[2]) {
1.467     albertel 4486: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4487: 	}
1.467     albertel 4488: 	$studentTable.='&nbsp;</td>'.
                   4489: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4490:     }
1.467     albertel 4491:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4492:     return $studentTable;
1.71      ng       4493: }
                   4494: 
                   4495: sub updateGradeByPage {
                   4496:     my ($request) = shift;
                   4497: 
1.257     albertel 4498:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4499:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4500:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4501:     my $pageTitle = $env{'form.page'};
1.103     albertel 4502:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4503:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4504:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4505:     if (!&canmodify($usec)) {
1.398     albertel 4506: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4507: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4508: 	return;
                   4509:     }
1.398     albertel 4510:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4511:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4512: 	'</h3>'."\n";
1.70      ng       4513: 
1.68      ng       4514:     $request->print($result);
                   4515: 
1.132     bowersj2 4516:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4517:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4518:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4519:     if (!$map) {
1.398     albertel 4520: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4521: 	my ($symb)=&get_symb($request);
                   4522: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4523: 	return; 
                   4524:     }
1.71      ng       4525:     my $iterator = $navmap->getIterator($map->map_start(),
                   4526: 					$map->map_finish());
1.70      ng       4527: 
1.484     albertel 4528:     my $studentTable=
                   4529: 	&Apache::loncommon::start_data_table().
                   4530: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4531: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4532: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4533: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4534: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4535: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4536: 
                   4537:     $iterator->next(); # skip the first BEGIN_MAP
                   4538:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4539:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4540:     while ($depth > 0) {
1.71      ng       4541:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4542:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4543: 
1.385     albertel 4544:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4545: 	    my $parts = $curRes->parts();
1.71      ng       4546:             my $title = $curRes->compTitle();
                   4547: 	    my $symbx = $curRes->symb();
1.484     albertel 4548: 	    $studentTable.=
                   4549: 		&Apache::loncommon::start_data_table_row().
                   4550: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4551: 		(scalar(@{$parts}) == 1 ? '' 
                   4552:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
                   4553: 		 ).')</td>';
1.71      ng       4554: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4555: 
                   4556: 	    my %newrecord=();
                   4557: 	    my @displayPts=();
1.269     raeburn  4558:             my %aggregate = ();
                   4559:             my $aggregateflag = 0;
1.71      ng       4560: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4561: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4562: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4563: 
1.257     albertel 4564: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4565: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4566: 		my $partial = $newpts/$wgt;
                   4567: 		my $score;
                   4568: 		if ($partial > 0) {
                   4569: 		    $score = 'correct_by_override';
1.125     ng       4570: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4571: 		    $score = 'incorrect_by_override';
                   4572: 		}
1.257     albertel 4573: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4574: 		if ($dropMenu eq 'excused') {
1.71      ng       4575: 		    $partial = '';
                   4576: 		    $score = 'excused';
1.125     ng       4577: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4578: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4579: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4580: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4581: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4582: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4583: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4584: 		    $changeflag++;
                   4585: 		    $newpts = '';
1.269     raeburn  4586:                     
                   4587:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4588:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4589:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4590:                     if ($aggtries > 0) {
                   4591:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4592:                         $aggregateflag = 1;
                   4593:                     }
1.71      ng       4594: 		}
1.324     albertel 4595: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4596: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4597: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4598: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4599: 		    '&nbsp;<br />';
1.207     albertel 4600: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4601: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4602: 		    '&nbsp;<br />';
1.71      ng       4603: 		$question++;
1.380     albertel 4604: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4605: 
1.71      ng       4606: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4607: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4608: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4609: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4610: 
                   4611: 		$changeflag++;
                   4612: 	    }
                   4613: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4614: 		my %record = 
                   4615: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4616: 					     $udom,$uname);
                   4617: 
                   4618: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4619: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4620: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4621: 		    $newrecord{'resource.CODE'} = '';
                   4622: 		}
1.257     albertel 4623: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4624: 					$udom,$uname);
1.382     albertel 4625: 		%record = &Apache::lonnet::restore($symbx,
                   4626: 						   $env{'request.course.id'},
                   4627: 						   $udom,$uname);
1.380     albertel 4628: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4629: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4630: 	    }
1.380     albertel 4631: 	    
1.269     raeburn  4632:             if ($aggregateflag) {
                   4633:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4634:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4635:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4636:             }
1.125     ng       4637: 
1.71      ng       4638: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4639: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4640: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4641: 
1.196     albertel 4642: 	    $prob++;
1.68      ng       4643: 	}
1.71      ng       4644:         $curRes = $iterator->next();
1.68      ng       4645:     }
1.98      albertel 4646: 
1.484     albertel 4647:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4648:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4649:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4650: 		  'The scores were changed for '.
                   4651: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4652:     $request->print($grademsg.$studentTable);
1.68      ng       4653: 
1.70      ng       4654:     return '';
                   4655: }
                   4656: 
1.72      ng       4657: #-------- end of section for handling grading by page/sequence ---------
                   4658: #
                   4659: #-------------------------------------------------------------------
                   4660: 
1.75      albertel 4661: #--------------------Scantron Grading-----------------------------------
                   4662: #
                   4663: #------ start of section for handling grading by page/sequence ---------
                   4664: 
1.423     albertel 4665: =pod
                   4666: 
                   4667: =head1 Bubble sheet grading routines
                   4668: 
1.424     albertel 4669:   For this documentation:
                   4670: 
                   4671:    'scanline' refers to the full line of characters
                   4672:    from the file that we are parsing that represents one entire sheet
                   4673: 
                   4674:    'bubble line' refers to the data
                   4675:    representing the line of bubbles that are on the physical bubble sheet
                   4676: 
                   4677: 
                   4678: The overall process is that a scanned in bubble sheet data is uploaded
                   4679: into a course. When a user wants to grade, they select a
                   4680: sequence/folder of resources, a file of bubble sheet info, and pick
                   4681: one of the predefined configurations for what each scanline looks
                   4682: like.
                   4683: 
                   4684: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4685: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4686: because too light bubbling), 'double bubble' (each bubble line should
                   4687: have no more that one letter picked), invalid or duplicated CODE,
                   4688: invalid student ID
                   4689: 
                   4690: If the CODE option is used that determines the randomization of the
                   4691: homework problems, either way the student ID is looked up into a
                   4692: username:domain.
                   4693: 
                   4694: During the validation phase the instructor can choose to skip scanlines. 
                   4695: 
1.435     foxr     4696: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4697: 
                   4698:   scantron_original_filename (unmodified original file)
                   4699:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4700:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4701: 
                   4702: Also there is a separate hash nohist_scantrondata that contains extra
                   4703: correction information that isn't representable in the bubble sheet
                   4704: file (see &scantron_getfile() for more information)
                   4705: 
                   4706: After all scanlines are either valid, marked as valid or skipped, then
                   4707: foreach line foreach problem in the picked sequence, an ssi request is
                   4708: made that simulates a user submitting their selected letter(s) against
                   4709: the homework problem.
1.423     albertel 4710: 
                   4711: =over 4
                   4712: 
                   4713: 
                   4714: 
                   4715: =item defaultFormData
                   4716: 
                   4717:   Returns html hidden inputs used to hold context/default values.
                   4718: 
                   4719:  Arguments:
                   4720:   $symb - $symb of the current resource 
                   4721: 
                   4722: =cut
1.422     foxr     4723: 
1.81      albertel 4724: sub defaultFormData {
1.324     albertel 4725:     my ($symb)=@_;
1.447     foxr     4726:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4727:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4728:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4729: }
                   4730: 
1.447     foxr     4731: 
1.423     albertel 4732: =pod 
                   4733: 
                   4734: =item getSequenceDropDown
                   4735: 
                   4736:    Return html dropdown of possible sequences to grade
                   4737:  
                   4738:  Arguments:
                   4739:    $symb - $symb of the current resource 
                   4740: 
                   4741: =cut
1.422     foxr     4742: 
1.75      albertel 4743: sub getSequenceDropDown {
1.423     albertel 4744:     my ($symb)=@_;
1.75      albertel 4745:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4746:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4747:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4748:     my $ctr=0;
                   4749:     foreach (@$titles) {
                   4750: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4751: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4752: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4753: 	    '>'.$showtitle.'</option>'."\n";
                   4754: 	$ctr++;
                   4755:     }
                   4756:     $result.= '</select>';
                   4757:     return $result;
                   4758: }
                   4759: 
1.423     albertel 4760: 
                   4761: =pod 
                   4762: 
                   4763: =item scantron_filenames
                   4764: 
                   4765:    Returns a list of the scantron files in the current course 
                   4766: 
                   4767: =cut
1.422     foxr     4768: 
1.202     albertel 4769: sub scantron_filenames {
1.257     albertel 4770:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4771:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4772:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4773: 				    &propath($cdom,$cname));
1.202     albertel 4774:     my @possiblenames;
1.201     albertel 4775:     foreach my $filename (sort(@files)) {
1.157     albertel 4776: 	($filename)=split(/&/,$filename);
                   4777: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4778: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4779: 	push(@possiblenames,$filename);
                   4780:     }
                   4781:     return @possiblenames;
                   4782: }
                   4783: 
1.423     albertel 4784: =pod 
                   4785: 
                   4786: =item scantron_uploads
                   4787: 
                   4788:    Returns  html drop-down list of scantron files in current course.
                   4789: 
                   4790:  Arguments:
                   4791:    $file2grade - filename to set as selected in the dropdown
                   4792: 
                   4793: =cut
1.422     foxr     4794: 
1.202     albertel 4795: sub scantron_uploads {
1.209     ng       4796:     my ($file2grade) = @_;
1.202     albertel 4797:     my $result=	'<select name="scantron_selectfile">';
                   4798:     $result.="<option></option>";
                   4799:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4800: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4801:     }
                   4802:     $result.="</select>";
                   4803:     return $result;
                   4804: }
                   4805: 
1.423     albertel 4806: =pod 
                   4807: 
                   4808: =item scantron_scantab
                   4809: 
                   4810:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4811:   file.
                   4812: 
                   4813: =cut
1.422     foxr     4814: 
1.82      albertel 4815: sub scantron_scantab {
                   4816:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4817:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4818:     $result.='<option></option>'."\n";
1.82      albertel 4819:     foreach my $line (<$fh>) {
                   4820: 	my ($name,$descrip)=split(/:/,$line);
                   4821: 	if ($name =~ /^\#/) { next; }
                   4822: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4823:     }
                   4824:     $result.='</select>'."\n";
                   4825: 
                   4826:     return $result;
                   4827: }
                   4828: 
1.423     albertel 4829: =pod 
                   4830: 
                   4831: =item scantron_CODElist
                   4832: 
                   4833:   Returns html drop down of the saved CODE lists from current course,
                   4834:   generated from earlier printings.
                   4835: 
                   4836: =cut
1.422     foxr     4837: 
1.186     albertel 4838: sub scantron_CODElist {
1.257     albertel 4839:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4840:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4841:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4842:     my $namechoice='<option></option>';
1.225     albertel 4843:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4844: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4845: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4846: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4847:     }
                   4848:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4849:     return $namechoice;
                   4850: }
                   4851: 
1.423     albertel 4852: =pod 
                   4853: 
                   4854: =item scantron_CODEunique
                   4855: 
                   4856:   Returns the html for "Each CODE to be used once" radio.
                   4857: 
                   4858: =cut
1.422     foxr     4859: 
1.186     albertel 4860: sub scantron_CODEunique {
1.381     albertel 4861:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4862:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4863:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4864:                 </span>
                   4865:                 <span style="white-space: nowrap;">
1.272     albertel 4866:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4867:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4868:                 </span>';
1.186     albertel 4869:     return $result;
                   4870: }
1.423     albertel 4871: 
                   4872: =pod 
                   4873: 
                   4874: =item scantron_selectphase
                   4875: 
                   4876:   Generates the initial screen to start the bubble sheet process.
                   4877:   Allows for - starting a grading run.
1.424     albertel 4878:              - downloading existing scan data (original, corrected
1.423     albertel 4879:                                                 or skipped info)
                   4880: 
                   4881:              - uploading new scan data
                   4882: 
                   4883:  Arguments:
                   4884:   $r          - The Apache request object
                   4885:   $file2grade - name of the file that contain the scanned data to score
                   4886: 
                   4887: =cut
1.186     albertel 4888: 
1.75      albertel 4889: sub scantron_selectphase {
1.209     ng       4890:     my ($r,$file2grade) = @_;
1.324     albertel 4891:     my ($symb)=&get_symb($r);
1.75      albertel 4892:     if (!$symb) {return '';}
1.423     albertel 4893:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4894:     my $default_form_data=&defaultFormData($symb);
                   4895:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4896:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4897:     my $format_selector=&scantron_scantab();
1.186     albertel 4898:     my $CODE_selector=&scantron_CODElist();
                   4899:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4900:     my $result;
1.422     foxr     4901: 
                   4902:     # Chunk of form to prompt for a file to grade and how:
                   4903: 
1.489     albertel 4904:     $result.= '
                   4905:     <br />
                   4906:     <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
                   4907:     <input type="hidden" name="command" value="scantron_warning" />
                   4908:     '.$default_form_data.'
                   4909:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4910:        '.&Apache::loncommon::start_data_table_header_row().'
                   4911:             <th colspan="2">
1.492     albertel 4912:               &nbsp;'.&mt('Specify file and which Folder/Sequence to grade').'
1.489     albertel 4913:             </th>
                   4914:        '.&Apache::loncommon::end_data_table_header_row().'
                   4915:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4916:             <td> '.&mt('Sequence to grade:').' </td><td> '.$sequence_selector.' </td>
1.489     albertel 4917:        '.&Apache::loncommon::end_data_table_row().'
                   4918:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4919:             <td> '.&mt('Filename of scoring office file:').' </td><td> '.$file_selector.' </td>
1.489     albertel 4920:        '.&Apache::loncommon::end_data_table_row().'
                   4921:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4922:             <td> '.&mt('Format of data file:').' </td><td> '.$format_selector.' </td>
1.489     albertel 4923:        '.&Apache::loncommon::end_data_table_row().'
                   4924:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4925:             <td> '.&mt('Saved CODEs to validate against:').' </td><td> '.$CODE_selector.' </td>
1.489     albertel 4926:        '.&Apache::loncommon::end_data_table_row().'
                   4927:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4928:             <td> '.&mt('Each CODE is only to be used once:').'</td><td> '.$CODE_unique.' </td>
1.489     albertel 4929:        '.&Apache::loncommon::end_data_table_row().'
                   4930:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 4931: 	    <td> '.&mt('Options:').' </td>
1.187     albertel 4932:             <td>
1.492     albertel 4933: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> '.&mt('Do only previously skipped records').'</label> <br />
                   4934:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> '.&mt('Remove all existing corrections').'</label> <br />
                   4935:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> '.&mt('Skip hidden resources when grading').'</label>
1.187     albertel 4936: 	    </td>
1.489     albertel 4937:        '.&Apache::loncommon::end_data_table_row().'
                   4938:        '.&Apache::loncommon::start_data_table_row().'
1.174     albertel 4939:             <td colspan="2">
1.492     albertel 4940:               <input type="submit" value="'.&mt('Grading: Validate Scantron Records').'" />
1.162     albertel 4941:             </td>
1.489     albertel 4942:        '.&Apache::loncommon::end_data_table_row().'
                   4943:     '.&Apache::loncommon::end_data_table().'
                   4944:     </form>
                   4945: ';
1.162     albertel 4946:    
                   4947:     $r->print($result);
                   4948: 
1.257     albertel 4949:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4950:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4951: 
1.422     foxr     4952: 	# Chunk of form to prompt for a scantron file upload.
                   4953: 
1.489     albertel 4954:         $r->print('
                   4955:     <br />
                   4956:     '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   4957:        '.&Apache::loncommon::start_data_table_header_row().'
                   4958:             <th>
1.492     albertel 4959:               &nbsp;'.&mt('Specify a Scantron data file to upload.').'
1.489     albertel 4960:             </th>
                   4961:        '.&Apache::loncommon::end_data_table_header_row().'
                   4962:        '.&Apache::loncommon::start_data_table_row().'
1.162     albertel 4963:             <td>
1.489     albertel 4964: ');
1.324     albertel 4965:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4966:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4967:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.492     albertel 4968:     $r->print('
1.174     albertel 4969:               <script type="text/javascript" language="javascript">
                   4970:     function checkUpload(formname) {
                   4971: 	if (formname.upfile.value == "") {
1.492     albertel 4972: 	    alert("'.&mt('Please use the browse button to select a file from your local directory.').'");
1.174     albertel 4973: 	    return false;
                   4974: 	}
                   4975: 	formname.submit();
                   4976:     }
                   4977:               </script>
                   4978: 
1.492     albertel 4979:               <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   4980:                 '.$default_form_data.'
                   4981:                 <input name="courseid" type="hidden" value="'.$cnum.'" />
                   4982:                 <input name="domainid" type="hidden" value="'.$cdom.'" />
                   4983:                 <input name="command" value="scantronupload_save" type="hidden" />
                   4984:                 '.&mt('File to upload: [_1]','<input type="file" name="upfile" size="50" />').'
1.174     albertel 4985:                 <br />
1.492     albertel 4986:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.174     albertel 4987:               </form>
1.492     albertel 4988: ');
1.162     albertel 4989: 
1.489     albertel 4990:         $r->print('
1.162     albertel 4991:             </td>
1.489     albertel 4992:        '.&Apache::loncommon::end_data_table_row().'
                   4993:        '.&Apache::loncommon::end_data_table().'
                   4994: ');
1.162     albertel 4995:     }
1.422     foxr     4996: 
                   4997:     # Chunk of the form that prompts to view a scoring office file,
                   4998:     # corrected file, skipped records in a file.
                   4999: 
1.489     albertel 5000:     $r->print('
                   5001:    <br />
                   5002:    <form action="/adm/grades" name="scantron_download">
                   5003:      '.$default_form_data.'
                   5004:      <input type="hidden" name="command" value="scantron_download" />
                   5005:      '.&Apache::loncommon::start_data_table('LC_scantron_action').'
                   5006:        '.&Apache::loncommon::start_data_table_header_row().'
                   5007:               <th>
1.492     albertel 5008:                 &nbsp;'.&mt('Download a scoring office file').'
1.489     albertel 5009:               </th>
                   5010:        '.&Apache::loncommon::end_data_table_header_row().'
                   5011:        '.&Apache::loncommon::start_data_table_row().'
1.492     albertel 5012:               <td> '.&mt('Filename of scoring office file: [_1]',$file_selector).' 
1.489     albertel 5013:                 <br />
1.492     albertel 5014:                 <input type="submit" value="'.&mt('Download: Show List of Associated Files').'" />
1.489     albertel 5015:        '.&Apache::loncommon::end_data_table_row().'
                   5016:      '.&Apache::loncommon::end_data_table().'
                   5017:    </form>
                   5018:    <br />
                   5019: ');
1.162     albertel 5020: 
1.457     banghart 5021:     &Apache::lonpickcode::code_list($r,2);
                   5022:     $r->print($grading_menu_button);
1.162     albertel 5023:     return
1.75      albertel 5024: }
                   5025: 
1.423     albertel 5026: =pod
                   5027: 
                   5028: =item get_scantron_config
                   5029: 
                   5030:    Parse and return the scantron configuration line selected as a
                   5031:    hash of configuration file fields.
                   5032: 
                   5033:  Arguments:
                   5034:     which - the name of the configuration to parse from the file.
                   5035: 
                   5036: 
                   5037:  Returns:
                   5038:             If the named configuration is not in the file, an empty
                   5039:             hash is returned.
                   5040:     a hash with the fields
                   5041:       name         - internal name for the this configuration setup
                   5042:       description  - text to display to operator that describes this config
                   5043:       CODElocation - if 0 or the string 'none'
                   5044:                           - no CODE exists for this config
                   5045:                      if -1 || the string 'letter'
                   5046:                           - a CODE exists for this config and is
                   5047:                             a string of letters
                   5048:                      Unsupported value (but planned for future support)
                   5049:                           if a positive integer
                   5050:                                - The CODE exists as the first n items from
                   5051:                                  the question section of the form
                   5052:                           if the string 'number'
                   5053:                                - The CODE exists for this config and is
                   5054:                                  a string of numbers
                   5055:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5056:                      the CODE starts
                   5057:       CODElength  - length of the CODE
                   5058:       IDstart     - column where the student ID number starts
                   5059:       IDlength    - length of the student ID info
                   5060:       Qstart      - column where the information from the bubbled
                   5061:                     'questions' start
                   5062:       Qlength     - number of columns comprising a single bubble line from
                   5063:                     the sheet. (usually either 1 or 10)
1.424     albertel 5064:       Qon         - either a single character representing the character used
1.423     albertel 5065:                     to signal a bubble was chosen in the positional setup, or
                   5066:                     the string 'letter' if the letter of the chosen bubble is
                   5067:                     in the final, or 'number' if a number representing the
                   5068:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5069:       Qoff        - the character used to represent that a bubble was
                   5070:                     left blank
1.423     albertel 5071:       PaperID     - if the scanning process generates a unique number for each
                   5072:                     sheet scanned the column that this ID number starts in
                   5073:       PaperIDlength - number of columns that comprise the unique ID number
                   5074:                       for the sheet of paper
1.424     albertel 5075:       FirstName   - column that the first name starts in
1.423     albertel 5076:       FirstNameLength - number of columns that the first name spans
                   5077:  
                   5078:       LastName    - column that the last name starts in
                   5079:       LastNameLength - number of columns that the last name spans
                   5080: 
                   5081: =cut
1.422     foxr     5082: 
1.82      albertel 5083: sub get_scantron_config {
                   5084:     my ($which) = @_;
                   5085:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5086:     my %config;
1.157     albertel 5087:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5088:     foreach my $line (<$fh>) {
                   5089: 	my ($name,$descrip)=split(/:/,$line);
                   5090: 	if ($name ne $which ) { next; }
                   5091: 	chomp($line);
                   5092: 	my @config=split(/:/,$line);
                   5093: 	$config{'name'}=$config[0];
                   5094: 	$config{'description'}=$config[1];
                   5095: 	$config{'CODElocation'}=$config[2];
                   5096: 	$config{'CODEstart'}=$config[3];
                   5097: 	$config{'CODElength'}=$config[4];
                   5098: 	$config{'IDstart'}=$config[5];
                   5099: 	$config{'IDlength'}=$config[6];
                   5100: 	$config{'Qstart'}=$config[7];
                   5101: 	$config{'Qlength'}=$config[8];
                   5102: 	$config{'Qoff'}=$config[9];
                   5103: 	$config{'Qon'}=$config[10];
1.157     albertel 5104: 	$config{'PaperID'}=$config[11];
                   5105: 	$config{'PaperIDlength'}=$config[12];
                   5106: 	$config{'FirstName'}=$config[13];
                   5107: 	$config{'FirstNamelength'}=$config[14];
                   5108: 	$config{'LastName'}=$config[15];
                   5109: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5110: 	last;
                   5111:     }
                   5112:     return %config;
                   5113: }
                   5114: 
1.423     albertel 5115: =pod 
                   5116: 
                   5117: =item username_to_idmap
                   5118: 
                   5119:     creates a hash keyed by student id with values of the corresponding
                   5120:     student username:domain.
                   5121: 
                   5122:   Arguments:
                   5123: 
                   5124:     $classlist - reference to the class list hash. This is a hash
                   5125:                  keyed by student name:domain  whose elements are references
1.424     albertel 5126:                  to arrays containing various chunks of information
1.423     albertel 5127:                  about the student. (See loncoursedata for more info).
                   5128: 
                   5129:   Returns
                   5130:     %idmap - the constructed hash
                   5131: 
                   5132: =cut
                   5133: 
1.82      albertel 5134: sub username_to_idmap {
                   5135:     my ($classlist)= @_;
                   5136:     my %idmap;
                   5137:     foreach my $student (keys(%$classlist)) {
                   5138: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5139: 	    $student;
                   5140:     }
                   5141:     return %idmap;
                   5142: }
1.423     albertel 5143: 
                   5144: =pod
                   5145: 
1.424     albertel 5146: =item scantron_fixup_scanline
1.423     albertel 5147: 
                   5148:    Process a requested correction to a scanline.
                   5149: 
                   5150:   Arguments:
                   5151:     $scantron_config   - hash from &get_scantron_config()
                   5152:     $scan_data         - hash of correction information 
                   5153:                           (see &scantron_getfile())
                   5154:     $line              - existing scanline
                   5155:     $whichline         - line number of the passed in scanline
                   5156:     $field             - type of change to process 
                   5157:                          (either 
                   5158:                           'ID'     -> correct the student ID number
                   5159:                           'CODE'   -> correct the CODE
                   5160:                           'answer' -> fixup the submitted answers)
                   5161:     
                   5162:    $args               - hash of additional info,
                   5163:                           - 'ID' 
                   5164:                                'newid' -> studentID to use in replacement
1.424     albertel 5165:                                           of existing one
1.423     albertel 5166:                           - 'CODE' 
                   5167:                                'CODE_ignore_dup' - set to true if duplicates
                   5168:                                                    should be ignored.
                   5169: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5170:                                         if the existing unfound code should
1.423     albertel 5171:                                         be used as is
                   5172:                           - 'answer'
                   5173:                                'response' - new answer or 'none' if blank
                   5174:                                'question' - the bubble line to change
                   5175: 
                   5176:   Returns:
                   5177:     $line - the modified scanline
                   5178: 
                   5179:   Side effects: 
                   5180:     $scan_data - may be updated
                   5181: 
                   5182: =cut
                   5183: 
1.82      albertel 5184: 
1.157     albertel 5185: sub scantron_fixup_scanline {
                   5186:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.479     foxr     5187:     
                   5188:     
1.157     albertel 5189:     if ($field eq 'ID') {
                   5190: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5191: 	    return ($line,1,'New value too large');
1.157     albertel 5192: 	}
                   5193: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5194: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5195: 				     $args->{'newid'});
                   5196: 	}
                   5197: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5198: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5199: 	if ($args->{'newid'}=~/^\s*$/) {
                   5200: 	    &scan_data($scan_data,"$whichline.user",
                   5201: 		       $args->{'username'}.':'.$args->{'domain'});
                   5202: 	}
1.186     albertel 5203:     } elsif ($field eq 'CODE') {
1.192     albertel 5204: 	if ($args->{'CODE_ignore_dup'}) {
                   5205: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5206: 	}
                   5207: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5208: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5209: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5210: 		return ($line,1,'New CODE value too large');
                   5211: 	    }
                   5212: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5213: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5214: 	    }
                   5215: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5216: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5217: 	}
1.157     albertel 5218:     } elsif ($field eq 'answer') {
1.479     foxr     5219: 	&scantron_get_maxbubble(); # Need the bubble counter info.
1.482     foxr     5220: 	my $length =$scantron_config->{'Qlength'};
1.157     albertel 5221: 	my $off=$scantron_config->{'Qoff'};
                   5222: 	my $on=$scantron_config->{'Qon'};
1.479     foxr     5223:         my $question_number = $args->{'question'} -1;
                   5224:         my $first_position  = $first_bubble_line{$question_number};
                   5225: 	my $bubble_count    = $bubble_lines_per_response{$question_number};
                   5226:         my $bubbles_per_line= $$scantron_config{'Qlength'};
1.482     foxr     5227: 	my $answer=${off}x($bubbles_per_line*$bubble_count);
1.479     foxr     5228:         my $final_answer;
                   5229:         if ($$scantron_config{'Qon'} eq 'letter'  ||
                   5230: 	    $$scantron_config{'Qon'} eq 'number') { 
                   5231: 	    $bubbles_per_line = 10;
                   5232: 	}
                   5233: 	if (defined $args->{'response'}) {
                   5234: 	    
                   5235: 	    if ($args->{'response'} eq 'none') {
                   5236: 		&scan_data($scan_data,
                   5237: 			   "$whichline.no_bubble.".$args->{'question'},'1');
1.274     albertel 5238: 	    } else {
1.479     foxr     5239: 		my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
                   5240: 		if ($on eq 'letter') {
                   5241: 		    my @alphabet=('A'..'Z');
                   5242: 		    $answer=$alphabet[$bubble_number];
                   5243: 		} elsif ($on eq 'number') {
1.482     foxr     5244: 		    $answer= $bubble_number+1;
1.479     foxr     5245: 		    if ($answer == 10) { $answer = '0'; }
                   5246: 		} else {
1.482     foxr     5247: 		    substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
                   5248: 		    $final_answer = $answer;
1.479     foxr     5249: 		}
                   5250: 		&scan_data($scan_data,
                   5251: 			   "$whichline.no_bubble.".$args->{'question'},undef,'1');
1.482     foxr     5252: 		
                   5253: 		# Positional notation already has the right final answer length..
                   5254: 
                   5255: 		if (($on eq 'letter') || ($on eq 'number')) {
                   5256: 		    for (my $l = 0; $l < $bubble_count; $l++) {
                   5257: 			if ($l eq $bubble_line) {
                   5258: 			    $final_answer .= $answer;
                   5259: 			} else {
                   5260: 			    $final_answer .= ' ';
                   5261: 			}
1.479     foxr     5262: 		    }
                   5263: 		}
1.274     albertel 5264: 	    }
1.479     foxr     5265: 	    # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5266: 	    #substr($line,$where-1,$length)=$answer;
                   5267: 	    substr($line, 
                   5268: 		   $scantron_config->{'Qstart'}+$first_position-1,
1.482     foxr     5269: 		   $bubbles_per_line*$length) = $final_answer;
1.157     albertel 5270: 	}
                   5271:     }
                   5272:     return $line;
                   5273: }
1.423     albertel 5274: 
                   5275: =pod
                   5276: 
                   5277: =item scan_data
                   5278: 
                   5279:     Edit or look up  an item in the scan_data hash.
                   5280: 
                   5281:   Arguments:
                   5282:     $scan_data  - The hash (see scantron_getfile)
                   5283:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5284:                   scantronfilename_key).
1.423     albertel 5285:     $data        - New value of the hash entry.
                   5286:     $delete      - If true, the entry is removed from the hash.
                   5287: 
                   5288:   Returns:
                   5289:     The new value of the hash table field (undefined if deleted).
                   5290: 
                   5291: =cut
                   5292: 
                   5293: 
1.157     albertel 5294: sub scan_data {
                   5295:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5296:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5297:     if (defined($value)) {
                   5298: 	$scan_data->{$filename.'_'.$key} = $value;
                   5299:     }
                   5300:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5301:     return $scan_data->{$filename.'_'.$key};
                   5302: }
1.423     albertel 5303: 
                   5304: =pod 
                   5305: 
                   5306: =item scantron_parse_scanline
                   5307: 
                   5308:   Decodes a scanline from the selected scantron file
                   5309: 
                   5310:  Arguments:
                   5311:     line             - The text of the scantron file line to process
                   5312:     whichline        - Line number
                   5313:     scantron_config  - Hash describing the format of the scantron lines.
                   5314:     scan_data        - Hash of extra information about the scanline
                   5315:                        (see scantron_getfile for more information)
                   5316:     just_header      - True if should not process question answers but only
                   5317:                        the stuff to the left of the answers.
                   5318:  Returns:
                   5319:    Hash containing the result of parsing the scanline
                   5320: 
                   5321:    Keys are all proceeded by the string 'scantron.'
                   5322: 
                   5323:        CODE    - the CODE in use for this scanline
                   5324:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5325:                  by the operator
                   5326:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5327:                             CODEs were selected, but the usage has been
                   5328:                             forced by the operator
                   5329:        ID  - student ID
                   5330:        PaperID - if used, the ID number printed on the sheet when the 
                   5331:                  paper was scanned
                   5332:        FirstName - first name from the sheet
                   5333:        LastName  - last name from the sheet
                   5334: 
                   5335:      if just_header was not true these key may also exist
                   5336: 
1.447     foxr     5337:        missingerror - a list of bubble ranges that are considered to be answers
                   5338:                       to a single question that don't have any bubbles filled in.
                   5339:                       Of the form questionnumber:firstbubblenumber:count.
                   5340:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5341:                       to a single question that have more than one bubble filled in.
                   5342:                       Of the form questionnumber::firstbubblenumber:count
                   5343:    
                   5344:                 In the above, count is the number of bubble responses in the
                   5345:                 input line needed to represent the possible answers to the question.
                   5346:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5347:                 per line would have count = 2.
                   5348: 
1.423     albertel 5349:        maxquest     - the number of the last bubble line that was parsed
                   5350: 
                   5351:        (<number> starts at 1)
                   5352:        <number>.answer - zero or more letters representing the selected
                   5353:                          letters from the scanline for the bubble line 
                   5354:                          <number>.
                   5355:                          if blank there was either no bubble or there where
                   5356:                          multiple bubbles, (consult the keys missingerror and
                   5357:                          doubleerror if this is an error condition)
                   5358: 
                   5359: =cut
                   5360: 
1.82      albertel 5361: sub scantron_parse_scanline {
1.423     albertel 5362:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5363: 
1.82      albertel 5364:     my %record;
1.422     foxr     5365:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5366:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5367:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5368: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5369: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5370: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5371: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5372: 	    $record{'scantron.CODE'}=substr($data,
                   5373: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5374: 					    $$scantron_config{'CODElength'});
1.191     albertel 5375: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5376: 		$record{'scantron.useCODE'}=1;
                   5377: 	    }
1.192     albertel 5378: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5379: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5380: 	    }
1.82      albertel 5381: 	} else {
                   5382: 	    #FIXME interpret first N questions
                   5383: 	}
                   5384:     }
1.83      albertel 5385:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5386: 				  $$scantron_config{'IDlength'});
1.157     albertel 5387:     $record{'scantron.PaperID'}=
                   5388: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5389: 	       $$scantron_config{'PaperIDlength'});
                   5390:     $record{'scantron.FirstName'}=
                   5391: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5392: 	       $$scantron_config{'FirstNamelength'});
                   5393:     $record{'scantron.LastName'}=
                   5394: 	substr($data,$$scantron_config{'LastName'}-1,
                   5395: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5396:     if ($just_header) { return \%record; }
1.194     albertel 5397: 
1.82      albertel 5398:     my @alphabet=('A'..'Z');
                   5399:     my $questnum=0;
1.447     foxr     5400:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5401: 
1.470     foxr     5402:     chomp($questions);		# Get rid of any trailing \n.
                   5403:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5404:     while (length($questions)) {
1.447     foxr     5405: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5406: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5407: 
                   5408: 
1.82      albertel 5409: 	$questnum++;
1.447     foxr     5410: 	my $currentquest = substr($questions,0,$answer_length);
1.490     foxr     5411: 	$questions       = substr($questions,$answer_length);
1.447     foxr     5412: 	if (length($currentquest) < $answer_length) { next; }
                   5413: 
                   5414: 	# Qon letter implies for each slot in currentquest we have:
                   5415: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5416:         #    about anything else (esp. a value of Qoff for missing
                   5417: 	#    bubbles.
                   5418: 
                   5419: 
1.239     albertel 5420: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5421: 	    if ($currentquest =~ /\?/
                   5422: 		|| $currentquest =~ /\*/
                   5423: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5424: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5425: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5426: 		    my $bubble = substr($currentquest, $ans, 1);
                   5427: 		    if ($bubble =~ /[A-Z]/ ) {
                   5428: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5429: 		    } else {
                   5430: 			$record{"scantron.$ansnum.answer"}='';
                   5431: 		    }
1.447     foxr     5432: 		    $ansnum++;
                   5433: 		}
                   5434: 
1.389     albertel 5435: 	    } elsif (!defined($currentquest)
1.447     foxr     5436: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5437: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5438: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5439: 		    $record{"scantron.$ansnum.answer"}='';
                   5440: 		    $ansnum++;
                   5441: 
                   5442: 		}
1.239     albertel 5443: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5444: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5445: 		   #  $ansnum += $answers_needed;
1.239     albertel 5446: 		}
                   5447: 	    } else {
1.447     foxr     5448: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.490     foxr     5449: 		    my $bubble = substr($currentquest, $ans, 1);
                   5450: 		    $record{"scantron.$ansnum.answer"} = $bubble;
1.447     foxr     5451: 		    $ansnum++;
                   5452: 		}
1.239     albertel 5453: 	    }
1.447     foxr     5454: 
                   5455: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5456: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5457:         #    and *? for double bubbles on a line.
                   5458: 	#    these answers are also stored as letters.
                   5459: 
1.239     albertel 5460: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5461: 	    if ($currentquest =~ /\?/
                   5462: 		|| $currentquest =~ /\*/
                   5463: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5464: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5465: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5466: 		    my $bubble = substr($currentquest, $ans, 1);
                   5467: 		    if ($bubble =~ /\d/) {
                   5468: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5469: 		    } else {
1.461     foxr     5470: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5471: 		    }
1.447     foxr     5472: 		    $ansnum++;
                   5473: 		}
                   5474: 
1.389     albertel 5475: 	    } elsif (!defined($currentquest)
1.447     foxr     5476: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5477: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5478: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5479: 		    $record{"scantron.$ansnum.answer"}='';
                   5480: 		    $ansnum++;
                   5481: 
                   5482: 		}
1.239     albertel 5483: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5484: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5485: 		    $ansnum += $answers_needed;
1.239     albertel 5486: 		}
1.447     foxr     5487: 
1.239     albertel 5488: 	    } else {
1.447     foxr     5489: 		$currentquest = &digits_to_letters($currentquest);
                   5490: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5491: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5492: 		    $ansnum++;
1.371     albertel 5493: 		}
1.239     albertel 5494: 	    }
1.82      albertel 5495: 	} else {
1.447     foxr     5496: 
                   5497: 	    # Otherwise there's a positional notation;
                   5498: 	    # each bubble line requires Qlength items, and there are filled in
                   5499: 	    # bubbles for each case where there 'Qon' characters.
                   5500: 	    #
                   5501: 
1.239     albertel 5502: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5503: 
                   5504: 	    # If the split only  giveas us one element.. the full length of the
                   5505: 	    # answser string, no bubbles are filled in:
                   5506: 
                   5507: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5508: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5509: 		    $record{"scantron.$ansnum.answer"}='';
                   5510: 		    $ansnum++;
                   5511: 
                   5512: 		}
1.239     albertel 5513: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5514: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5515: 		}
1.482     foxr     5516: 		
                   5517: 
1.490     foxr     5518: 
                   5519: 	    } elsif (scalar(@array) eq 2) {
1.447     foxr     5520: 
1.459     foxr     5521: 		my $location      = length($array[0]);
1.483     foxr     5522: 		my $line_num      = int($location / $$scantron_config{'Qlength'});
1.447     foxr     5523: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
1.483     foxr     5524: 		
1.447     foxr     5525: 
                   5526: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5527: 		    if ($ans eq $line_num) {
                   5528: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5529: 		    } else {
                   5530: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5531: 		    }
                   5532: 		    $ansnum++;
                   5533: 		}
1.239     albertel 5534: 	    }
1.447     foxr     5535: 	    #  If there's more than one instance of a bubble character
                   5536: 	    #  That's a double bubble; with positional notation we can
                   5537: 	    #  record all the bubbles filled in as well as the 
                   5538: 	    #  fact this response consists of multiple bubbles.
                   5539: 	    #
                   5540: 	    else {
1.239     albertel 5541: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5542: 
                   5543: 		my $first_answer = $ansnum;
                   5544: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5545: 		    my $item = $first_answer+$ans;
                   5546: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5547: 		}
                   5548: 
1.239     albertel 5549: 		my @ans=@array;
1.462     foxr     5550: 		my $i=0;
                   5551: 		my $increment = 0;
1.239     albertel 5552: 		while ($#ans) {
1.462     foxr     5553: 		    $i+=length($ans[0]) + $increment;
                   5554: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5555: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5556: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5557: 		    shift(@ans);
1.462     foxr     5558: 		    $increment = 1;
1.239     albertel 5559: 		}
1.462     foxr     5560: 		$ansnum += $answers_needed;
1.239     albertel 5561: 	    }
1.82      albertel 5562: 	}
                   5563:     }
1.83      albertel 5564:     $record{'scantron.maxquest'}=$questnum;
                   5565:     return \%record;
1.82      albertel 5566: }
                   5567: 
1.423     albertel 5568: =pod
                   5569: 
                   5570: =item scantron_add_delay
                   5571: 
                   5572:    Adds an error message that occurred during the grading phase to a
                   5573:    queue of messages to be shown after grading pass is complete
                   5574: 
                   5575:  Arguments:
1.424     albertel 5576:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5577:    $scanline    - the scanline that caused the error
                   5578:    $errormesage - the error message
                   5579:    $errorcode   - a numeric code for the error
                   5580: 
                   5581:  Side Effects:
1.424     albertel 5582:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5583: 
                   5584: =cut
                   5585: 
1.82      albertel 5586: sub scantron_add_delay {
1.140     albertel 5587:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5588:     push(@$delayqueue,
                   5589: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5590: 	  'ecode' => $errorcode }
                   5591: 	 );
1.82      albertel 5592: }
                   5593: 
1.423     albertel 5594: =pod
                   5595: 
                   5596: =item scantron_find_student
                   5597: 
1.424     albertel 5598:    Finds the username for the current scanline
                   5599: 
                   5600:   Arguments:
                   5601:    $scantron_record - hash result from scantron_parse_scanline
                   5602:    $scan_data       - hash of correction information 
                   5603:                       (see &scantron_getfile() form more information)
                   5604:    $idmap           - hash from &username_to_idmap()
                   5605:    $line            - number of current scanline
                   5606:  
                   5607:   Returns:
                   5608:    Either 'username:domain' or undef if unknown
                   5609: 
1.423     albertel 5610: =cut
                   5611: 
1.82      albertel 5612: sub scantron_find_student {
1.157     albertel 5613:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5614:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5615:     if ($scanID =~ /^\s*$/) {
                   5616:  	return &scan_data($scan_data,"$line.user");
                   5617:     }
1.83      albertel 5618:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5619:  	if (lc($id) eq lc($scanID)) {
                   5620:  	    return $$idmap{$id};
                   5621:  	}
1.83      albertel 5622:     }
                   5623:     return undef;
                   5624: }
                   5625: 
1.423     albertel 5626: =pod
                   5627: 
                   5628: =item scantron_filter
                   5629: 
1.424     albertel 5630:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5631:    hidden resources was selected
                   5632: 
1.423     albertel 5633: =cut
                   5634: 
1.83      albertel 5635: sub scantron_filter {
                   5636:     my ($curres)=@_;
1.331     albertel 5637: 
                   5638:     if (ref($curres) && $curres->is_problem()) {
                   5639: 	# if the user has asked to not have either hidden
                   5640: 	# or 'randomout' controlled resources to be graded
                   5641: 	# don't include them
                   5642: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5643: 	    && $curres->randomout) {
                   5644: 	    return 0;
                   5645: 	}
1.83      albertel 5646: 	return 1;
                   5647:     }
                   5648:     return 0;
1.82      albertel 5649: }
                   5650: 
1.423     albertel 5651: =pod
                   5652: 
                   5653: =item scantron_process_corrections
                   5654: 
1.424     albertel 5655:    Gets correction information out of submitted form data and corrects
                   5656:    the scanline
                   5657: 
1.423     albertel 5658: =cut
                   5659: 
1.157     albertel 5660: sub scantron_process_corrections {
                   5661:     my ($r) = @_;
1.257     albertel 5662:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5663:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5664:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5665:     my $which=$env{'form.scantron_line'};
1.200     albertel 5666:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5667:     my ($skip,$err,$errmsg);
1.257     albertel 5668:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5669: 	$skip=1;
1.257     albertel 5670:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5671: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5672: 	    $env{'form.scantron_domain'};
1.157     albertel 5673: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5674: 	($line,$err,$errmsg)=
                   5675: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5676: 				     'ID',{'newid'=>$newid,
1.257     albertel 5677: 				    'username'=>$env{'form.scantron_username'},
                   5678: 				    'domain'=>$env{'form.scantron_domain'}});
                   5679:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5680: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5681: 	my $newCODE;
1.192     albertel 5682: 	my %args;
1.190     albertel 5683: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5684: 	    $newCODE='use_unfound';
1.190     albertel 5685: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5686: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5687: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5688: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5689: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5690: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5691: 	}
1.257     albertel 5692: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5693: 	    $args{'CODE_ignore_dup'}=1;
                   5694: 	}
                   5695: 	$args{'CODE'}=$newCODE;
1.186     albertel 5696: 	($line,$err,$errmsg)=
                   5697: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5698: 				     'CODE',\%args);
1.257     albertel 5699:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5700: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5701: 	    ($line,$err,$errmsg)=
                   5702: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5703: 					 $which,'answer',
                   5704: 					 { 'question'=>$question,
1.257     albertel 5705: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5706: 	    if ($err) { last; }
                   5707: 	}
                   5708:     }
                   5709:     if ($err) {
1.398     albertel 5710: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5711:     } else {
1.200     albertel 5712: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5713: 	&scantron_putfile($scanlines,$scan_data);
                   5714:     }
                   5715: }
                   5716: 
1.423     albertel 5717: =pod
                   5718: 
                   5719: =item reset_skipping_status
                   5720: 
1.424     albertel 5721:    Forgets the current set of remember skipped scanlines (and thus
                   5722:    reverts back to considering all lines in the
                   5723:    scantron_skipped_<filename> file)
                   5724: 
1.423     albertel 5725: =cut
                   5726: 
1.200     albertel 5727: sub reset_skipping_status {
                   5728:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5729:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5730:     &scantron_putfile(undef,$scan_data);
                   5731: }
                   5732: 
1.423     albertel 5733: =pod
                   5734: 
                   5735: =item start_skipping
                   5736: 
1.424     albertel 5737:    Marks a scanline to be skipped. 
                   5738: 
1.423     albertel 5739: =cut
                   5740: 
1.376     albertel 5741: sub start_skipping {
1.200     albertel 5742:     my ($scan_data,$i)=@_;
                   5743:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5744:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5745: 	$remembered{$i}=2;
                   5746:     } else {
                   5747: 	$remembered{$i}=1;
                   5748:     }
1.200     albertel 5749:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5750: }
                   5751: 
1.423     albertel 5752: =pod
                   5753: 
                   5754: =item should_be_skipped
                   5755: 
1.424     albertel 5756:    Checks whether a scanline should be skipped.
                   5757: 
1.423     albertel 5758: =cut
                   5759: 
1.200     albertel 5760: sub should_be_skipped {
1.376     albertel 5761:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5762:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5763: 	# not redoing old skips
1.376     albertel 5764: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5765: 	return 0;
                   5766:     }
                   5767:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5768: 
                   5769:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5770: 	return 0;
                   5771:     }
1.200     albertel 5772:     return 1;
                   5773: }
                   5774: 
1.423     albertel 5775: =pod
                   5776: 
                   5777: =item remember_current_skipped
                   5778: 
1.424     albertel 5779:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5780:    file and remembers them into scan_data for later use.
                   5781: 
1.423     albertel 5782: =cut
                   5783: 
1.200     albertel 5784: sub remember_current_skipped {
                   5785:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5786:     my %to_remember;
                   5787:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5788: 	if ($scanlines->{'skipped'}[$i]) {
                   5789: 	    $to_remember{$i}=1;
                   5790: 	}
                   5791:     }
1.376     albertel 5792: 
1.200     albertel 5793:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5794:     &scantron_putfile(undef,$scan_data);
                   5795: }
                   5796: 
1.423     albertel 5797: =pod
                   5798: 
                   5799: =item check_for_error
                   5800: 
1.424     albertel 5801:     Checks if there was an error when attempting to remove a specific
                   5802:     scantron_.. bubble sheet data file. Prints out an error if
                   5803:     something went wrong.
                   5804: 
1.423     albertel 5805: =cut
                   5806: 
1.200     albertel 5807: sub check_for_error {
                   5808:     my ($r,$result)=@_;
                   5809:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.492     albertel 5810: 	$r->print(&mt("An error occurred ([_1]) when trying to remove the existing corrections.",$result));
1.200     albertel 5811:     }
                   5812: }
1.157     albertel 5813: 
1.423     albertel 5814: =pod
                   5815: 
                   5816: =item scantron_warning_screen
                   5817: 
1.424     albertel 5818:    Interstitial screen to make sure the operator has selected the
                   5819:    correct options before we start the validation phase.
                   5820: 
1.423     albertel 5821: =cut
                   5822: 
1.203     albertel 5823: sub scantron_warning_screen {
                   5824:     my ($button_text)=@_;
1.257     albertel 5825:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5826:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5827:     my $CODElist;
1.284     albertel 5828:     if ($scantron_config{'CODElocation'} &&
                   5829: 	$scantron_config{'CODEstart'} &&
                   5830: 	$scantron_config{'CODElength'}) {
                   5831: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5832: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5833: 	$CODElist=
1.492     albertel 5834: 	    '<tr><td><b>'.&mt('List of CODES to validate against:').'</b></td><td><tt>'.
1.373     albertel 5835: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5836:     }
1.492     albertel 5837:     return ('
1.203     albertel 5838: <p>
1.492     albertel 5839: <span class="LC_warning">
                   5840: '.&mt('Please double check the information below before clicking on \'[_1]\'',&mt($button_text)).'</span>
1.203     albertel 5841: </p>
                   5842: <table>
1.492     albertel 5843: <tr><td><b>'.&mt('Sequence to be Graded:').'</b></td><td>'.$title.'</td></tr>
                   5844: <tr><td><b>'.&mt('Data File that will be used:').'</b></td><td><tt>'.$env{'form.scantron_selectfile'}.'</tt></td></tr>
                   5845: '.$CODElist.'
1.203     albertel 5846: </table>
                   5847: <br />
1.492     albertel 5848: <p> '.&mt('If this information is correct, please click on \'[_1]\'.',&mt($button_text)).'</p>
                   5849: <p> '.&mt('If something is incorrect, please click the \'Grading Menu\' button to start over.').'</p>
1.203     albertel 5850: 
                   5851: <br />
1.492     albertel 5852: ');
1.203     albertel 5853: }
                   5854: 
1.423     albertel 5855: =pod
                   5856: 
                   5857: =item scantron_do_warning
                   5858: 
1.424     albertel 5859:    Check if the operator has picked something for all required
                   5860:    fields. Error out if something is missing.
                   5861: 
1.423     albertel 5862: =cut
                   5863: 
1.203     albertel 5864: sub scantron_do_warning {
                   5865:     my ($r)=@_;
1.324     albertel 5866:     my ($symb)=&get_symb($r);
1.203     albertel 5867:     if (!$symb) {return '';}
1.324     albertel 5868:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5869:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5870:     if ( $env{'form.selectpage'} eq '' ||
                   5871: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5872: 	 $env{'form.scantron_format'} eq '' ) {
1.492     albertel 5873: 	$r->print("<p>".&mt('You have forgetten to specify some information. Please go Back and try again.')."</p>");
1.257     albertel 5874: 	if ( $env{'form.selectpage'} eq '') {
1.492     albertel 5875: 	    $r->print('<p><span class="LC_error">'.&mt('You have not selected a Sequence to grade').'</span></p>');
1.237     albertel 5876: 	} 
1.257     albertel 5877: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.492     albertel 5878: 	    $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 5879: 	} 
1.257     albertel 5880: 	if ( $env{'form.scantron_format'} eq '') {
1.492     albertel 5881: 	    $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 5882: 	} 
                   5883:     } else {
1.265     www      5884: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.492     albertel 5885: 	$r->print('
                   5886: '.$warning.'
                   5887: <input type="submit" name="submit" value="'.&mt('Grading: Validate Records').'" />
1.203     albertel 5888: <input type="hidden" name="command" value="scantron_validate" />
1.492     albertel 5889: ');
1.237     albertel 5890:     }
1.352     albertel 5891:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5892:     return '';
                   5893: }
                   5894: 
1.423     albertel 5895: =pod
                   5896: 
                   5897: =item scantron_form_start
                   5898: 
1.424     albertel 5899:     html hidden input for remembering all selected grading options
                   5900: 
1.423     albertel 5901: =cut
                   5902: 
1.203     albertel 5903: sub scantron_form_start {
                   5904:     my ($max_bubble)=@_;
                   5905:     my $result= <<SCANTRONFORM;
                   5906: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5907:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5908:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5909:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5910:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5911:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5912:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5913:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5914:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5915:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5916: SCANTRONFORM
1.447     foxr     5917: 
                   5918:   my $line = 0;
                   5919:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5920:        my $chunk =
                   5921: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5922:        $chunk .=
                   5923: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5924:        $result .= $chunk;
                   5925:        $line++;
                   5926:    }
1.203     albertel 5927:     return $result;
                   5928: }
                   5929: 
1.423     albertel 5930: =pod
                   5931: 
                   5932: =item scantron_validate_file
                   5933: 
1.424     albertel 5934:     Dispatch routine for doing validation of a bubble sheet data file.
                   5935: 
                   5936:     Also processes any necessary information resets that need to
                   5937:     occur before validation begins (ignore previous corrections,
                   5938:     restarting the skipped records processing)
                   5939: 
1.423     albertel 5940: =cut
                   5941: 
1.157     albertel 5942: sub scantron_validate_file {
                   5943:     my ($r) = @_;
1.324     albertel 5944:     my ($symb)=&get_symb($r);
1.157     albertel 5945:     if (!$symb) {return '';}
1.324     albertel 5946:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5947:     
                   5948:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5949:     # them when doing the corrections reset
1.257     albertel 5950:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5951: 	&reset_skipping_status();
                   5952:     }
1.257     albertel 5953:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5954: 	&remember_current_skipped();
1.257     albertel 5955: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5956:     }
                   5957: 
1.257     albertel 5958:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5959: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5960: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5961: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5962: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5963:     }
1.200     albertel 5964: 
1.257     albertel 5965:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5966: 	&scantron_process_corrections($r);
                   5967:     }
1.492     albertel 5968:     $r->print('<p>'.&mt('Gathering necessary info.').'</p>');$r->rflush();
1.157     albertel 5969:     #get the student pick code ready
                   5970:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5971:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5972:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5973:     $r->print($result);
                   5974:     
1.334     albertel 5975:     my @validate_phases=( 'sequence',
                   5976: 			  'ID',
1.157     albertel 5977: 			  'CODE',
                   5978: 			  'doublebubble',
                   5979: 			  'missingbubbles');
1.257     albertel 5980:     if (!$env{'form.validatepass'}) {
                   5981: 	$env{'form.validatepass'} = 0;
1.157     albertel 5982:     }
1.257     albertel 5983:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5984: 
1.448     foxr     5985: 
1.157     albertel 5986:     my $stop=0;
                   5987:     while (!$stop && $currentphase < scalar(@validate_phases)) {
1.492     albertel 5988: 	$r->print('<p> '.&mt('Validating '.$validate_phases[$currentphase]).'</p>');
1.157     albertel 5989: 	$r->rflush();
                   5990: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5991: 	{
                   5992: 	    no strict 'refs';
                   5993: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5994: 	}
                   5995:     }
                   5996:     if (!$stop) {
1.203     albertel 5997: 	my $warning=&scantron_warning_screen('Start Grading');
1.492     albertel 5998: 	$r->print('
                   5999: '.&mt('Validation process complete.').'<br />
                   6000: '.$warning.'
                   6001: <input type="submit" name="submit" value="'.&mt('Start Grading').'" />
1.203     albertel 6002: <input type="hidden" name="command" value="scantron_process" />
1.492     albertel 6003: ');
1.203     albertel 6004: 
1.157     albertel 6005:     } else {
                   6006: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6007: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6008:     }
                   6009:     if ($stop) {
1.334     albertel 6010: 	if ($validate_phases[$currentphase] eq 'sequence') {
1.492     albertel 6011: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Ignore -&gt;').' " />');
                   6012: 	    $r->print(' '.&mt('this error').' <br />');
1.334     albertel 6013: 
1.492     albertel 6014: 	    $r->print(" <p>".&mt("Or click the 'Grading Menu' button to start over.")."</p>");
1.334     albertel 6015: 	} else {
1.492     albertel 6016: 	    $r->print('<input type="submit" name="submit" value="'.&mt('Continue -&gt;').'" />');
                   6017: 	    $r->print(' '.&mt('using corrected info').' <br />');
                   6018: 	    $r->print("<input type='submit' value='".&mt("Skip")."' name='scantron_skip_record' />");
                   6019: 	    $r->print(" ".&mt("this scanline saving it for later."));
1.334     albertel 6020: 	}
1.157     albertel 6021:     }
1.352     albertel 6022:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6023:     return '';
                   6024: }
                   6025: 
1.423     albertel 6026: 
                   6027: =pod
                   6028: 
                   6029: =item scantron_remove_file
                   6030: 
1.424     albertel 6031:    Removes the requested bubble sheet data file, makes sure that
                   6032:    scantron_original_<filename> is never removed
                   6033: 
                   6034: 
1.423     albertel 6035: =cut
                   6036: 
1.200     albertel 6037: sub scantron_remove_file {
1.192     albertel 6038:     my ($which)=@_;
1.257     albertel 6039:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6040:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6041:     my $file='scantron_';
1.200     albertel 6042:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6043: 	$file.=$which.'_';
1.192     albertel 6044:     } else {
                   6045: 	return 'refused';
                   6046:     }
1.257     albertel 6047:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6048:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6049: }
                   6050: 
1.423     albertel 6051: 
                   6052: =pod
                   6053: 
                   6054: =item scantron_remove_scan_data
                   6055: 
1.424     albertel 6056:    Removes all scan_data correction for the requested bubble sheet
                   6057:    data file.  (In the case that both the are doing skipped records we need
                   6058:    to remember the old skipped lines for the time being so that element
                   6059:    persists for a while.)
                   6060: 
1.423     albertel 6061: =cut
                   6062: 
1.200     albertel 6063: sub scantron_remove_scan_data {
1.257     albertel 6064:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6065:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6066:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6067:     my @todelete;
1.257     albertel 6068:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6069:     foreach my $key (@keys) {
                   6070: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6071: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6072: 		$key=~/remember_skipping/) {
                   6073: 		next;
                   6074: 	    }
1.192     albertel 6075: 	    push(@todelete,$key);
                   6076: 	}
                   6077:     }
1.200     albertel 6078:     my $result;
1.192     albertel 6079:     if (@todelete) {
1.491     albertel 6080: 	$result = &Apache::lonnet::del('nohist_scantrondata',
                   6081: 				       \@todelete,$cdom,$cname);
                   6082:     } else {
                   6083: 	$result = 'ok';
1.192     albertel 6084:     }
                   6085:     return $result;
                   6086: }
                   6087: 
1.423     albertel 6088: 
                   6089: =pod
                   6090: 
                   6091: =item scantron_getfile
                   6092: 
1.424     albertel 6093:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6094:     the scan_data hash
                   6095:   
                   6096:   Arguments:
                   6097:     None
                   6098: 
                   6099:   Returns:
                   6100:     2 hash references
                   6101: 
                   6102:      - first one has 
                   6103:          orig      -
                   6104:          corrected -
                   6105:          skipped   -  each of which points to an array ref of the specified
                   6106:                       file broken up into individual lines
                   6107:          count     - number of scanlines
                   6108:  
                   6109:      - second is the scan_data hash possible keys are
1.425     albertel 6110:        ($number refers to scanline numbered $number and thus the key affects
                   6111:         only that scanline
                   6112:         $bubline refers to the specific bubble line element and the aspects
                   6113:         refers to that specific bubble line element)
                   6114: 
                   6115:        $number.user - username:domain to use
                   6116:        $number.CODE_ignore_dup 
                   6117:                     - ignore the duplicate CODE error 
                   6118:        $number.useCODE
                   6119:                     - use the CODE in the scanline as is
                   6120:        $number.no_bubble.$bubline
                   6121:                     - it is valid that there is no bubbled in bubble
                   6122:                       at $number $bubline
                   6123:        remember_skipping
                   6124:                     - a frozen hash containing keys of $number and values
                   6125:                       of either 
                   6126:                         1 - we are on a 'do skipped records pass' and plan
                   6127:                             on processing this line
                   6128:                         2 - we are on a 'do skipped records pass' and this
                   6129:                             scanline has been marked to skip yet again
1.424     albertel 6130: 
1.423     albertel 6131: =cut
                   6132: 
1.157     albertel 6133: sub scantron_getfile {
1.200     albertel 6134:     #FIXME really would prefer a scantron directory
1.257     albertel 6135:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6136:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6137:     my $lines;
                   6138:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6139: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6140:     my %scanlines;
                   6141:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6142:     my $temp=$scanlines{'orig'};
                   6143:     $scanlines{'count'}=$#$temp;
                   6144: 
                   6145:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6146: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6147:     if ($lines eq '-1') {
                   6148: 	$scanlines{'corrected'}=[];
                   6149:     } else {
                   6150: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6151:     }
                   6152:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6153: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6154:     if ($lines eq '-1') {
                   6155: 	$scanlines{'skipped'}=[];
                   6156:     } else {
                   6157: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6158:     }
1.175     albertel 6159:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6160:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6161:     my %scan_data = @tmp;
                   6162:     return (\%scanlines,\%scan_data);
                   6163: }
                   6164: 
1.423     albertel 6165: =pod
                   6166: 
                   6167: =item lonnet_putfile
                   6168: 
1.424     albertel 6169:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6170: 
                   6171:  Arguments:
                   6172:    $contents - data to store
                   6173:    $filename - filename to store $contents into
                   6174: 
                   6175:  Returns:
                   6176:    result value from &Apache::lonnet::finishuserfileupload
                   6177: 
1.423     albertel 6178: =cut
                   6179: 
1.157     albertel 6180: sub lonnet_putfile {
                   6181:     my ($contents,$filename)=@_;
1.257     albertel 6182:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6183:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6184:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6185:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6186: 
                   6187: }
                   6188: 
1.423     albertel 6189: =pod
                   6190: 
                   6191: =item scantron_putfile
                   6192: 
1.424     albertel 6193:     Stores the current version of the bubble sheet data files, and the
                   6194:     scan_data hash. (Does not modify the original version only the
                   6195:     corrected and skipped versions.
                   6196: 
                   6197:  Arguments:
                   6198:     $scanlines - hash ref that looks like the first return value from
                   6199:                  &scantron_getfile()
                   6200:     $scan_data - hash ref that looks like the second return value from
                   6201:                  &scantron_getfile()
                   6202: 
1.423     albertel 6203: =cut
                   6204: 
1.157     albertel 6205: sub scantron_putfile {
                   6206:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6207:     #FIXME really would prefer a scantron directory
1.257     albertel 6208:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6209:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6210:     if ($scanlines) {
                   6211: 	my $prefix='scantron_';
1.157     albertel 6212: # no need to update orig, shouldn't change
                   6213: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6214: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6215: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6216: 			$prefix.'corrected_'.
1.257     albertel 6217: 			$env{'form.scantron_selectfile'});
1.200     albertel 6218: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6219: 			$prefix.'skipped_'.
1.257     albertel 6220: 			$env{'form.scantron_selectfile'});
1.200     albertel 6221:     }
1.175     albertel 6222:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6223: }
                   6224: 
1.423     albertel 6225: =pod
                   6226: 
                   6227: =item scantron_get_line
                   6228: 
1.424     albertel 6229:    Returns the correct version of the scanline
                   6230: 
                   6231:  Arguments:
                   6232:     $scanlines - hash ref that looks like the first return value from
                   6233:                  &scantron_getfile()
                   6234:     $scan_data - hash ref that looks like the second return value from
                   6235:                  &scantron_getfile()
                   6236:     $i         - number of the requested line (starts at 0)
                   6237: 
                   6238:  Returns:
                   6239:    A scanline, (either the original or the corrected one if it
                   6240:    exists), or undef if the requested scanline should be
                   6241:    skipped. (Either because it's an skipped scanline, or it's an
                   6242:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6243:    pass.
                   6244: 
1.423     albertel 6245: =cut
                   6246: 
1.157     albertel 6247: sub scantron_get_line {
1.200     albertel 6248:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6249:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6250:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6251:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6252:     return $scanlines->{'orig'}[$i]; 
                   6253: }
                   6254: 
1.423     albertel 6255: =pod
                   6256: 
                   6257: =item scantron_todo_count
                   6258: 
1.424     albertel 6259:     Counts the number of scanlines that need processing.
                   6260: 
                   6261:  Arguments:
                   6262:     $scanlines - hash ref that looks like the first return value from
                   6263:                  &scantron_getfile()
                   6264:     $scan_data - hash ref that looks like the second return value from
                   6265:                  &scantron_getfile()
                   6266: 
                   6267:  Returns:
                   6268:     $count - number of scanlines to process
                   6269: 
1.423     albertel 6270: =cut
                   6271: 
1.200     albertel 6272: sub get_todo_count {
                   6273:     my ($scanlines,$scan_data)=@_;
                   6274:     my $count=0;
                   6275:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6276: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6277: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6278: 	$count++;
                   6279:     }
                   6280:     return $count;
                   6281: }
                   6282: 
1.423     albertel 6283: =pod
                   6284: 
                   6285: =item scantron_put_line
                   6286: 
1.424     albertel 6287:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6288:     data file.
                   6289: 
                   6290:  Arguments:
                   6291:     $scanlines - hash ref that looks like the first return value from
                   6292:                  &scantron_getfile()
                   6293:     $scan_data - hash ref that looks like the second return value from
                   6294:                  &scantron_getfile()
                   6295:     $i         - line number to update
                   6296:     $newline   - contents of the updated scanline
                   6297:     $skip      - if true make the line for skipping and update the
                   6298:                  'skipped' file
                   6299: 
1.423     albertel 6300: =cut
                   6301: 
1.157     albertel 6302: sub scantron_put_line {
1.200     albertel 6303:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6304:     if ($skip) {
                   6305: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6306: 	&start_skipping($scan_data,$i);
1.157     albertel 6307: 	return;
                   6308:     }
                   6309:     $scanlines->{'corrected'}[$i]=$newline;
                   6310: }
                   6311: 
1.423     albertel 6312: =pod
                   6313: 
                   6314: =item scantron_clear_skip
                   6315: 
1.424     albertel 6316:    Remove a line from the 'skipped' file
                   6317: 
                   6318:  Arguments:
                   6319:     $scanlines - hash ref that looks like the first return value from
                   6320:                  &scantron_getfile()
                   6321:     $scan_data - hash ref that looks like the second return value from
                   6322:                  &scantron_getfile()
                   6323:     $i         - line number to update
                   6324: 
1.423     albertel 6325: =cut
                   6326: 
1.376     albertel 6327: sub scantron_clear_skip {
                   6328:     my ($scanlines,$scan_data,$i)=@_;
                   6329:     if (exists($scanlines->{'skipped'}[$i])) {
                   6330: 	undef($scanlines->{'skipped'}[$i]);
                   6331: 	return 1;
                   6332:     }
                   6333:     return 0;
                   6334: }
                   6335: 
1.423     albertel 6336: =pod
                   6337: 
                   6338: =item scantron_filter_not_exam
                   6339: 
1.424     albertel 6340:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6341:    filter out resources that are not marked as 'exam' mode
                   6342: 
1.423     albertel 6343: =cut
                   6344: 
1.334     albertel 6345: sub scantron_filter_not_exam {
                   6346:     my ($curres)=@_;
                   6347:     
                   6348:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6349: 	# if the user has asked to not have either hidden
                   6350: 	# or 'randomout' controlled resources to be graded
                   6351: 	# don't include them
                   6352: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6353: 	    && $curres->randomout) {
                   6354: 	    return 0;
                   6355: 	}
                   6356: 	return 1;
                   6357:     }
                   6358:     return 0;
                   6359: }
                   6360: 
1.423     albertel 6361: =pod
                   6362: 
                   6363: =item scantron_validate_sequence
                   6364: 
1.424     albertel 6365:     Validates the selected sequence, checking for resource that are
                   6366:     not set to exam mode.
                   6367: 
1.423     albertel 6368: =cut
                   6369: 
1.334     albertel 6370: sub scantron_validate_sequence {
                   6371:     my ($r,$currentphase) = @_;
                   6372: 
                   6373:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6374:     my (undef,undef,$sequence)=
                   6375: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6376: 
                   6377:     my $map=$navmap->getResourceByUrl($sequence);
                   6378: 
                   6379:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6380:                                     value="ignore" />');
                   6381:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6382: 	my @resources=
                   6383: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6384: 	if (@resources) {
1.357     banghart 6385: 	    $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 6386: 	    return (1,$currentphase);
                   6387: 	}
                   6388:     }
                   6389: 
                   6390:     return (0,$currentphase+1);
                   6391: }
                   6392: 
1.423     albertel 6393: =pod
                   6394: 
                   6395: =item scantron_validate_ID
                   6396: 
1.424     albertel 6397:    Validates all scanlines in the selected file to not have any
                   6398:    invalid or underspecified student IDs
                   6399: 
1.423     albertel 6400: =cut
                   6401: 
1.157     albertel 6402: sub scantron_validate_ID {
                   6403:     my ($r,$currentphase) = @_;
                   6404:     
                   6405:     #get student info
                   6406:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6407:     my %idmap=&username_to_idmap($classlist);
                   6408: 
                   6409:     #get scantron line setup
1.257     albertel 6410:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6411:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6412:     
                   6413:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6414: 
                   6415:     my %found=('ids'=>{},'usernames'=>{});
                   6416:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6417: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6418: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6419: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6420: 						 $scan_data);
                   6421: 	my $id=$$scan_record{'scantron.ID'};
                   6422: 	my $found;
                   6423: 	foreach my $checkid (keys(%idmap)) {
                   6424: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6425: 	}
                   6426: 	if ($found) {
                   6427: 	    my $username=$idmap{$found};
                   6428: 	    if ($found{'ids'}{$found}) {
                   6429: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6430: 					 $line,'duplicateID',$found);
1.194     albertel 6431: 		return(1,$currentphase);
1.157     albertel 6432: 	    } elsif ($found{'usernames'}{$username}) {
                   6433: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6434: 					 $line,'duplicateID',$username);
1.194     albertel 6435: 		return(1,$currentphase);
1.157     albertel 6436: 	    }
1.186     albertel 6437: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6438: 	    $found{'ids'}{$found}++;
                   6439: 	    $found{'usernames'}{$username}++;
                   6440: 	} else {
                   6441: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6442: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6443: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6444: 		    &scantron_get_correction($r,$i,$scan_record,
                   6445: 					     \%scantron_config,
                   6446: 					     $line,'duplicateID',$username);
1.194     albertel 6447: 		    return(1,$currentphase);
1.157     albertel 6448: 		} elsif (!defined($username)) {
                   6449: 		    &scantron_get_correction($r,$i,$scan_record,
                   6450: 					     \%scantron_config,
                   6451: 					     $line,'incorrectID');
1.194     albertel 6452: 		    return(1,$currentphase);
1.157     albertel 6453: 		}
                   6454: 		$found{'usernames'}{$username}++;
                   6455: 	    } else {
                   6456: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6457: 					 $line,'incorrectID');
1.194     albertel 6458: 		return(1,$currentphase);
1.157     albertel 6459: 	    }
                   6460: 	}
                   6461:     }
                   6462: 
                   6463:     return (0,$currentphase+1);
                   6464: }
                   6465: 
1.423     albertel 6466: =pod
                   6467: 
                   6468: =item scantron_get_correction
                   6469: 
1.424     albertel 6470:    Builds the interface screen to interact with the operator to fix a
                   6471:    specific error condition in a specific scanline
                   6472: 
                   6473:  Arguments:
                   6474:     $r           - Apache request object
                   6475:     $i           - number of the current scanline
                   6476:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6477:     $scan_config - hash ref as returned from &get_scantron_config()
                   6478:     $line        - full contents of the current scanline
                   6479:     $error       - error condition, valid values are
                   6480:                    'incorrectCODE', 'duplicateCODE',
                   6481:                    'doublebubble', 'missingbubble',
                   6482:                    'duplicateID', 'incorrectID'
                   6483:     $arg         - extra information needed
                   6484:        For errors:
                   6485:          - duplicateID   - paper number that this studentID was seen before on
                   6486:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6487:                            seen on before
                   6488:          - incorrectCODE - current incorrect CODE 
                   6489:          - doublebubble  - array ref of the bubble lines that have double
                   6490:                            bubble errors
                   6491:          - missingbubble - array ref of the bubble lines that have missing
                   6492:                            bubble errors
                   6493: 
1.423     albertel 6494: =cut
                   6495: 
1.157     albertel 6496: sub scantron_get_correction {
                   6497:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6498: 
1.454     banghart 6499: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6500: #to show both the current line and the previous one and allow skipping
                   6501: #the previous one or the current one
                   6502: 
1.333     albertel 6503:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.492     albertel 6504: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6505: 			    " for PaperID <tt>[_1]</tt>",
                   6506: 			    $$scan_record{'scantron.PaperID'})."</p> \n");
1.157     albertel 6507:     } else {
1.492     albertel 6508: 	$r->print("<p>".&mt("<b>An error was detected ($error)</b>".
                   6509: 			    " in scanline [_1] <pre>[_2]</pre>",
                   6510: 			    $i,$line)."</p> \n");
                   6511:     }
                   6512:     my $message="<p>".&mt("The ID on the form is  <tt>[_1]</tt><br />".
                   6513: 			  "The name on the paper is [_2],[_3]",
                   6514: 			  $$scan_record{'scantron.ID'},
                   6515: 			  $$scan_record{'scantron.LastName'},
                   6516: 			  $$scan_record{'scantron.FirstName'})."</p>";
1.242     albertel 6517: 
1.157     albertel 6518:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6519:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6520:     if ($error =~ /ID$/) {
1.186     albertel 6521: 	if ($error eq 'incorrectID') {
1.492     albertel 6522: 	    $r->print("<p>".&mt("The encoded ID is not in the classlist").
                   6523: 		      "</p>\n");
1.157     albertel 6524: 	} elsif ($error eq 'duplicateID') {
1.492     albertel 6525: 	    $r->print("<p>".&mt("The encoded ID has also been used by a previous paper [_1]",$arg)."</p>\n");
1.157     albertel 6526: 	}
1.242     albertel 6527: 	$r->print($message);
1.492     albertel 6528: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.157     albertel 6529: 	$r->print("\n<ul><li> ");
                   6530: 	#FIXME it would be nice if this sent back the user ID and
                   6531: 	#could do partial userID matches
                   6532: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6533: 				       'scantron_username','scantron_domain'));
                   6534: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6535: 	$r->print("\n@".
1.257     albertel 6536: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6537: 
                   6538: 	$r->print('</li>');
1.186     albertel 6539:     } elsif ($error =~ /CODE$/) {
                   6540: 	if ($error eq 'incorrectCODE') {
1.492     albertel 6541: 	    $r->print("<p>".&mt("The encoded CODE is not in the list of possible CODEs.")."</p>\n");
1.186     albertel 6542: 	} elsif ($error eq 'duplicateCODE') {
1.492     albertel 6543: 	    $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 6544: 	}
1.492     albertel 6545: 	$r->print("<p>".&mt("The CODE on the form is  <tt>'[_1]'</tt>",
                   6546: 			    $$scan_record{'scantron.CODE'})."<br />\n");
1.242     albertel 6547: 	$r->print($message);
1.492     albertel 6548: 	$r->print("<p>".&mt("How should I handle this?")." <br /> \n");
1.187     albertel 6549: 	$r->print("\n<br /> ");
1.194     albertel 6550: 	my $i=0;
1.273     albertel 6551: 	if ($error eq 'incorrectCODE' 
                   6552: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6553: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6554: 	    if ($closest > 0) {
                   6555: 		foreach my $testcode (@{$closest}) {
                   6556: 		    my $checked='';
1.401     albertel 6557: 		    if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6558: 		    $r->print("
                   6559:    <label>
                   6560:        <input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked />
                   6561:        ".&mt("Use the similar CODE [_1] instead.",
                   6562: 	    "<b><tt>".$testcode."</tt></b>")."
                   6563:     </label>
                   6564:     <input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
1.278     albertel 6565: 		    $r->print("\n<br />");
                   6566: 		    $i++;
                   6567: 		}
1.194     albertel 6568: 	    }
                   6569: 	}
1.273     albertel 6570: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6571: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.492     albertel 6572: 	    $r->print("
                   6573:     <label>
                   6574:         <input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked />
                   6575:        ".&mt("Use the CODE [_1] that is was on the paper, ignoring the error.",
                   6576: 	     "<b><tt>".$$scan_record{'scantron.CODE'}."</tt></b>")."
                   6577:     </label>");
1.273     albertel 6578: 	    $r->print("\n<br />");
                   6579: 	}
1.194     albertel 6580: 
1.188     albertel 6581: 	$r->print(<<ENDSCRIPT);
                   6582: <script type="text/javascript">
                   6583: function change_radio(field) {
1.190     albertel 6584:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6585:     var i;
                   6586:     for (i=0;i<slct.length;i++) {
                   6587:         if (slct[i].value==field) { slct[i].checked=true; }
                   6588:     }
                   6589: }
                   6590: </script>
                   6591: ENDSCRIPT
1.187     albertel 6592: 	my $href="/adm/pickcode?".
1.359     www      6593: 	   "form=".&escape("scantronupload").
                   6594: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6595: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6596: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6597: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6598: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
1.492     albertel 6599: 	    $r->print("
                   6600:     <label>
                   6601:        <input type='radio' name='scantron_CODE_resolution' value='use_found' />
                   6602:        ".&mt("[_1]Select[_2] a CODE from the list of all CODEs and use it.",
                   6603: 	     "<a target='_blank' href='$href'>","</a>")."
                   6604:     </label> 
                   6605:     ".&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 6606: 	    $r->print("\n<br />");
                   6607: 	}
1.492     albertel 6608: 	$r->print("
                   6609:     <label>
                   6610:        <input type='radio' name='scantron_CODE_resolution' value='use_typed' />
                   6611:        ".&mt("Use [_1] as the CODE.",
                   6612: 	     "</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 6613: 	$r->print("\n<br /><br />");
1.157     albertel 6614:     } elsif ($error eq 'doublebubble') {
1.492     albertel 6615: 	$r->print("<p>".&mt("There have been multiple bubbles scanned for a some question(s)")."</p>\n");
1.157     albertel 6616: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6617: 		  join(',',@{$arg}).'" />');
1.242     albertel 6618: 	$r->print($message);
1.492     albertel 6619: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading")."</p>");
1.157     albertel 6620: 	foreach my $question (@{$arg}) {
1.447     foxr     6621: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6622: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6623: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6624: 				      @select_array);
1.157     albertel 6625: 	}
                   6626:     } elsif ($error eq 'missingbubble') {
1.492     albertel 6627: 	$r->print("<p>".&mt("There have been <b>no</b> bubbles scanned for some question(s)")."</p>\n");
1.242     albertel 6628: 	$r->print($message);
1.492     albertel 6629: 	$r->print("<p>".&mt("Please indicate which bubble should be used for grading.")."</p>");
                   6630: 	$r->print(&mt("Some questions have no scanned bubbles")."\n");
1.157     albertel 6631: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6632: 		  join(',',@{$arg}).'" />');
                   6633: 	foreach my $question (@{$arg}) {
1.448     foxr     6634: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6635: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6636: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6637: 	}
                   6638:     } else {
                   6639: 	$r->print("\n<ul>");
                   6640:     }
                   6641:     $r->print("\n</li></ul>");
                   6642: 
                   6643: }
1.423     albertel 6644: 
                   6645: =pod
                   6646: 
                   6647: =item scantron_bubble_selector
                   6648:   
                   6649:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6650:    possibly showing the existing the selected bubbles if known
1.423     albertel 6651: 
                   6652:  Arguments:
                   6653:     $r           - Apache request object
                   6654:     $scan_config - hash from &get_scantron_config()
                   6655:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6656:     @lines       - array of answer lines.
1.423     albertel 6657: 
                   6658: =cut
                   6659: 
1.157     albertel 6660: sub scantron_bubble_selector {
1.461     foxr     6661:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6662:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6663: 
1.461     foxr     6664: 
1.274     albertel 6665:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6666: 
1.461     foxr     6667:     my $bubble_length = scalar(@lines);
1.460     foxr     6668: 
1.447     foxr     6669: 
1.274     albertel 6670:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6671: 
1.448     foxr     6672:     my $response = $quest-1;
                   6673:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6674: 
1.422     foxr     6675:     my $total_lines = $lines*2;
1.157     albertel 6676:     my @alphabet=('A'..'Z');
1.479     foxr     6677: 
1.422     foxr     6678:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6679: 
                   6680:     for (my $l = 0; $l < $lines; $l++) {
                   6681: 	if ($l != 0) {
                   6682: 	    $r->print('<tr>');
                   6683: 	}
1.462     foxr     6684: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6685: 	for (my $i=0;$i<$max;$i++) {
                   6686: 	    $r->print("\n".'<td align="center">');
                   6687: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6688: 		$r->print('X'); 
                   6689: 		shift(@selected) ;
                   6690: 	    } else { 
                   6691: 		$r->print('&nbsp;'); 
                   6692: 	    }
                   6693: 	    $r->print('</td>');
                   6694: 	    
                   6695: 	}
                   6696: 
                   6697: 	if ($l == 0) {
                   6698: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6699: 
                   6700: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
1.492     albertel 6701: 	      $quest.'" value="none" /> '.&mt('No bubble').' </label></td>');
1.422     foxr     6702: 	
                   6703: 	}
                   6704: 
                   6705: 	$r->print('</tr><tr>');
                   6706: 
                   6707: 	# FIXME: This may have to be a bit more clever for
                   6708: 	#        multiline questions (different values e.g..).
                   6709: 
                   6710: 	for (my $i=0;$i<$max;$i++) {
1.479     foxr     6711: 	    my $value = "$l:$i";	# Relative bubble line #: Bubble in line.
1.422     foxr     6712: 	    $r->print("\n".
                   6713: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
1.479     foxr     6714: 		      $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
1.422     foxr     6715: 	}
                   6716: 	$r->print('</tr>');
                   6717: 
                   6718: 	    
1.157     albertel 6719:     }
1.422     foxr     6720:     $r->print('</table>');
1.157     albertel 6721: }
                   6722: 
1.423     albertel 6723: =pod
                   6724: 
                   6725: =item num_matches
                   6726: 
1.424     albertel 6727:    Counts the number of characters that are the same between the two arguments.
                   6728: 
                   6729:  Arguments:
                   6730:    $orig - CODE from the scanline
                   6731:    $code - CODE to match against
                   6732: 
                   6733:  Returns:
                   6734:    $count - integer count of the number of same characters between the
                   6735:             two arguments
                   6736: 
1.423     albertel 6737: =cut
                   6738: 
1.194     albertel 6739: sub num_matches {
                   6740:     my ($orig,$code) = @_;
                   6741:     my @code=split(//,$code);
                   6742:     my @orig=split(//,$orig);
                   6743:     my $same=0;
                   6744:     for (my $i=0;$i<scalar(@code);$i++) {
                   6745: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6746:     }
                   6747:     return $same;
                   6748: }
                   6749: 
1.423     albertel 6750: =pod
                   6751: 
                   6752: =item scantron_get_closely_matching_CODEs
                   6753: 
1.424     albertel 6754:    Cycles through all CODEs and finds the set that has the greatest
                   6755:    number of same characters as the provided CODE
                   6756: 
                   6757:  Arguments:
                   6758:    $allcodes - hash ref returned by &get_codes()
                   6759:    $CODE     - CODE from the current scanline
                   6760: 
                   6761:  Returns:
                   6762:    2 element list
                   6763:     - first elements is number of how closely matching the best fit is 
                   6764:       (5 means best set has 5 matching characters)
                   6765:     - second element is an arrary ref containing the set of valid CODEs
                   6766:       that best fit the passed in CODE
                   6767: 
1.423     albertel 6768: =cut
                   6769: 
1.194     albertel 6770: sub scantron_get_closely_matching_CODEs {
                   6771:     my ($allcodes,$CODE)=@_;
                   6772:     my @CODEs;
                   6773:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6774: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6775:     }
                   6776: 
                   6777:     return ($#CODEs,$CODEs[-1]);
                   6778: }
                   6779: 
1.423     albertel 6780: =pod
                   6781: 
                   6782: =item get_codes
                   6783: 
1.424     albertel 6784:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6785:    set of remembered CODEs.
                   6786: 
                   6787:  Arguments:
                   6788:   $old_name - name of the set of remembered CODEs
                   6789:   $cdom     - domain of the course
                   6790:   $cnum     - internal course name
                   6791: 
                   6792:  Returns:
                   6793:   %allcodes - keys are the valid CODEs, values are all 1
                   6794: 
1.423     albertel 6795: =cut
                   6796: 
1.194     albertel 6797: sub get_codes {
1.280     foxr     6798:     my ($old_name, $cdom, $cnum) = @_;
                   6799:     if (!$old_name) {
                   6800: 	$old_name=$env{'form.scantron_CODElist'};
                   6801:     }
                   6802:     if (!$cdom) {
                   6803: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6804:     }
                   6805:     if (!$cnum) {
                   6806: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6807:     }
1.278     albertel 6808:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6809: 				    $cdom,$cnum);
                   6810:     my %allcodes;
                   6811:     if ($result{"type\0$old_name"} eq 'number') {
                   6812: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6813:     } else {
                   6814: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6815:     }
1.194     albertel 6816:     return %allcodes;
                   6817: }
                   6818: 
1.423     albertel 6819: =pod
                   6820: 
                   6821: =item scantron_validate_CODE
                   6822: 
1.424     albertel 6823:    Validates all scanlines in the selected file to not have any
                   6824:    invalid or underspecified CODEs and that none of the codes are
                   6825:    duplicated if this was requested.
                   6826: 
1.423     albertel 6827: =cut
                   6828: 
1.157     albertel 6829: sub scantron_validate_CODE {
                   6830:     my ($r,$currentphase) = @_;
1.257     albertel 6831:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6832:     if ($scantron_config{'CODElocation'} &&
                   6833: 	$scantron_config{'CODEstart'} &&
                   6834: 	$scantron_config{'CODElength'}) {
1.257     albertel 6835: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6836: 	    &FIXME_blow_up()
                   6837: 	}
                   6838:     } else {
                   6839: 	return (0,$currentphase+1);
                   6840:     }
                   6841:     
                   6842:     my %usedCODEs;
                   6843: 
1.194     albertel 6844:     my %allcodes=&get_codes();
1.186     albertel 6845: 
1.447     foxr     6846:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6847: 
1.186     albertel 6848:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6849:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6850: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6851: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6852: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6853: 						 $scan_data);
                   6854: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6855: 	my $error=0;
1.224     albertel 6856: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6857: 	    &scantron_get_correction($r,$i,$scan_record,
                   6858: 				     \%scantron_config,
                   6859: 				     $line,'incorrectCODE',\%allcodes);
                   6860: 	    return(1,$currentphase);
                   6861: 	}
1.221     albertel 6862: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6863: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6864: 	    &scantron_get_correction($r,$i,$scan_record,
                   6865: 				     \%scantron_config,
1.194     albertel 6866: 				     $line,'incorrectCODE',\%allcodes);
                   6867: 	    return(1,$currentphase);
1.186     albertel 6868: 	}
1.214     albertel 6869: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6870: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6871: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6872: 	    &scantron_get_correction($r,$i,$scan_record,
                   6873: 				     \%scantron_config,
1.194     albertel 6874: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6875: 	    return(1,$currentphase);
1.186     albertel 6876: 	}
1.194     albertel 6877: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6878:     }
1.157     albertel 6879:     return (0,$currentphase+1);
                   6880: }
                   6881: 
1.423     albertel 6882: =pod
                   6883: 
                   6884: =item scantron_validate_doublebubble
                   6885: 
1.424     albertel 6886:    Validates all scanlines in the selected file to not have any
                   6887:    bubble lines with multiple bubbles marked.
                   6888: 
1.423     albertel 6889: =cut
                   6890: 
1.157     albertel 6891: sub scantron_validate_doublebubble {
                   6892:     my ($r,$currentphase) = @_;
                   6893:     #get student info
                   6894:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6895:     my %idmap=&username_to_idmap($classlist);
                   6896: 
                   6897:     #get scantron line setup
1.257     albertel 6898:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6899:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6900: 
                   6901:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6902: 
1.157     albertel 6903:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6904: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6905: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6906: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6907: 						 $scan_data);
                   6908: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6909: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6910: 				 'doublebubble',
                   6911: 				 $$scan_record{'scantron.doubleerror'});
                   6912:     	return (1,$currentphase);
                   6913:     }
                   6914:     return (0,$currentphase+1);
                   6915: }
                   6916: 
1.423     albertel 6917: =pod
                   6918: 
                   6919: =item scantron_get_maxbubble
                   6920: 
1.424     albertel 6921:    Returns the maximum number of bubble lines that are expected to
                   6922:    occur. Does this by walking the selected sequence rendering the
                   6923:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6924:    for what the current value of the problem counter is.
                   6925: 
1.447     foxr     6926:    Caches the results to $env{'form.scantron_maxbubble'},
                   6927:    $env{'form.scantron.bubble_lines.n'} and 
                   6928:    $env{'form.scantron.first_bubble_line.n'}
                   6929:    which are the total number of bubble, lines, the number of bubble
                   6930:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6931: 
1.423     albertel 6932: =cut
                   6933: 
1.330     albertel 6934: sub scantron_get_maxbubble {    
1.257     albertel 6935:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6936: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6937: 	&restore_bubble_lines();
1.257     albertel 6938: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6939:     }
1.330     albertel 6940: 
1.447     foxr     6941:     my (undef, undef, $sequence) =
1.257     albertel 6942: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6943: 
1.447     foxr     6944:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6945:     my $map=$navmap->getResourceByUrl($sequence);
                   6946:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6947: 
                   6948:     &Apache::lonxml::clear_problem_counter();
                   6949: 
1.435     foxr     6950:     my $uname       = $env{'form.student'};
                   6951:     my $udom        = $env{'form.userdom'};
                   6952:     my $cid         = $env{'request.course.id'};
                   6953:     my $total_lines = 0;
                   6954:     %bubble_lines_per_response = ();
1.447     foxr     6955:     %first_bubble_line         = ();
1.435     foxr     6956: 
1.447     foxr     6957:   
                   6958:     my $response_number = 0;
                   6959:     my $bubble_line     = 0;
1.191     albertel 6960:     foreach my $resource (@resources) {
1.435     foxr     6961: 	my $symb = $resource->symb();
1.330     albertel 6962: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6963: 					('symb' => $resource->symb()),
                   6964: 					('grade_target' => 'analyze'),
                   6965: 					('grade_courseid' => $cid),
                   6966: 					('grade_domain' => $udom),
                   6967: 					('grade_username' => $uname));
1.436     albertel 6968: 	my (undef, $an) =
1.435     foxr     6969: 	    split(/_HASH_REF__/,$result, 2);
                   6970: 
                   6971: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6972: 
                   6973: 
                   6974: 
                   6975: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6976: 
1.490     foxr     6977: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
                   6978: 
1.460     foxr     6979: 
1.447     foxr     6980: 
                   6981: 	    # TODO - make this a persistent hash not an array.
                   6982: 
                   6983: 
                   6984: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6985: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6986: 	    $response_number++;
                   6987: 
                   6988: 	    $bubble_line +=  $lines;
                   6989: 	    $total_lines +=  $lines;
1.435     foxr     6990: 	}
                   6991: 
1.191     albertel 6992:     }
                   6993:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6994: 
                   6995:     &save_bubble_lines();
1.330     albertel 6996:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6997: 	$total_lines;
1.257     albertel 6998:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6999: }
                   7000: 
1.423     albertel 7001: =pod
                   7002: 
                   7003: =item scantron_validate_missingbubbles
                   7004: 
1.424     albertel 7005:    Validates all scanlines in the selected file to not have any
1.447     foxr     7006:     answers that don't have bubbles that have not been verified
                   7007:     to be bubble free.
1.424     albertel 7008: 
1.423     albertel 7009: =cut
                   7010: 
1.157     albertel 7011: sub scantron_validate_missingbubbles {
                   7012:     my ($r,$currentphase) = @_;
                   7013:     #get student info
                   7014:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7015:     my %idmap=&username_to_idmap($classlist);
                   7016: 
                   7017:     #get scantron line setup
1.257     albertel 7018:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7019:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7020:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7021:     if (!$max_bubble) { $max_bubble=2**31; }
                   7022:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7023: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7024: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7025: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7026: 						 $scan_data);
                   7027: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7028: 	my @to_correct;
1.470     foxr     7029: 	
                   7030: 	# Probably here's where the error is...
                   7031: 
1.157     albertel 7032: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   7033: 	    if ($missing > $max_bubble) { next; }
                   7034: 	    push(@to_correct,$missing);
                   7035: 	}
                   7036: 	if (@to_correct) {
                   7037: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7038: 				     $line,'missingbubble',\@to_correct);
                   7039: 	    return (1,$currentphase);
                   7040: 	}
                   7041: 
                   7042:     }
                   7043:     return (0,$currentphase+1);
                   7044: }
                   7045: 
1.423     albertel 7046: =pod
                   7047: 
                   7048: =item scantron_process_students
                   7049: 
                   7050:    Routine that does the actual grading of the bubble sheet information.
                   7051: 
                   7052:    The parsed scanline hash is added to %env 
                   7053: 
                   7054:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7055:    foreach resource , with the form data of
                   7056: 
                   7057: 	'submitted'     =>'scantron' 
                   7058: 	'grade_target'  =>'grade',
                   7059: 	'grade_username'=> username of student
                   7060: 	'grade_domain'  => domain of student
                   7061: 	'grade_courseid'=> of course
                   7062: 	'grade_symb'    => symb of resource to grade
                   7063: 
                   7064:     This triggers a grading pass. The problem grading code takes care
                   7065:     of converting the bubbled letter information (now in %env) into a
                   7066:     valid submission.
                   7067: 
                   7068: =cut
                   7069: 
1.82      albertel 7070: sub scantron_process_students {
1.75      albertel 7071:     my ($r) = @_;
1.257     albertel 7072:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7073:     my ($symb)=&get_symb($r);
1.81      albertel 7074:     if (!$symb) {return '';}
1.324     albertel 7075:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7076: 
1.257     albertel 7077:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7078:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7079:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7080:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7081:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7082:     my $map=$navmap->getResourceByUrl($sequence);
                   7083:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7084: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7085:     my $result= <<SCANTRONFORM;
1.81      albertel 7086: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7087:   <input type="hidden" name="command" value="scantron_configphase" />
                   7088:   $default_form_data
                   7089: SCANTRONFORM
1.82      albertel 7090:     $r->print($result);
                   7091: 
                   7092:     my @delayqueue;
1.140     albertel 7093:     my %completedstudents;
                   7094:     
1.200     albertel 7095:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7096:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7097:  				    'Scantron Progress',$count,
1.195     albertel 7098: 				    'inline',undef,'scantronupload');
1.140     albertel 7099:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7100: 					  'Processing first student');
                   7101:     my $start=&Time::HiRes::time();
1.158     albertel 7102:     my $i=-1;
1.200     albertel 7103:     my ($uname,$udom,$started);
1.447     foxr     7104: 
                   7105:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   7106: 
1.157     albertel 7107:     while ($i<$scanlines->{'count'}) {
                   7108:  	($uname,$udom)=('','');
                   7109:  	$i++;
1.200     albertel 7110:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7111:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7112: 	if ($started) {
                   7113: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7114: 						     'last student');
                   7115: 	}
                   7116: 	$started=1;
1.157     albertel 7117:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7118:  						 $scan_data);
                   7119:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7120:  					      \%idmap,$i)) {
                   7121:   	    &scantron_add_delay(\@delayqueue,$line,
                   7122:  				'Unable to find a student that matches',1);
                   7123:  	    next;
                   7124:   	}
                   7125:  	if (exists $completedstudents{$uname}) {
                   7126:  	    &scantron_add_delay(\@delayqueue,$line,
                   7127:  				'Student '.$uname.' has multiple sheets',2);
                   7128:  	    next;
                   7129:  	}
                   7130:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7131: 
                   7132: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7133:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7134: 
                   7135: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7136: 	    &scantron_putfile($scanlines,$scan_data);
                   7137: 	}
1.161     albertel 7138: 	
                   7139: 	my $i=0;
1.83      albertel 7140: 	foreach my $resource (@resources) {
1.85      albertel 7141: 	    $i++;
1.193     albertel 7142: 	    my %form=('submitted'     =>'scantron',
                   7143: 		      'grade_target'  =>'grade',
                   7144: 		      'grade_username'=>$uname,
                   7145: 		      'grade_domain'  =>$udom,
1.257     albertel 7146: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7147: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7148: 	    if (exists($scan_record->{'scantron.CODE'})
                   7149: 		&& 
                   7150: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7151: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7152: 	    } else {
                   7153: 		$form{'CODE'}='';
1.193     albertel 7154: 	    }
                   7155: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7156: 	    if ($result ne '') {
                   7157: 	    }
1.213     albertel 7158: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7159: 	}
1.140     albertel 7160: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7161: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7162:     } continue {
1.330     albertel 7163: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7164: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7165:     }
1.140     albertel 7166:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7167: #    my $lasttime = &Time::HiRes::time()-$start;
                   7168: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7169: 
1.200     albertel 7170:     $r->print("</form>");
1.324     albertel 7171:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7172:     return '';
1.75      albertel 7173: }
1.157     albertel 7174: 
1.423     albertel 7175: =pod
                   7176: 
                   7177: =item scantron_upload_scantron_data
                   7178: 
                   7179:     Creates the screen for adding a new bubble sheet data file to a course.
                   7180: 
                   7181: =cut
                   7182: 
1.157     albertel 7183: sub scantron_upload_scantron_data {
                   7184:     my ($r)=@_;
1.257     albertel 7185:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7186:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7187: 							  'domainid',
                   7188: 							  'coursename');
1.257     albertel 7189:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7190: 						   'domainid');
1.324     albertel 7191:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.492     albertel 7192:     $r->print('
1.157     albertel 7193: <script type="text/javascript" language="javascript">
                   7194:     function checkUpload(formname) {
                   7195: 	if (formname.upfile.value == "") {
                   7196: 	    alert("Please use the browse button to select a file from your local directory.");
                   7197: 	    return false;
                   7198: 	}
                   7199: 	formname.submit();
                   7200:     }
                   7201: </script>
                   7202: 
1.492     albertel 7203: <form enctype="multipart/form-data" action="/adm/grades" name="rules" method="post">
                   7204: '.$default_form_data.'
1.181     albertel 7205: <table>
1.492     albertel 7206: <tr><td>'.$select_link.'                             </td></tr>
                   7207: <tr><td>'.&mt('Course ID:').'     </td>
                   7208:     <td><input name="courseid"   type="text" />      </td></tr>
                   7209: <tr><td>'.&mt('Course Name:').'   </td>
                   7210:     <td><input name="coursename" type="text" />      </td></tr>
                   7211: <tr><td>'.&mt('Domain:').'        </td>
                   7212:     <td>'.$domsel.'                                  </td></tr>
                   7213: <tr><td>'.&mt('File to upload:').'</td>
                   7214:     <td><input type="file" name="upfile" size="50" /></td></tr>
1.181     albertel 7215: </table>
1.492     albertel 7216: <input name="command" value="scantronupload_save" type="hidden" />
                   7217: <input type="button" onClick="javascript:checkUpload(this.form);" value="'.&mt('Upload Scantron Data').'" />
1.157     albertel 7218: </form>
1.492     albertel 7219: ');
1.157     albertel 7220:     return '';
                   7221: }
                   7222: 
1.423     albertel 7223: =pod
                   7224: 
                   7225: =item scantron_upload_scantron_data_save
                   7226: 
                   7227:    Adds a provided bubble information data file to the course if user
                   7228:    has the correct privileges to do so.  
                   7229: 
                   7230: =cut
                   7231: 
1.157     albertel 7232: sub scantron_upload_scantron_data_save {
                   7233:     my($r)=@_;
1.324     albertel 7234:     my ($symb)=&get_symb($r,1);
1.182     albertel 7235:     my $doanotherupload=
                   7236: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7237: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
1.492     albertel 7238: 	'<input type="submit" name="submit" value="'.&mt('Do Another Upload').'" />'."\n".
1.182     albertel 7239: 	'</form>'."\n";
1.257     albertel 7240:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7241: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7242: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.492     albertel 7243: 	$r->print(&mt("You are not allowed to upload Scantron data to the requested course.")."<br />");
1.182     albertel 7244: 	if ($symb) {
1.324     albertel 7245: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7246: 	} else {
                   7247: 	    $r->print($doanotherupload);
                   7248: 	}
1.162     albertel 7249: 	return '';
                   7250:     }
1.257     albertel 7251:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.492     albertel 7252:     $r->print(&mt("Doing upload to [_1]",$coursedata{'description'})." <br />");
1.257     albertel 7253:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7254:     #FIXME
                   7255:     #copied from lonnet::userfileupload()
                   7256:     #make that function able to target a specified course
                   7257:     # Replace Windows backslashes by forward slashes
                   7258:     $fname=~s/\\/\//g;
                   7259:     # Get rid of everything but the actual filename
                   7260:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7261:     # Replace spaces by underscores
                   7262:     $fname=~s/\s+/\_/g;
                   7263:     # Replace all other weird characters by nothing
                   7264:     $fname=~s/[^\w\.\-]//g;
                   7265:     # See if there is anything left
                   7266:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7267:     my $uploadedfile=$fname;
1.157     albertel 7268:     $fname='scantron_orig_'.$fname;
1.257     albertel 7269:     if (length($env{'form.upfile'}) < 2) {
1.492     albertel 7270: 	$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 7271:     } else {
1.275     albertel 7272: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7273: 	if ($result =~ m|^/uploaded/|) {
1.492     albertel 7274: 	    $r->print(&mt("<span class=\"LC_success\">Success:</span> Successfully uploaded [_1] bytes of data into location [_2]",
                   7275: 			  (length($env{'form.upfile'})-1),
                   7276: 			  '<span class="LC_filename">'.$result."</span>"));
1.210     albertel 7277: 	} else {
1.492     albertel 7278: 	    $r->print(&mt("<span class=\"LC_error\">Error:</span> An error ([_1]) occurred when attempting to upload the file, [_2]",
                   7279: 			  $result,
                   7280: 			  '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</span>"));
                   7281: 
1.183     albertel 7282: 	}
                   7283:     }
1.174     albertel 7284:     if ($symb) {
1.209     ng       7285: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7286:     } else {
1.182     albertel 7287: 	$r->print($doanotherupload);
1.174     albertel 7288:     }
1.157     albertel 7289:     return '';
                   7290: }
                   7291: 
1.423     albertel 7292: =pod
                   7293: 
                   7294: =item valid_file
                   7295: 
1.424     albertel 7296:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7297: 
                   7298: =cut
                   7299: 
1.202     albertel 7300: sub valid_file {
                   7301:     my ($requested_file)=@_;
                   7302:     foreach my $filename (sort(&scantron_filenames())) {
                   7303: 	if ($requested_file eq $filename) { return 1; }
                   7304:     }
                   7305:     return 0;
                   7306: }
                   7307: 
1.423     albertel 7308: =pod
                   7309: 
                   7310: =item scantron_download_scantron_data
                   7311: 
                   7312:    Shows a list of the three internal files (original, corrected,
                   7313:    skipped) for a specific bubble sheet data file that exists in the
                   7314:    course.
                   7315: 
                   7316: =cut
                   7317: 
1.202     albertel 7318: sub scantron_download_scantron_data {
                   7319:     my ($r)=@_;
1.324     albertel 7320:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7321:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7322:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7323:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7324:     if (! &valid_file($file)) {
1.492     albertel 7325: 	$r->print('
1.202     albertel 7326: 	<p>
1.492     albertel 7327: 	    '.&mt('The requested file name was invalid.').'
1.202     albertel 7328:         </p>
1.492     albertel 7329: ');
1.324     albertel 7330: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7331: 	return;
                   7332:     }
                   7333:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7334:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7335:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7336:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7337:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7338:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
1.492     albertel 7339:     $r->print('
1.202     albertel 7340:     <p>
1.492     albertel 7341: 	'.&mt('[_1]Original[_2] file as uploaded by the scantron office.',
                   7342: 	      '<a href="'.$orig.'">','</a>').'
1.202     albertel 7343:     </p>
                   7344:     <p>
1.492     albertel 7345: 	'.&mt('[_1]Corrections[_2], a file of corrected records that were used in grading.',
                   7346: 	      '<a href="'.$corrected.'">','</a>').'
1.202     albertel 7347:     </p>
                   7348:     <p>
1.492     albertel 7349: 	'.&mt('[_1]Skipped[_2], a file of records that were skipped.',
                   7350: 	      '<a href="'.$skipped.'">','</a>').'
1.202     albertel 7351:     </p>
1.492     albertel 7352: ');
1.324     albertel 7353:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7354:     return '';
                   7355: }
1.157     albertel 7356: 
1.423     albertel 7357: =pod
                   7358: 
                   7359: =back
                   7360: 
                   7361: =cut
                   7362: 
1.75      albertel 7363: #-------- end of section for handling grading scantron forms -------
                   7364: #
                   7365: #-------------------------------------------------------------------
                   7366: 
1.72      ng       7367: #-------------------------- Menu interface -------------------------
                   7368: #
                   7369: #--- Show a Grading Menu button - Calls the next routine ---
                   7370: sub show_grading_menu_form {
1.324     albertel 7371:     my ($symb)=@_;
1.125     ng       7372:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7373: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7374: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7375: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7376: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7377: 	'</form>'."\n";
                   7378:     return $result;
                   7379: }
                   7380: 
1.77      ng       7381: # -- Retrieve choices for grading form
                   7382: sub savedState {
                   7383:     my %savedState = ();
1.257     albertel 7384:     if ($env{'form.saveState'}) {
                   7385: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7386: 	    my ($key,$value) = split(/=/,$_,2);
                   7387: 	    $savedState{$key} = $value;
                   7388: 	}
                   7389:     }
                   7390:     return \%savedState;
                   7391: }
1.76      ng       7392: 
1.443     banghart 7393: sub grading_menu {
                   7394:     my ($request) = @_;
                   7395:     my ($symb)=&get_symb($request);
                   7396:     if (!$symb) {return '';}
                   7397:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7398:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7399: 
1.444     banghart 7400:     $request->print($table);
1.443     banghart 7401:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7402:                   'handgrade'=>$hdgrade,
                   7403:                   'probTitle'=>$probTitle,
                   7404:                   'command'=>'submit_options',
                   7405:                   'saveState'=>"",
                   7406:                   'gradingMenu'=>1,
                   7407:                   'showgrading'=>"yes");
                   7408:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7409:     my @menu = ({ url => $url,
                   7410:                      name => &mt('Manual Grading/View Submissions'),
                   7411:                      short_description => 
                   7412:     &mt('Start the process of hand grading submissions.'),
                   7413:                  });
                   7414:     $fields{'command'} = 'csvform';
                   7415:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7416:     push (@menu, { url => $url,
                   7417:                    name => &mt('Upload Scores'),
                   7418:                    short_description => 
                   7419:             &mt('Specify a file containing the class scores for current resource.')});
                   7420:     $fields{'command'} = 'processclicker';
                   7421:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7422:     push (@menu, { url => $url,
                   7423:                    name => &mt('Process Clicker'),
                   7424:                    short_description => 
                   7425:             &mt('Specify a file containing the clicker information for this resource.')});
                   7426:     $fields{'command'} = 'scantron_selectphase';
                   7427:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7428:     push (@menu, { url => $url,
1.454     banghart 7429:                    name => &mt('Grade/Manage Scantron Forms'),
                   7430:                    short_description => 
                   7431:             &mt('')});
1.443     banghart 7432:     $fields{'command'} = 'verify';
                   7433:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7434:     push (@menu, { url => "",
1.443     banghart 7435:                    name => &mt('Verify Receipt'),
                   7436:                    short_description => 
                   7437:             &mt('')});
                   7438:     #
                   7439:     # Create the menu
                   7440:     my $Str;
1.444     banghart 7441:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7442:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7443:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7444:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7445: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7446: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7447: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7448: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7449: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7450: 
1.443     banghart 7451:     foreach my $menudata (@menu) {
1.445     banghart 7452:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7453:             $Str .='    <h3><a '.
                   7454:                 $menudata->{'jscript'}.
                   7455:                 ' href="'.
                   7456:                 $menudata->{'url'}.'" >'.
                   7457:                 $menudata->{'name'}."</a></h3>\n";
                   7458:         } else {
1.485     albertel 7459:             $Str .='    <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 7460:                 $menudata->{'jscript'}.
1.458     banghart 7461:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7462:                 ' /></h3>';
1.446     banghart 7463:             $Str .= ('&nbsp;'x8).
1.485     albertel 7464: 		&mt(' receipt: [_1]',
                   7465: 		    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7466:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
1.444     banghart 7467:         }
1.443     banghart 7468:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7469:             "\n";
                   7470:     }
1.444     banghart 7471:     $Str .="</form>\n";
1.443     banghart 7472:     $request->print(<<GRADINGMENUJS);
                   7473: <script type="text/javascript" language="javascript">
                   7474:     function checkChoice(formname,val,cmdx) {
                   7475: 	if (val <= 2) {
                   7476: 	    var cmd = radioSelection(formname.radioChoice);
                   7477: 	    var cmdsave = cmd;
                   7478: 	} else {
                   7479: 	    cmd = cmdx;
                   7480: 	    cmdsave = 'submission';
                   7481: 	}
                   7482: 	formname.command.value = cmd;
                   7483: 	if (val < 5) formname.submit();
                   7484: 	if (val == 5) {
1.458     banghart 7485: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7486: 	        return false;
                   7487: 	    } else {
                   7488: 	        formname.submit();
                   7489: 	    }
1.445     banghart 7490: 	}
                   7491:     }
1.443     banghart 7492: 
                   7493:     function checkReceiptNo(formname,nospace) {
                   7494: 	var receiptNo = formname.receipt.value;
                   7495: 	var checkOpt = false;
                   7496: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7497: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7498: 	if (checkOpt) {
                   7499: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7500: 	    formname.receipt.value = "";
                   7501: 	    formname.receipt.focus();
                   7502: 	    return false;
                   7503: 	}
                   7504: 	return true;
                   7505:     }
                   7506: </script>
                   7507: GRADINGMENUJS
                   7508:     &commonJSfunctions($request);
                   7509:     return $Str;    
                   7510: }
                   7511: 
                   7512: 
                   7513: #--- Displays the submissions first page -------
                   7514: sub submit_options {
1.72      ng       7515:     my ($request) = @_;
1.324     albertel 7516:     my ($symb)=&get_symb($request);
1.72      ng       7517:     if (!$symb) {return '';}
1.76      ng       7518:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7519: 
                   7520:     $request->print(<<GRADINGMENUJS);
                   7521: <script type="text/javascript" language="javascript">
1.116     ng       7522:     function checkChoice(formname,val,cmdx) {
                   7523: 	if (val <= 2) {
                   7524: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7525: 	    var cmdsave = cmd;
1.116     ng       7526: 	} else {
                   7527: 	    cmd = cmdx;
1.118     ng       7528: 	    cmdsave = 'submission';
1.116     ng       7529: 	}
                   7530: 	formname.command.value = cmd;
1.118     ng       7531: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7532: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7533: 	if (val < 5) formname.submit();
                   7534: 	if (val == 5) {
1.72      ng       7535: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7536: 	    formname.submit();
                   7537: 	}
1.238     albertel 7538: 	if (val < 7) formname.submit();
1.72      ng       7539:     }
                   7540: 
                   7541:     function checkReceiptNo(formname,nospace) {
                   7542: 	var receiptNo = formname.receipt.value;
                   7543: 	var checkOpt = false;
                   7544: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7545: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7546: 	if (checkOpt) {
                   7547: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7548: 	    formname.receipt.value = "";
                   7549: 	    formname.receipt.focus();
                   7550: 	    return false;
                   7551: 	}
                   7552: 	return true;
                   7553:     }
                   7554: </script>
                   7555: GRADINGMENUJS
1.118     ng       7556:     &commonJSfunctions($request);
1.324     albertel 7557:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7558:     my $result;
1.76      ng       7559:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7560:     my $savedState = &savedState();
1.118     ng       7561:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7562:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7563:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7564:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7565: 
                   7566:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7567: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7568: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7569: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7570: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7571: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7572: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7573: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7574: 
1.472     albertel 7575:     $result.='
                   7576:     <div class="LC_grade_select_mode">
1.473     albertel 7577:       <div class="LC_grade_select_mode_current">
                   7578:         <h2>
                   7579:           '.&mt('Grade Current Resource').'
                   7580:         </h2>
                   7581:         <div class="LC_grade_select_mode_body">
                   7582:           <div class="LC_grades_resource_info">
                   7583:            '.$table.'
                   7584:           </div>
                   7585:           <div class="LC_grade_select_mode_selector">
                   7586:              <div class="LC_grade_select_mode_selector_header">
                   7587:                 '.&mt('Sections').'
                   7588:              </div>
                   7589:              <div class="LC_grade_select_mode_selector_body">
                   7590: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7591:     if (ref($sections)) {
1.472     albertel 7592: 	foreach my $section (sort (@$sections)) {
                   7593: 	    $result.='<option value="'.$section.'" '.
                   7594: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7595: 	}
1.116     ng       7596:     }
1.401     albertel 7597:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7598:     $result.='
1.473     albertel 7599:              </div>
                   7600:           </div>
                   7601:           <div class="LC_grade_select_mode_selector">
                   7602:              <div class="LC_grade_select_mode_selector_header">
                   7603:                 '.&mt('Groups').'
                   7604:              </div>
                   7605:              <div class="LC_grade_select_mode_selector_body">
                   7606:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7607:              </div>
1.472     albertel 7608:           </div>
1.473     albertel 7609:           <div class="LC_grade_select_mode_selector">
                   7610:              <div class="LC_grade_select_mode_selector_header">
                   7611:                 '.&mt('Access Status').'
                   7612:              </div>
                   7613:              <div class="LC_grade_select_mode_selector_body">
                   7614:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7615:              </div>
1.472     albertel 7616:           </div>
1.473     albertel 7617:           <div class="LC_grade_select_mode_selector">
                   7618:              <div class="LC_grade_select_mode_selector_header">
                   7619:                 '.&mt('Submission Status').'
                   7620:              </div>
                   7621:              <div class="LC_grade_select_mode_selector_body">
                   7622:                <select name="submitonly" size="5">
                   7623: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7624: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7625: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7626: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7627:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7628:                </select>
                   7629:              </div>
1.472     albertel 7630:           </div>
1.473     albertel 7631:           <div class="LC_grade_select_mode_type_body">
                   7632:             <div class="LC_grade_select_mode_type">
                   7633:               <label>
                   7634:                 <input type="radio" name="radioChoice" value="submission" '.
                   7635:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7636:              &mt('Select individual students to grade and view submissions.').'
                   7637: 	      </label> 
                   7638:             </div>
                   7639:             <div class="LC_grade_select_mode_type">
                   7640: 	      <label>
                   7641:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7642:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7643:                     &mt('Grade all selected students in a grading table.').'
                   7644:               </label>
                   7645:             </div>
                   7646:             <div class="LC_grade_select_mode_type">
                   7647: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7648:             </div>
1.472     albertel 7649:           </div>
1.473     albertel 7650:         </div>
                   7651:       </div>
                   7652:       <div class="LC_grade_select_mode_page">
                   7653:         <h2>
                   7654:          '.&mt('Grade Complete Folder for One Student').'
                   7655:         </h2>
                   7656:         <div class="LC_grades_select_mode_body">
                   7657:           <div class="LC_grade_select_mode_type_body">
                   7658:             <div class="LC_grade_select_mode_type">
                   7659:               <label>
                   7660:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7661: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7662:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7663:               </label>
                   7664:             </div>
                   7665:             <div class="LC_grade_select_mode_type">
                   7666: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7667:             </div>
1.472     albertel 7668:           </div>
                   7669:         </div>
                   7670:       </div>
                   7671:     </div>
                   7672:   </form>';
1.44      ng       7673:     return $result;
1.2       albertel 7674: }
                   7675: 
1.285     albertel 7676: sub reset_perm {
                   7677:     undef(%perm);
                   7678: }
                   7679: 
                   7680: sub init_perm {
                   7681:     &reset_perm();
1.300     albertel 7682:     foreach my $test_perm ('vgr','mgr','opa') {
                   7683: 
                   7684: 	my $scope = $env{'request.course.id'};
                   7685: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7686: 
                   7687: 	    $scope .= '/'.$env{'request.course.sec'};
                   7688: 	    if ( $perm{$test_perm}=
                   7689: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7690: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7691: 	    } else {
                   7692: 		delete($perm{$test_perm});
                   7693: 	    }
1.285     albertel 7694: 	}
                   7695:     }
                   7696: }
                   7697: 
1.400     www      7698: sub gather_clicker_ids {
1.408     albertel 7699:     my %clicker_ids;
1.400     www      7700: 
                   7701:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7702: 
                   7703:     # Set up a couple variables.
1.407     albertel 7704:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7705:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7706:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7707: 
1.407     albertel 7708:     foreach my $student (keys(%$classlist)) {
1.438     www      7709:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7710:         my $username = $classlist->{$student}->[$username_idx];
                   7711:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7712:         my $clickers =
1.408     albertel 7713: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7714:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7715:             $id=~s/^[\#0]+//;
1.421     www      7716:             $id=~s/[\-\:]//g;
1.407     albertel 7717:             if (exists($clicker_ids{$id})) {
1.408     albertel 7718: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7719:             } else {
1.408     albertel 7720: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7721:             }
                   7722:         }
                   7723:     }
1.407     albertel 7724:     return %clicker_ids;
1.400     www      7725: }
                   7726: 
1.402     www      7727: sub gather_adv_clicker_ids {
1.408     albertel 7728:     my %clicker_ids;
1.402     www      7729:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7730:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7731:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7732:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7733:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7734:             my ($puname,$pudom)=split(/\:/,$person);
                   7735:             my $clickers =
1.408     albertel 7736: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7737:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7738: 		$id=~s/^[\#0]+//;
1.421     www      7739:                 $id=~s/[\-\:]//g;
1.408     albertel 7740: 		if (exists($clicker_ids{$id})) {
                   7741: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7742: 		} else {
                   7743: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7744: 		}
1.405     www      7745:             }
1.402     www      7746:         }
                   7747:     }
1.407     albertel 7748:     return %clicker_ids;
1.402     www      7749: }
                   7750: 
1.413     www      7751: sub clicker_grading_parameters {
                   7752:     return ('gradingmechanism' => 'scalar',
                   7753:             'upfiletype' => 'scalar',
                   7754:             'specificid' => 'scalar',
                   7755:             'pcorrect' => 'scalar',
                   7756:             'pincorrect' => 'scalar');
                   7757: }
                   7758: 
1.400     www      7759: sub process_clicker {
                   7760:     my ($r)=@_;
                   7761:     my ($symb)=&get_symb($r);
                   7762:     if (!$symb) {return '';}
                   7763:     my $result=&checkforfile_js();
                   7764:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7765:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7766:     $result.=$table;
                   7767:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7768:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7769:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7770:         '.</b></td></tr>'."\n";
                   7771:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7772: # Attempt to restore parameters from last session, set defaults if not present
                   7773:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7774:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7775:                                                  \%Saveable_Parameters);
                   7776:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7777:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7778:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7779:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7780: 
                   7781:     my %checked;
                   7782:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7783:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7784:           $checked{$gradingmechanism}="checked='checked'";
                   7785:        }
                   7786:     }
                   7787: 
1.400     www      7788:     my $upload=&mt("Upload File");
                   7789:     my $type=&mt("Type");
1.402     www      7790:     my $attendance=&mt("Award points just for participation");
                   7791:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7792:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7793:     my $pcorrect=&mt("Percentage points for correct solution");
                   7794:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7795:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7796: 						   ('iclicker' => 'i>clicker',
                   7797:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7798:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7799:     $result.=<<ENDUPFORM;
1.402     www      7800: <script type="text/javascript">
                   7801: function sanitycheck() {
                   7802: // Accept only integer percentages
                   7803:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7804:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7805: // Find out grading choice
                   7806:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7807:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7808:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7809:       }
                   7810:    }
                   7811: // By default, new choice equals user selection
                   7812:    newgradingchoice=gradingchoice;
                   7813: // Not good to give more points for false answers than correct ones
                   7814:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7815:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7816:    }
                   7817: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7818:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7819:       document.forms.gradesupload.pcorrect.value=100;
                   7820:       document.forms.gradesupload.pincorrect.value=100;
                   7821:    }
                   7822: // If the values are different, cannot be attendance only
                   7823:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7824:        (gradingchoice=='attendance')) {
                   7825:        newgradingchoice='personnel';
                   7826:    }
                   7827: // Change grading choice to new one
                   7828:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7829:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7830:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7831:       } else {
                   7832:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7833:       }
                   7834:    }
                   7835: // Remember the old state
                   7836:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7837: }
                   7838: </script>
1.400     www      7839: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7840: <input type="hidden" name="symb" value="$symb" />
                   7841: <input type="hidden" name="command" value="processclickerfile" />
                   7842: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7843: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7844: <input type="file" name="upfile" size="50" />
                   7845: <br /><label>$type: $selectform</label>
1.451     albertel 7846: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7847: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7848: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7849: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7850: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7851: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7852: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7853: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7854: </form>
                   7855: ENDUPFORM
                   7856:     $result.='</td></tr></table>'."\n".
                   7857:              '</td></tr></table><br /><br />'."\n";
                   7858:     $result.=&show_grading_menu_form($symb);
                   7859:     return $result;
                   7860: }
                   7861: 
                   7862: sub process_clicker_file {
                   7863:     my ($r)=@_;
                   7864:     my ($symb)=&get_symb($r);
                   7865:     if (!$symb) {return '';}
1.413     www      7866: 
                   7867:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7868:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7869:                                               \%Saveable_Parameters);
                   7870: 
1.400     www      7871:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7872:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7873: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7874: 	return $result.&show_grading_menu_form($symb);
1.404     www      7875:     }
1.407     albertel 7876:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7877:     my %correct_ids;
1.404     www      7878:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7879: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7880:     }
                   7881:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7882: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7883: 	   $correct_id=~tr/a-z/A-Z/;
                   7884: 	   $correct_id=~s/\s//gs;
                   7885: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7886:            $correct_id=~s/[\-\:]//g;
1.414     www      7887:            if ($correct_id) {
                   7888: 	      $correct_ids{$correct_id}='specified';
                   7889:            }
                   7890:         }
1.400     www      7891:     }
1.404     www      7892:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7893: 	$result.=&mt('Score based on attendance only');
1.404     www      7894:     } else {
1.408     albertel 7895: 	my $number=0;
1.411     www      7896: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7897: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7898: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7899: 	    if ($correct_ids{$id} eq 'specified') {
                   7900: 		$result.=&mt('specified');
                   7901: 	    } else {
                   7902: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7903: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7904: 	    }
                   7905: 	    $number++;
                   7906: 	}
1.411     www      7907:         $result.="</p>\n";
1.408     albertel 7908: 	if ($number==0) {
                   7909: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7910: 	    return $result.&show_grading_menu_form($symb);
                   7911: 	}
1.404     www      7912:     }
1.405     www      7913:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7914:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7915: 		     '<span class="LC_error">',
                   7916: 		     '</span>',
                   7917: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7918:         return $result.&show_grading_menu_form($symb);
                   7919:     }
1.410     www      7920: 
                   7921: # Were able to get all the info needed, now analyze the file
                   7922: 
1.411     www      7923:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7924:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7925:     my $heading=&mt('Scanning clicker file');
                   7926:     $result.=(<<ENDHEADER);
                   7927: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7928: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7929: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7930: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7931: <input type="hidden" name="symb" value="$symb" />
                   7932: <input type="hidden" name="command" value="assignclickergrades" />
                   7933: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7934: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7935: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7936: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7937: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7938: ENDHEADER
1.408     albertel 7939:     my %responses;
                   7940:     my @questiontitles;
1.405     www      7941:     my $errormsg='';
                   7942:     my $number=0;
                   7943:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7944: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7945:     }
1.419     www      7946:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7947:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7948:     }
1.411     www      7949:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7950:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7951:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7952:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7953:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7954:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7955:              '<br />';
1.414     www      7956: # Remember Question Titles
                   7957: # FIXME: Possibly need delimiter other than ":"
                   7958:     for (my $i=0;$i<$number;$i++) {
                   7959:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7960:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7961:     }
1.411     www      7962:     my $correct_count=0;
                   7963:     my $student_count=0;
                   7964:     my $unknown_count=0;
1.414     www      7965: # Match answers with usernames
                   7966: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7967:     foreach my $id (keys(%responses)) {
1.410     www      7968:        if ($correct_ids{$id}) {
1.414     www      7969:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7970:           $correct_count++;
1.410     www      7971:        } elsif ($clicker_ids{$id}) {
1.437     www      7972:           if ($clicker_ids{$id}=~/\,/) {
                   7973: # More than one user with the same clicker!
                   7974:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7975:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7976:                            "<select name='multi".$id."'>";
                   7977:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7978:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7979:              }
                   7980:              $result.='</select>';
                   7981:              $unknown_count++;
                   7982:           } else {
                   7983: # Good: found one and only one user with the right clicker
                   7984:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7985:              $student_count++;
                   7986:           }
1.410     www      7987:        } else {
1.411     www      7988:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7989:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7990:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7991:                    "\n".&mt("Domain").": ".
                   7992:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7993:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7994:           $unknown_count++;
1.410     www      7995:        }
1.405     www      7996:     }
1.412     www      7997:     $result.='<hr />'.
                   7998:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7999:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   8000:        if ($correct_count==0) {
                   8001:           $errormsg.="Found no correct answers answers for grading!";
                   8002:        } elsif ($correct_count>1) {
1.414     www      8003:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      8004:        }
                   8005:     }
1.428     www      8006:     if ($number<1) {
                   8007:        $errormsg.="Found no questions.";
                   8008:     }
1.412     www      8009:     if ($errormsg) {
                   8010:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   8011:     } else {
                   8012:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   8013:     }
                   8014:     $result.='</form></td></tr></table>'."\n".
1.410     www      8015:              '</td></tr></table><br /><br />'."\n";
1.404     www      8016:     return $result.&show_grading_menu_form($symb);
1.400     www      8017: }
                   8018: 
1.405     www      8019: sub iclicker_eval {
1.406     www      8020:     my ($questiontitles,$responses)=@_;
1.405     www      8021:     my $number=0;
                   8022:     my $errormsg='';
                   8023:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      8024:         my %components=&Apache::loncommon::record_sep($line);
                   8025:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8026: 	if ($entries[0] eq 'Question') {
                   8027: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8028: 		$$questiontitles[$number]=$entries[$i];
                   8029: 		$number++;
                   8030: 	    }
                   8031: 	}
                   8032: 	if ($entries[0]=~/^\#/) {
                   8033: 	    my $id=$entries[0];
                   8034: 	    my @idresponses;
                   8035: 	    $id=~s/^[\#0]+//;
                   8036: 	    for (my $i=0;$i<$number;$i++) {
                   8037: 		my $idx=3+$i*6;
                   8038: 		push(@idresponses,$entries[$idx]);
                   8039: 	    }
                   8040: 	    $$responses{$id}=join(',',@idresponses);
                   8041: 	}
1.405     www      8042:     }
                   8043:     return ($errormsg,$number);
                   8044: }
                   8045: 
1.419     www      8046: sub interwrite_eval {
                   8047:     my ($questiontitles,$responses)=@_;
                   8048:     my $number=0;
                   8049:     my $errormsg='';
1.420     www      8050:     my $skipline=1;
                   8051:     my $questionnumber=0;
                   8052:     my %idresponses=();
1.419     www      8053:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8054:         my %components=&Apache::loncommon::record_sep($line);
                   8055:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8056:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8057:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8058:         next if $skipline;
                   8059:         if ($entries[0]!=$questionnumber) {
                   8060:            $questionnumber=$entries[0];
                   8061:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8062:            $number++;
1.419     www      8063:         }
1.420     www      8064:         my $id=$entries[4];
                   8065:         $id=~s/^[\#0]+//;
1.421     www      8066:         $id=~s/^v\d*\://i;
                   8067:         $id=~s/[\-\:]//g;
1.420     www      8068:         $idresponses{$id}[$number]=$entries[6];
                   8069:     }
                   8070:     foreach my $id (keys %idresponses) {
                   8071:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8072:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8073:     }
                   8074:     return ($errormsg,$number);
                   8075: }
                   8076: 
1.414     www      8077: sub assign_clicker_grades {
                   8078:     my ($r)=@_;
                   8079:     my ($symb)=&get_symb($r);
                   8080:     if (!$symb) {return '';}
1.416     www      8081: # See which part we are saving to
                   8082:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8083: # FIXME: This should probably look for the first handgradeable part
                   8084:     my $part=$$partlist[0];
                   8085: # Start screen output
1.414     www      8086:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8087: 
1.414     www      8088:     my $heading=&mt('Assigning grades based on clicker file');
                   8089:     $result.=(<<ENDHEADER);
                   8090: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8091: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8092: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8093: ENDHEADER
                   8094: # Get correct result
                   8095: # FIXME: Possibly need delimiter other than ":"
                   8096:     my @correct=();
1.415     www      8097:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8098:     my $number=$env{'form.number'};
                   8099:     if ($gradingmechanism ne 'attendance') {
1.414     www      8100:        foreach my $key (keys(%env)) {
                   8101:           if ($key=~/^form\.correct\:/) {
                   8102:              my @input=split(/\,/,$env{$key});
                   8103:              for (my $i=0;$i<=$#input;$i++) {
                   8104:                  if (($correct[$i]) && ($input[$i]) &&
                   8105:                      ($correct[$i] ne $input[$i])) {
                   8106:                     $result.='<br /><span class="LC_warning">'.
                   8107:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8108:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8109:                  } elsif ($input[$i]) {
                   8110:                     $correct[$i]=$input[$i];
                   8111:                  }
                   8112:              }
                   8113:           }
                   8114:        }
1.415     www      8115:        for (my $i=0;$i<$number;$i++) {
1.414     www      8116:           if (!$correct[$i]) {
                   8117:              $result.='<br /><span class="LC_error">'.
                   8118:                       &mt('No correct result given for question "[_1]"!',
                   8119:                           $env{'form.question:'.$i}).'</span>';
                   8120:           }
                   8121:        }
                   8122:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8123:     }
                   8124: # Start grading
1.415     www      8125:     my $pcorrect=$env{'form.pcorrect'};
                   8126:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8127:     my $storecount=0;
1.415     www      8128:     foreach my $key (keys(%env)) {
1.420     www      8129:        my $user='';
1.415     www      8130:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8131:           $user=$1;
                   8132:        }
                   8133:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8134:           my $id=$1;
                   8135:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8136:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8137:           } elsif ($env{'form.multi'.$id}) {
                   8138:              $user=$env{'form.multi'.$id};
1.420     www      8139:           }
                   8140:        }
                   8141:        if ($user) { 
1.415     www      8142:           my @answer=split(/\,/,$env{$key});
                   8143:           my $sum=0;
                   8144:           for (my $i=0;$i<$number;$i++) {
                   8145:              if ($answer[$i]) {
                   8146:                 if ($gradingmechanism eq 'attendance') {
                   8147:                    $sum+=$pcorrect;
                   8148:                 } else {
                   8149:                    if ($answer[$i] eq $correct[$i]) {
                   8150:                       $sum+=$pcorrect;
                   8151:                    } else {
                   8152:                       $sum+=$pincorrect;
                   8153:                    }
                   8154:                 }
                   8155:              }
                   8156:           }
1.416     www      8157:           my $ave=$sum/(100*$number);
                   8158: # Store
                   8159:           my ($username,$domain)=split(/\:/,$user);
                   8160:           my %grades=();
                   8161:           $grades{"resource.$part.solved"}='correct_by_override';
                   8162:           $grades{"resource.$part.awarded"}=$ave;
                   8163:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8164:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8165:                                                  $env{'request.course.id'},
                   8166:                                                  $domain,$username);
                   8167:           if ($returncode ne 'ok') {
                   8168:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8169:           } else {
                   8170:              $storecount++;
                   8171:           }
1.415     www      8172:        }
                   8173:     }
                   8174: # We are done
1.416     www      8175:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8176:              '</td></tr></table>'."\n".
1.414     www      8177:              '</td></tr></table><br /><br />'."\n";
                   8178:     return $result.&show_grading_menu_form($symb);
                   8179: }
                   8180: 
1.1       albertel 8181: sub handler {
1.41      ng       8182:     my $request=$_[0];
1.434     albertel 8183:     &reset_caches();
1.257     albertel 8184:     if ($env{'browser.mathml'}) {
1.141     www      8185: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8186:     } else {
1.141     www      8187: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8188:     }
                   8189:     $request->send_http_header;
1.44      ng       8190:     return '' if $request->header_only;
1.41      ng       8191:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8192:     my $symb=&get_symb($request,1);
1.160     albertel 8193:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8194:     my $command=$commands[0];
1.447     foxr     8195: 
1.160     albertel 8196:     if ($#commands > 0) {
                   8197: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8198:     }
1.447     foxr     8199: 
                   8200: 
1.353     albertel 8201:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8202:     if ($symb eq '' && $command eq '') {
1.257     albertel 8203: 	if ($env{'user.adv'}) {
                   8204: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8205: 		($env{'form.codethree'})) {
                   8206: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8207: 		    $env{'form.codethree'};
1.41      ng       8208: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8209: 		    &Apache::lonnet::checkin($token);
                   8210: 		if ($tsymb) {
1.137     albertel 8211: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8212: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8213: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8214: 					  ('grade_username' => $tuname,
                   8215: 					   'grade_domain' => $tudom,
                   8216: 					   'grade_courseid' => $tcrsid,
                   8217: 					   'grade_symb' => $tsymb)));
1.41      ng       8218: 		    } else {
1.45      ng       8219: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8220: 		    }
1.41      ng       8221: 		} else {
1.45      ng       8222: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8223: 		}
1.14      www      8224: 	    } else {
1.41      ng       8225: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8226: 	    }
                   8227: 	}
                   8228:     } else {
1.285     albertel 8229: 	&init_perm();
1.104     albertel 8230: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8231: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8232: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8233: 	    &pickStudentPage($request);
1.103     albertel 8234: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8235: 	    &displayPage($request);
1.104     albertel 8236: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8237: 	    &updateGradeByPage($request);
1.104     albertel 8238: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8239: 	    &processGroup($request);
1.104     albertel 8240: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8241: 	    $request->print(&grading_menu($request));
                   8242: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8243: 	    $request->print(&submit_options($request));
1.104     albertel 8244: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8245: 	    $request->print(&viewgrades($request));
1.104     albertel 8246: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8247: 	    $request->print(&processHandGrade($request));
1.106     albertel 8248: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8249: 	    $request->print(&editgrades($request));
1.106     albertel 8250: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8251: 	    $request->print(&verifyreceipt($request));
1.400     www      8252:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8253:             $request->print(&process_clicker($request));
                   8254:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8255:             $request->print(&process_clicker_file($request));
1.414     www      8256:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8257:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8258: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8259: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8260: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8261: 	    $request->print(&csvupload($request));
1.106     albertel 8262: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8263: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8264: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8265: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8266: 		$request->print(&csvuploadoptions($request));
1.41      ng       8267: 	    } else {
1.257     albertel 8268: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8269: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8270: 		} else {
1.257     albertel 8271: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8272: 		}
                   8273: 		$request->print(&csvuploadmap($request));
                   8274: 	    }
1.246     albertel 8275: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8276: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8277: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8278: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8279:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8280:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8281: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8282: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8283: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8284: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8285:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8286:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8287: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8288:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8289:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8290:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8291: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8292:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8293:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8294: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8295:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8296: 	} elsif ($command) {
1.157     albertel 8297: 	    $request->print("Access Denied ($command)");
1.26      albertel 8298: 	}
1.2       albertel 8299:     }
1.353     albertel 8300:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8301:     &reset_caches();
1.44      ng       8302:     return '';
                   8303: }
                   8304: 
1.1       albertel 8305: 1;
                   8306: 
1.13      albertel 8307: __END__;

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