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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.485   ! albertel    4: # $Id: grades.pm,v 1.484 2007/11/06 19:19:54 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.398     albertel  736:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    737: 	$receipt.'</h3></span>'."\n".
                    738: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        739: 
                    740:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   741:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  742:     
                    743:     my $receiptparts=0;
1.390     albertel  744:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    745: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  746:     my $parts=['0'];
1.324     albertel  747:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  748:     foreach (sort 
                    749: 	     {
                    750: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    751: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    752: 		 }
                    753: 		 return $a cmp $b;
                    754: 	     } (keys(%$fullname))) {
1.44      ng        755: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  756: 	foreach my $part (@$parts) {
                    757: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    758: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    759: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  760: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  761: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    762: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    763: 		if ($receiptparts) {
                    764: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    765: 		}
                    766: 		$contents.='</tr>'."\n";
                    767: 		
                    768: 		$matches++;
                    769: 	    }
1.44      ng        770: 	}
                    771:     }
                    772:     if ($matches == 0) {
                    773: 	$string = $title.'No match found for the above receipt.';
                    774:     } else {
1.324     albertel  775: 	$string = &jscriptNform($symb).$title.
1.44      ng        776: 	    'The above receipt matches the following student'.
                    777: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    778: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    779: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    780: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    781: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  782: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    783: 	if ($receiptparts) {
                    784: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    785: 	}
                    786: 	$string.='</tr>'."\n".$contents.
1.44      ng        787: 	    '</table></td></tr></table>'."\n";
                    788:     }
1.324     albertel  789:     return $string.&show_grading_menu_form($symb);
1.44      ng        790: }
                    791: 
                    792: #--- This is called by a number of programs.
                    793: #--- Called from the Grading Menu - View/Grade an individual student
                    794: #--- Also called directly when one clicks on the subm button 
                    795: #    on the problem page.
1.30      ng        796: sub listStudents {
1.41      ng        797:     my ($request) = shift;
1.49      albertel  798: 
1.324     albertel  799:     my ($symb) = &get_symb($request);
1.257     albertel  800:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    801:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    802:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  803:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  804:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    805:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    806:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    807: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  808: 
1.485   ! albertel  809:     my $result='<h3><span class="LC_info">&nbsp;'.
        !           810: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
        !           811: 	.'</span></h3>';
1.118     ng        812: 
1.324     albertel  813:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  814: 
1.485   ! albertel  815:     my %lt = ( 'multiple' =>
        !           816: 	       "Please select a student or group of students before clicking on the Next button.",
        !           817: 	       'single'   =>
        !           818: 	       "Please select the student before clicking on the Next button.",
        !           819: 	       );
        !           820:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        821:     $request->print(<<LISTJAVASCRIPT);
                    822: <script type="text/javascript" language="javascript">
1.110     ng        823:     function checkSelect(checkBox) {
                    824: 	var ctr=0;
                    825: 	var sense="";
                    826: 	if (checkBox.length > 1) {
                    827: 	    for (var i=0; i<checkBox.length; i++) {
                    828: 		if (checkBox[i].checked) {
                    829: 		    ctr++;
                    830: 		}
                    831: 	    }
1.485   ! albertel  832: 	    sense = '$lt{'multiple'}';
1.110     ng        833: 	} else {
                    834: 	    if (checkBox.checked) {
                    835: 		ctr = 1;
                    836: 	    }
1.485   ! albertel  837: 	    sense = '$lt{'single'}';
1.110     ng        838: 	}
                    839: 	if (ctr == 0) {
1.485   ! albertel  840: 	    alert(sense);
1.110     ng        841: 	    return false;
                    842: 	}
                    843: 	document.gradesub.submit();
                    844:     }
                    845: 
                    846:     function reLoadList(formname) {
1.112     ng        847: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        848: 	formname.command.value = 'submission';
                    849: 	formname.submit();
                    850:     }
1.45      ng        851: </script>
                    852: LISTJAVASCRIPT
                    853: 
1.118     ng        854:     &commonJSfunctions($request);
1.41      ng        855:     $request->print($result);
1.39      ng        856: 
1.401     albertel  857:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    858:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  859:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485   ! albertel  860: 	"\n".$table;
        !           861: 	
        !           862:     $gradeTable .= 
        !           863: 	'&nbsp;'.
        !           864: 	&mt('<b>View Problem Text: </b>[_1]',
        !           865: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
        !           866: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
        !           867: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
        !           868:     $gradeTable .= 
        !           869: 	'&nbsp;'.
        !           870: 	&mt('<b>View Answer: </b>[_1]',
        !           871: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
        !           872: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
        !           873: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
        !           874: 
        !           875:     my $submission_options;
1.257     albertel  876:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485   ! albertel  877: 	$submission_options.=
        !           878: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  879:     }
1.442     banghart  880:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    881:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  882:     $env{'form.Status'} = $saveStatus;
1.485   ! albertel  883:     $submission_options.=
        !           884: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
        !           885: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
        !           886: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
        !           887: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
        !           888:     $gradeTable .= 
        !           889: 	'&nbsp;'.
        !           890: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
        !           891: 
        !           892:     $gradeTable .= 
        !           893:         '&nbsp;'.
        !           894: 	&mt('<b>Grading Increments:</b> [_1]',
        !           895: 	    '<select name="increment">'.
        !           896: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
        !           897: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
        !           898: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
        !           899: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
        !           900: 	    '</select>');
        !           901:     
        !           902:     $gradeTable .= 
1.432     banghart  903:         &build_section_inputs().
1.45      ng        904: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  905: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    906: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    907: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    908: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  909: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        910: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    911: 
1.257     albertel  912:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  913: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        914:     } else {
1.485   ! albertel  915: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
        !           916: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        917:     }
1.112     ng        918: 
1.485   ! albertel  919:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
        !           920: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        921: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  922: 
                    923: # checkall buttons
                    924:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        925:     $gradeTable.='<input type="button" '."\n".
1.45      ng        926: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485   ! albertel  927: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  928:     $gradeTable.=&check_buttons();
1.485   ! albertel  929:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  930:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  931:     $gradeTable.= &Apache::loncommon::start_data_table().
                    932: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        933:     my $loop = 0;
                    934:     while ($loop < 2) {
1.485   ! albertel  935: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
        !           936: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  937: 	if ($env{'form.showgrading'} eq 'yes' 
                    938: 	    && $submitonly ne 'queued'
                    939: 	    && $submitonly ne 'all') {
1.485   ! albertel  940: 	    foreach my $part (sort(@$partlist)) {
        !           941: 		my $display_part=
        !           942: 		    &get_display_part((split(/_/,$part))[0],$symb);
        !           943: 		$gradeTable.=
        !           944: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        945: 	    }
1.301     albertel  946: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  947: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        948: 	}
                    949: 	$loop++;
1.126     ng        950: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        951:     }
1.474     albertel  952:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        953: 
1.45      ng        954:     my $ctr = 0;
1.294     albertel  955:     foreach my $student (sort 
                    956: 			 {
                    957: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    958: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    959: 			     }
                    960: 			     return $a cmp $b;
                    961: 			 }
                    962: 			 (keys(%$fullname))) {
1.41      ng        963: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  964: 
1.110     ng        965: 	my %status = ();
1.301     albertel  966: 
                    967: 	if ($submitonly eq 'queued') {
                    968: 	    my %queue_status = 
                    969: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    970: 							$udom,$uname);
                    971: 	    next if (!defined($queue_status{'gradingqueue'}));
                    972: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    973: 	}
                    974: 
                    975: 	if ($env{'form.showgrading'} eq 'yes' 
                    976: 	    && $submitonly ne 'queued'
                    977: 	    && $submitonly ne 'all') {
1.324     albertel  978: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  979: 	    my $submitted = 0;
1.164     albertel  980: 	    my $graded = 0;
1.248     albertel  981: 	    my $incorrect = 0;
1.110     ng        982: 	    foreach (keys(%status)) {
1.145     albertel  983: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  984: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    985: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    986: 		
1.110     ng        987: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    988: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  989: 		    $submitted = 0;
1.150     albertel  990: 		    my ($part)=split(/\./,$partid);
1.110     ng        991: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  992: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        993: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    994: 		}
1.41      ng        995: 	    }
1.248     albertel  996: 	    
1.156     albertel  997: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    998: 				     $submitonly eq 'incorrect' ||
                    999: 				     $submitonly eq 'graded'));
1.248     albertel 1000: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1001: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1002: 	}
1.34      ng       1003: 
1.45      ng       1004: 	$ctr++;
1.249     albertel 1005: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1006:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1007: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1008: 	    if ($ctr%2 ==1) {
                   1009: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1010: 	    }
1.126     ng       1011: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1012:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1013:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1014: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1015: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1016: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1017: 
1.257     albertel 1018: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng       1019: 		foreach (sort keys(%status)) {
1.485   ! albertel 1020: 		    next if ($_ =~ /^resource.*?submitted_by$/);
        !          1021: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1022: 		}
1.41      ng       1023: 	    }
1.126     ng       1024: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1025: 	    if ($ctr%2 ==0) {
                   1026: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1027: 	    }
1.41      ng       1028: 	}
                   1029:     }
1.110     ng       1030:     if ($ctr%2 ==1) {
1.126     ng       1031: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1032: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1033: 		&& $submitonly ne 'queued'
                   1034: 		&& $submitonly ne 'all') {
1.110     ng       1035: 		foreach (@$partlist) {
                   1036: 		    $gradeTable.='<td>&nbsp;</td>';
                   1037: 		}
1.301     albertel 1038: 	    } elsif ($submitonly eq 'queued') {
                   1039: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1040: 	    }
1.474     albertel 1041: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1042:     }
                   1043: 
1.474     albertel 1044:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1045: 	'<input type="button" '.
                   1046: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485   ! albertel 1047: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1048:     if ($ctr == 0) {
1.96      albertel 1049: 	my $num_students=(scalar(keys(%$fullname)));
                   1050: 	if ($num_students eq 0) {
1.485   ! albertel 1051: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1052: 	} else {
1.171     albertel 1053: 	    my $submissions='submissions';
                   1054: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1055: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1056: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1057: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485   ! albertel 1058: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
        !          1059: 		    $num_students).
        !          1060: 		'</span><br />';
1.96      albertel 1061: 	}
1.46      ng       1062:     } elsif ($ctr == 1) {
1.474     albertel 1063: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1064:     }
1.324     albertel 1065:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1066:     $request->print($gradeTable);
1.44      ng       1067:     return '';
1.10      ng       1068: }
                   1069: 
1.44      ng       1070: #---- Called from the listStudents routine
1.249     albertel 1071: 
                   1072: sub check_script {
                   1073:     my ($form, $type)=@_;
                   1074:     my $chkallscript='<script type="text/javascript">
                   1075:     function checkall() {
                   1076:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1077:             ele = document.forms.'.$form.'.elements[i];
                   1078:             if (ele.name == "'.$type.'") {
                   1079:             document.forms.'.$form.'.elements[i].checked=true;
                   1080:                                        }
                   1081:         }
                   1082:     }
                   1083: 
                   1084:     function checksec() {
                   1085:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1086:             ele = document.forms.'.$form.'.elements[i];
                   1087:            string = document.forms.'.$form.'.chksec.value;
                   1088:            if
                   1089:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1090:               document.forms.'.$form.'.elements[i].checked=true;
                   1091:             }
                   1092:         }
                   1093:     }
                   1094: 
                   1095: 
                   1096:     function uncheckall() {
                   1097:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1098:             ele = document.forms.'.$form.'.elements[i];
                   1099:             if (ele.name == "'.$type.'") {
                   1100:             document.forms.'.$form.'.elements[i].checked=false;
                   1101:                                        }
                   1102:         }
                   1103:     }
                   1104: 
                   1105: </script>'."\n";
                   1106:     return $chkallscript;
                   1107: }
                   1108: 
                   1109: sub check_buttons {
1.485   ! albertel 1110:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
        !          1111:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
        !          1112:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1113:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1114:     return $buttons;
                   1115: }
                   1116: 
1.44      ng       1117: #     Displays the submissions for one student or a group of students
1.34      ng       1118: sub processGroup {
1.41      ng       1119:     my ($request)  = shift;
                   1120:     my $ctr        = 0;
1.155     albertel 1121:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1122:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1123: 
1.396     banghart 1124:     foreach my $student (@stuchecked) {
                   1125: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1126: 	$env{'form.student'}        = $uname;
                   1127: 	$env{'form.userdom'}        = $udom;
                   1128: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1129: 	&submission($request,$ctr,$total);
                   1130: 	$ctr++;
                   1131:     }
                   1132:     return '';
1.35      ng       1133: }
1.34      ng       1134: 
1.44      ng       1135: #------------------------------------------------------------------------------------
                   1136: #
                   1137: #-------------------------- Next few routines handles grading by student, essentially
                   1138: #                           handles essay response type problem/part
                   1139: #
                   1140: #--- Javascript to handle the submission page functionality ---
                   1141: sub sub_page_js {
                   1142:     my $request = shift;
                   1143:     $request->print(<<SUBJAVASCRIPT);
                   1144: <script type="text/javascript" language="javascript">
1.71      ng       1145:     function updateRadio(formname,id,weight) {
1.125     ng       1146: 	var gradeBox = formname["GD_BOX"+id];
                   1147: 	var radioButton = formname["RADVAL"+id];
                   1148: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1149: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1150: 	gradeBox.value = pts;
                   1151: 	var resetbox = false;
                   1152: 	if (isNaN(pts) || pts < 0) {
                   1153: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1154: 	    for (var i=0; i<radioButton.length; i++) {
                   1155: 		if (radioButton[i].checked) {
                   1156: 		    gradeBox.value = i;
                   1157: 		    resetbox = true;
                   1158: 		}
                   1159: 	    }
                   1160: 	    if (!resetbox) {
                   1161: 		formtextbox.value = "";
                   1162: 	    }
                   1163: 	    return;
1.44      ng       1164: 	}
1.71      ng       1165: 
                   1166: 	if (pts > weight) {
                   1167: 	    var resp = confirm("You entered a value ("+pts+
                   1168: 			       ") greater than the weight for the part. Accept?");
                   1169: 	    if (resp == false) {
1.125     ng       1170: 		gradeBox.value = oldpts;
1.71      ng       1171: 		return;
                   1172: 	    }
1.44      ng       1173: 	}
1.13      albertel 1174: 
1.71      ng       1175: 	for (var i=0; i<radioButton.length; i++) {
                   1176: 	    radioButton[i].checked=false;
                   1177: 	    if (pts == i && pts != "") {
                   1178: 		radioButton[i].checked=true;
                   1179: 	    }
                   1180: 	}
                   1181: 	updateSelect(formname,id);
1.125     ng       1182: 	formname["stores"+id].value = "0";
1.41      ng       1183:     }
1.5       albertel 1184: 
1.72      ng       1185:     function writeBox(formname,id,pts) {
1.125     ng       1186: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1187: 	if (checkSolved(formname,id) == 'update') {
                   1188: 	    gradeBox.value = pts;
                   1189: 	} else {
1.125     ng       1190: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1191: 	    gradeBox.value = oldpts;
1.125     ng       1192: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1193: 	    for (var i=0; i<radioButton.length; i++) {
                   1194: 		radioButton[i].checked=false;
1.72      ng       1195: 		if (i == oldpts) {
1.71      ng       1196: 		    radioButton[i].checked=true;
                   1197: 		}
                   1198: 	    }
1.41      ng       1199: 	}
1.125     ng       1200: 	formname["stores"+id].value = "0";
1.71      ng       1201: 	updateSelect(formname,id);
                   1202: 	return;
1.41      ng       1203:     }
1.44      ng       1204: 
1.71      ng       1205:     function clearRadBox(formname,id) {
                   1206: 	if (checkSolved(formname,id) == 'noupdate') {
                   1207: 	    updateSelect(formname,id);
                   1208: 	    return;
                   1209: 	}
1.125     ng       1210: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1211: 	for (var i=0; i<gradeSelect.length; i++) {
                   1212: 	    if (gradeSelect[i].selected) {
                   1213: 		var selectx=i;
                   1214: 	    }
                   1215: 	}
1.125     ng       1216: 	var stores = formname["stores"+id];
1.71      ng       1217: 	if (selectx == stores.value) { return };
1.125     ng       1218: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1219: 	gradeBox.value = "";
1.125     ng       1220: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1221: 	for (var i=0; i<radioButton.length; i++) {
                   1222: 	    radioButton[i].checked=false;
                   1223: 	}
                   1224: 	stores.value = selectx;
                   1225:     }
1.5       albertel 1226: 
1.71      ng       1227:     function checkSolved(formname,id) {
1.125     ng       1228: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1229: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1230: 	    if (!reply) {return "noupdate";}
1.120     ng       1231: 	    formname.overRideScore.value = 'yes';
1.41      ng       1232: 	}
1.71      ng       1233: 	return "update";
1.13      albertel 1234:     }
1.71      ng       1235: 
                   1236:     function updateSelect(formname,id) {
1.125     ng       1237: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1238: 	return;
1.41      ng       1239:     }
1.33      ng       1240: 
1.121     ng       1241: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1242:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1243: 	formname.gradeOpt.value = val;
1.71      ng       1244: 	if (val == "Save & Next") {
                   1245: 	    for (i=0;i<=total;i++) {
                   1246: 		for (j=0;j<parttot;j++) {
1.125     ng       1247: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1248: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1249: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1250: 			if (points == "") {
1.125     ng       1251: 			    var name = formname["name"+i].value;
1.129     ng       1252: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1253: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1254: 					       ", part "+partid+". Continue?");
1.71      ng       1255: 			    if (resp == false) {
1.125     ng       1256: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1257: 				return false;
                   1258: 			    }
                   1259: 			}
                   1260: 		    }
                   1261: 		    
                   1262: 		}
                   1263: 	    }
                   1264: 	    
                   1265: 	}
1.121     ng       1266: 	if (val == "Grade Student") {
                   1267: 	    formname.showgrading.value = "yes";
                   1268: 	    if (formname.Status.value == "") {
                   1269: 		formname.Status.value = "Active";
                   1270: 	    }
                   1271: 	    formname.studentNo.value = total;
                   1272: 	}
1.120     ng       1273: 	formname.submit();
                   1274:     }
                   1275: 
1.71      ng       1276: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1277:     function checkSubmitPage(formname,total) {
                   1278: 	noscore = new Array(100);
                   1279: 	var ptr = 0;
                   1280: 	for (i=1;i<total;i++) {
1.125     ng       1281: 	    var partid = formname["q_"+i].value;
1.127     ng       1282: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1283: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1284: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1285: 		if (points == "" && status != "correct_by_student") {
                   1286: 		    noscore[ptr] = i;
                   1287: 		    ptr++;
                   1288: 		}
                   1289: 	    }
                   1290: 	}
                   1291: 	if (ptr != 0) {
                   1292: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1293: 	    var prolist = "";
                   1294: 	    if (ptr == 1) {
                   1295: 		prolist = noscore[0];
                   1296: 	    } else {
                   1297: 		var i = 0;
                   1298: 		while (i < ptr-1) {
                   1299: 		    prolist += noscore[i]+", ";
                   1300: 		    i++;
                   1301: 		}
                   1302: 		prolist += "and "+noscore[i];
                   1303: 	    }
                   1304: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1305: 	    if (resp == false) {
                   1306: 		return false;
                   1307: 	    }
                   1308: 	}
1.45      ng       1309: 
1.71      ng       1310: 	formname.submit();
                   1311:     }
                   1312: </script>
                   1313: SUBJAVASCRIPT
                   1314: }
1.45      ng       1315: 
1.71      ng       1316: #--- javascript for essay type problem --
                   1317: sub sub_page_kw_js {
                   1318:     my $request = shift;
1.80      ng       1319:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1320:     &commonJSfunctions($request);
1.350     albertel 1321: 
1.351     albertel 1322:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1323:     <script text="text/javascript">
                   1324:     function checkInput() {
                   1325:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1326:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1327:       var usrctr = document.msgcenter.usrctr.value;
                   1328:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1329:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1330: 
                   1331:       var msgchk = "";
                   1332:       if (document.msgcenter.subchk.checked) {
                   1333:          msgchk = "msgsub,";
                   1334:       }
                   1335:       var includemsg = 0;
                   1336:       for (var i=1; i<=nmsg; i++) {
                   1337:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1338:           var frmmsg = document.msgcenter["msg"+i];
                   1339:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1340:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1341:           showflg.value = "1";
                   1342:           var chkbox = document.msgcenter["msgn"+i];
                   1343:           if (chkbox.checked) {
                   1344:              msgchk += "savemsg"+i+",";
                   1345:              includemsg = 1;
                   1346:           }
                   1347:       }
                   1348:       if (document.msgcenter.newmsgchk.checked) {
                   1349:          msgchk += "newmsg"+usrctr;
                   1350:          includemsg = 1;
                   1351:       }
                   1352:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1353:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1354:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1355:       includemsg.value = msgchk;
                   1356: 
                   1357:       self.close()
                   1358: 
                   1359:     }
                   1360:     </script>
                   1361: INNERJS
                   1362: 
1.351     albertel 1363:     my $inner_js_highlight_central=<<INNERJS;
                   1364:  <script type="text/javascript">
                   1365:     function updateChoice(flag) {
                   1366:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1367:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1368:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1369:       opener.document.SCORE.refresh.value = "on";
                   1370:       if (opener.document.SCORE.keywords.value!=""){
                   1371:          opener.document.SCORE.submit();
                   1372:       }
                   1373:       self.close()
                   1374:     }
                   1375: </script>
                   1376: INNERJS
                   1377: 
                   1378:     my $start_page_msg_central = 
                   1379:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1380: 				       {'js_ready'  => 1,
                   1381: 					'only_body' => 1,
                   1382: 					'bgcolor'   =>'#FFFFFF',});
                   1383:     my $end_page_msg_central = 
                   1384: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1385: 
                   1386: 
                   1387:     my $start_page_highlight_central = 
                   1388:         &Apache::loncommon::start_page('Highlight Central',
                   1389: 				       $inner_js_highlight_central,
1.350     albertel 1390: 				       {'js_ready'  => 1,
                   1391: 					'only_body' => 1,
                   1392: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1393:     my $end_page_highlight_central = 
1.350     albertel 1394: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1395: 
1.219     www      1396:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1397:     $docopen=~s/^document\.//;
1.71      ng       1398:     $request->print(<<SUBJAVASCRIPT);
                   1399: <script type="text/javascript" language="javascript">
1.45      ng       1400: 
1.44      ng       1401: //===================== Show list of keywords ====================
1.122     ng       1402:   function keywords(formname) {
                   1403:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1404:     if (nret==null) return;
1.122     ng       1405:     formname.keywords.value = nret;
1.44      ng       1406: 
1.122     ng       1407:     if (formname.keywords.value != "") {
1.128     ng       1408: 	formname.refresh.value = "on";
1.122     ng       1409: 	formname.submit();
1.44      ng       1410:     }
                   1411:     return;
                   1412:   }
                   1413: 
                   1414: //===================== Script to view submitted by ==================
                   1415:   function viewSubmitter(submitter) {
                   1416:     document.SCORE.refresh.value = "on";
                   1417:     document.SCORE.NCT.value = "1";
                   1418:     document.SCORE.unamedom0.value = submitter;
                   1419:     document.SCORE.submit();
                   1420:     return;
                   1421:   }
                   1422: 
                   1423: //===================== Script to add keyword(s) ==================
                   1424:   function getSel() {
                   1425:     if (document.getSelection) txt = document.getSelection();
                   1426:     else if (document.selection) txt = document.selection.createRange().text;
                   1427:     else return;
                   1428:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1429:     if (cleantxt=="") {
1.46      ng       1430: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1431: 	return;
                   1432:     }
                   1433:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1434:     if (nret==null) return;
1.127     ng       1435:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1436:     if (document.SCORE.keywords.value != "") {
1.127     ng       1437: 	document.SCORE.refresh.value = "on";
1.44      ng       1438: 	document.SCORE.submit();
                   1439:     }
                   1440:     return;
                   1441:   }
                   1442: 
                   1443: //====================== Script for composing message ==============
1.80      ng       1444:    // preload images
                   1445:    img1 = new Image();
                   1446:    img1.src = "$iconpath/mailbkgrd.gif";
                   1447:    img2 = new Image();
                   1448:    img2.src = "$iconpath/mailto.gif";
                   1449: 
1.44      ng       1450:   function msgCenter(msgform,usrctr,fullname) {
                   1451:     var Nmsg  = msgform.savemsgN.value;
                   1452:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1453:     var subject = msgform.msgsub.value;
1.127     ng       1454:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1455:     re = /msgsub/;
                   1456:     var shwsel = "";
                   1457:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1458:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1459:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1460:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1461: 	var testmsg = "savemsg"+i+",";
                   1462: 	re = new RegExp(testmsg,"g");
1.44      ng       1463: 	shwsel = "";
                   1464: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1465: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1466: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1467: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1468: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1469:     }
1.125     ng       1470:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1471:     shwsel = "";
                   1472:     re = /newmsg/;
                   1473:     if (re.test(msgchk)) { shwsel = "checked" }
                   1474:     newMsg(newmsg,shwsel);
                   1475:     msgTail(); 
                   1476:     return;
                   1477:   }
                   1478: 
1.123     ng       1479:   function checkEntities(strx) {
                   1480:     if (strx.length == 0) return strx;
                   1481:     var orgStr = ["&", "<", ">", '"']; 
                   1482:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1483:     var counter = 0;
                   1484:     while (counter < 4) {
                   1485: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1486: 	counter++;
                   1487:     }
                   1488:     return strx;
                   1489:   }
                   1490: 
                   1491:   function strReplace(strx, orgStr, newStr) {
                   1492:     return strx.split(orgStr).join(newStr);
                   1493:   }
                   1494: 
1.44      ng       1495:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1496:     var height = 70*Nmsg+250;
1.44      ng       1497:     var scrollbar = "no";
                   1498:     if (height > 600) {
                   1499: 	height = 600;
                   1500: 	scrollbar = "yes";
                   1501:     }
1.118     ng       1502:     var xpos = (screen.width-600)/2;
                   1503:     xpos = (xpos < 0) ? '0' : xpos;
                   1504:     var ypos = (screen.height-height)/2-30;
                   1505:     ypos = (ypos < 0) ? '0' : ypos;
                   1506: 
1.206     albertel 1507:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1508:     pWin.focus();
                   1509:     pDoc = pWin.document;
1.219     www      1510:     pDoc.$docopen;
1.351     albertel 1511:     pDoc.write('$start_page_msg_central');
1.76      ng       1512: 
                   1513:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1514:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1515:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1516: 
                   1517:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1518:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1519:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1520: }
                   1521:     function displaySubject(msg,shwsel) {
1.76      ng       1522:     pDoc = pWin.document;
                   1523:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1524:     pDoc.write("<td>Subject<\\/td>");
                   1525:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1526:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1527: }
                   1528: 
1.72      ng       1529:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1530:     pDoc = pWin.document;
                   1531:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1532:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1533:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1534:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1535: }
                   1536: 
                   1537:   function newMsg(newmsg,shwsel) {
1.76      ng       1538:     pDoc = pWin.document;
                   1539:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1540:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1541:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1542:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1543: }
                   1544: 
                   1545:   function msgTail() {
1.76      ng       1546:     pDoc = pWin.document;
1.465     albertel 1547:     pDoc.write("<\\/table>");
                   1548:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1549:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1550:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1551:     pDoc.write("<\\/form>");
1.351     albertel 1552:     pDoc.write('$end_page_msg_central');
1.128     ng       1553:     pDoc.close();
1.44      ng       1554: }
                   1555: 
                   1556: //====================== Script for keyword highlight options ==============
                   1557:   function kwhighlight() {
                   1558:     var kwclr    = document.SCORE.kwclr.value;
                   1559:     var kwsize   = document.SCORE.kwsize.value;
                   1560:     var kwstyle  = document.SCORE.kwstyle.value;
                   1561:     var redsel = "";
                   1562:     var grnsel = "";
                   1563:     var blusel = "";
                   1564:     if (kwclr=="red")   {var redsel="checked"};
                   1565:     if (kwclr=="green") {var grnsel="checked"};
                   1566:     if (kwclr=="blue")  {var blusel="checked"};
                   1567:     var sznsel = "";
                   1568:     var sz1sel = "";
                   1569:     var sz2sel = "";
                   1570:     if (kwsize=="0")  {var sznsel="checked"};
                   1571:     if (kwsize=="+1") {var sz1sel="checked"};
                   1572:     if (kwsize=="+2") {var sz2sel="checked"};
                   1573:     var synsel = "";
                   1574:     var syisel = "";
                   1575:     var sybsel = "";
                   1576:     if (kwstyle=="")    {var synsel="checked"};
                   1577:     if (kwstyle=="<i>") {var syisel="checked"};
                   1578:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1579:     highlightCentral();
                   1580:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1581:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1582:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1583:     highlightend();
                   1584:     return;
                   1585:   }
                   1586: 
                   1587:   function highlightCentral() {
1.76      ng       1588: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1589:     var xpos = (screen.width-400)/2;
                   1590:     xpos = (xpos < 0) ? '0' : xpos;
                   1591:     var ypos = (screen.height-330)/2-30;
                   1592:     ypos = (ypos < 0) ? '0' : ypos;
                   1593: 
1.206     albertel 1594:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1595:     hwdWin.focus();
                   1596:     var hDoc = hwdWin.document;
1.219     www      1597:     hDoc.$docopen;
1.351     albertel 1598:     hDoc.write('$start_page_highlight_central');
1.76      ng       1599:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1600:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1601: 
                   1602:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1603:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1604:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1605:   }
                   1606: 
                   1607:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1608:     var hDoc = hwdWin.document;
                   1609:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1610:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1611:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1612:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1613:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1614:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1615:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1616:     hDoc.write("<\\/tr>");
1.44      ng       1617:   }
                   1618: 
                   1619:   function highlightend() { 
1.76      ng       1620:     var hDoc = hwdWin.document;
1.465     albertel 1621:     hDoc.write("<\\/table>");
                   1622:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1623:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1624:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1625:     hDoc.write("<\\/form>");
1.351     albertel 1626:     hDoc.write('$end_page_highlight_central');
1.128     ng       1627:     hDoc.close();
1.44      ng       1628:   }
                   1629: 
                   1630: </script>
                   1631: SUBJAVASCRIPT
                   1632: }
                   1633: 
1.349     albertel 1634: sub get_increment {
1.348     bowersj2 1635:     my $increment = $env{'form.increment'};
                   1636:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1637:         $increment != .1) {
                   1638:         $increment = 1;
                   1639:     }
                   1640:     return $increment;
                   1641: }
                   1642: 
1.71      ng       1643: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1644: sub gradeBox {
1.322     albertel 1645:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1646:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485   ! albertel 1647: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1648:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1649:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1650:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1651:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1652:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1653: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1654:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1655:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1656:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1657: 				       [$partid]);
                   1658:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1659:     if ($last_resets{$partid}) {
                   1660:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1661:     }
1.485   ! albertel 1662:     $result.='<table border="0"><tr>';
1.71      ng       1663:     my $ctr = 0;
1.348     bowersj2 1664:     my $thisweight = 0;
1.349     albertel 1665:     my $increment = &get_increment();
1.485   ! albertel 1666: 
        !          1667:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1668:     while ($thisweight<=$wgt) {
1.485   ! albertel 1669: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1670: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1671: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1672: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485   ! albertel 1673: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1674:         $thisweight += $increment;
1.71      ng       1675: 	$ctr++;
                   1676:     }
1.485   ! albertel 1677:     $radio.='</tr></table>';
        !          1678: 
        !          1679:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1680: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1681: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1682: 	$wgt.')" /></td>'."\n";
1.485   ! albertel 1683:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1684: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1685: 	' </td><td>'."\n";
1.485   ! albertel 1686:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1687: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1688:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485   ! albertel 1689: 	$line.='<option></option>'.
        !          1690: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1691:     } else {
1.485   ! albertel 1692: 	$line.='<option selected="selected"></option>'.
        !          1693: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1694:     }
1.485   ! albertel 1695:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
        !          1696: 
        !          1697: 
        !          1698:     $result .= 
        !          1699: 	&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);
        !          1700: 
        !          1701:     
        !          1702:     $result.='</tr></table>'."\n";
1.71      ng       1703:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1704: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1705: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1706: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1707:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1708:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1709:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1710:         $aggtries.'" />'."\n";
1.323     banghart 1711:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1712:     return $result;
                   1713: }
1.322     albertel 1714: 
                   1715: sub handback_box {
1.323     banghart 1716:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1717:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1718:     my (@respids);
1.375     albertel 1719:      my @part_response_id = &flatten_responseType($responseType);
                   1720:     foreach my $part_response_id (@part_response_id) {
                   1721:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1722:         if ($part eq $partid) {
1.375     albertel 1723:             push(@respids,$resp);
1.323     banghart 1724:         }
                   1725:     }
1.318     banghart 1726:     my $result;
1.323     banghart 1727:     foreach my $respid (@respids) {
1.322     albertel 1728: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1729: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1730: 	next if (!@$files);
                   1731: 	my $file_counter = 1;
1.313     banghart 1732: 	foreach my $file (@$files) {
1.368     banghart 1733: 	    if ($file =~ /\/portfolio\//) {
                   1734:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1735:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1736:     	        $file_disp = "$name.$ext";
                   1737:     	        $file = $file_path.$file_disp;
                   1738:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1739:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1740:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1741:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485   ! albertel 1742:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1743:     	        $file_counter++;
                   1744: 	    }
1.322     albertel 1745: 	}
1.313     banghart 1746:     }
1.318     banghart 1747:     return $result;    
1.71      ng       1748: }
1.44      ng       1749: 
1.58      albertel 1750: sub show_problem {
1.382     albertel 1751:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1752:     my $rendered;
1.382     albertel 1753:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1754:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1755:     if ($mode eq 'both' or $mode eq 'text') {
                   1756: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1757: 						       $env{'request.course.id'},
                   1758: 						       undef,\%form);
1.144     albertel 1759:     }
1.58      albertel 1760:     if ($removeform) {
                   1761: 	$rendered=~s|<form(.*?)>||g;
                   1762: 	$rendered=~s|</form>||g;
1.374     albertel 1763: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1764:     }
1.144     albertel 1765:     my $companswer;
                   1766:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1767: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1768: 	$companswer=
                   1769: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1770: 						    $env{'request.course.id'},
                   1771: 						    %form);
1.144     albertel 1772:     }
1.58      albertel 1773:     if ($removeform) {
                   1774: 	$companswer=~s|<form(.*?)>||g;
                   1775: 	$companswer=~s|</form>||g;
1.144     albertel 1776: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1777:     }
1.468     albertel 1778:     $rendered=
                   1779: 	'<div class="LC_grade_show_problem_header">'.
                   1780: 	&mt('View of the problem').
                   1781: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1782: 	$rendered.
                   1783: 	'</div>';
                   1784:     $companswer=
                   1785: 	'<div class="LC_grade_show_problem_header">'.
                   1786: 	&mt('Correct answer').
                   1787: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1788: 	$companswer.
                   1789: 	'</div>';
                   1790:     my $result;
1.144     albertel 1791:     if ($mode eq 'both') {
1.468     albertel 1792: 	$result=$rendered.$companswer;
1.144     albertel 1793:     } elsif ($mode eq 'text') {
1.468     albertel 1794: 	$result=$rendered;
1.144     albertel 1795:     } elsif ($mode eq 'answer') {
1.468     albertel 1796: 	$result=$companswer;
1.144     albertel 1797:     }
1.468     albertel 1798:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1799:     return $result;
1.58      albertel 1800: }
1.397     albertel 1801: 
1.396     banghart 1802: sub files_exist {
                   1803:     my ($r, $symb) = @_;
                   1804:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1805: 
1.396     banghart 1806:     foreach my $student (@students) {
                   1807:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1808:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1809: 					      $udom,$uname);
1.396     banghart 1810:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1811:         foreach my $submission (@$string) {
                   1812:             my ($partid,$respid) =
                   1813: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1814:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1815: 					   \%record);
                   1816:             return 1 if (@$files);
1.396     banghart 1817:         }
                   1818:     }
1.397     albertel 1819:     return 0;
1.396     banghart 1820: }
1.397     albertel 1821: 
1.394     banghart 1822: sub download_all_link {
                   1823:     my ($r,$symb) = @_;
1.395     albertel 1824:     my $all_students = 
                   1825: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1826: 
                   1827:     my $parts =
                   1828: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1829: 
1.394     banghart 1830:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1831:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1832:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1833:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1834:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1835: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1836:     return
                   1837: }
1.395     albertel 1838: 
1.432     banghart 1839: sub build_section_inputs {
                   1840:     my $section_inputs;
                   1841:     if ($env{'form.section'} eq '') {
                   1842:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1843:     } else {
                   1844:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1845:         foreach my $section (@sections) {
1.432     banghart 1846:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1847:         }
                   1848:     }
                   1849:     return $section_inputs;
                   1850: }
                   1851: 
1.44      ng       1852: # --------------------------- show submissions of a student, option to grade 
                   1853: sub submission {
                   1854:     my ($request,$counter,$total) = @_;
1.257     albertel 1855:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1856:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1857:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1858:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1859:     my $symb = &get_symb($request); 
                   1860:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1861: 
                   1862:     if (!&canview($usec)) {
1.398     albertel 1863: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1864: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1865: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1866: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1867: 	return;
                   1868:     }
                   1869: 
1.257     albertel 1870:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1871:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1872:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1873:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1874:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1875: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1876: 	'/check.gif" height="16" border="0" />';
1.41      ng       1877: 
1.426     albertel 1878:     my %old_essays;
1.41      ng       1879:     # header info
                   1880:     if ($counter == 0) {
                   1881: 	&sub_page_js($request);
1.257     albertel 1882: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1883: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1884: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1885: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1886: 	    &download_all_link($request, $symb);
                   1887: 	}
1.485   ! albertel 1888: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
        !          1889: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1890: 
1.44      ng       1891: 	# option to display problem, only once else it cause problems 
                   1892:         # with the form later since the problem has a form.
1.257     albertel 1893: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1894: 	    my $mode;
1.257     albertel 1895: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1896: 		$mode='both';
1.257     albertel 1897: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1898: 		$mode='text';
1.257     albertel 1899: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1900: 		$mode='answer';
                   1901: 	    }
1.329     albertel 1902: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1903: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1904: 	}
1.441     www      1905: 
1.44      ng       1906: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1907:         # if this subroutine has been called once.
1.41      ng       1908: 	my %keyhash = ();
1.257     albertel 1909: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1910: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1911: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1912: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1913: 
1.257     albertel 1914: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1915: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1916: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1917: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1918: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1919: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1920: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1921: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1922: 	}
1.257     albertel 1923: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1924: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1925: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1926: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1927: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1928: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1929: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1930: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1931: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1932: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1933: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1934: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1935: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1936: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1937: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1938: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1939: 			&build_section_inputs().
1.326     albertel 1940: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1941: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1942: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1943: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1944: 	if ($env{'form.handgrade'} eq 'yes') {
                   1945: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1946: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1947: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1948: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1949: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1950: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1951: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1952: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1953: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1954: 	    }
1.123     ng       1955: 	}
1.41      ng       1956: 	
                   1957: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1958: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1959: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1960: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1961: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1962: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1963: 		'" />'."\n".
                   1964: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1965: 	    $cts++;
                   1966: 	}
                   1967: 	$request->print($prnmsg);
1.32      ng       1968: 
1.257     albertel 1969: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1970: #
                   1971: # Print out the keyword options line
                   1972: #
1.41      ng       1973: 	    $request->print(<<KEYWORDS);
1.38      ng       1974: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1975: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1976: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1977:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1978: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1979: KEYWORDS
1.88      www      1980: #
                   1981: # Load the other essays for similarity check
                   1982: #
1.324     albertel 1983:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1984: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1985: 	    $apath=&escape($apath);
1.88      www      1986: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1987: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1988:         }
                   1989:     }
1.44      ng       1990: 
1.441     www      1991: # This is where output for one specific student would start
1.468     albertel 1992:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      1993:     $request->print("\n\n".
1.468     albertel 1994:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   1995: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   1996: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      1997: 
1.257     albertel 1998:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1999: 	my $mode;
1.257     albertel 2000: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2001: 	    $mode='both';
1.257     albertel 2002: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2003: 	    $mode='text';
1.257     albertel 2004: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2005: 	    $mode='answer';
                   2006: 	}
1.329     albertel 2007: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2008: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2009:     }
1.144     albertel 2010: 
1.257     albertel 2011:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2012:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2013: 
1.44      ng       2014:     # Display student info
1.41      ng       2015:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2016:     my $result='<div class="LC_grade_submissions">';
                   2017:     
                   2018:     $result.='<div class="LC_grade_submissions_header">';
                   2019:     $result.= &mt('Submissions');
1.45      ng       2020:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2021: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2022:     if ($env{'form.handgrade'} eq 'no') {
                   2023: 	$result.='<span class="LC_grade_check_note">'.
                   2024: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2025: 
                   2026:     }
                   2027: 
                   2028: 
1.41      ng       2029: 
1.118     ng       2030:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2031:     my $fullname;
                   2032:     my $col_fullnames = [];
1.257     albertel 2033:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2034: 	(my $sub_result,$fullname,$col_fullnames)=
                   2035: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2036: 				 $counter);
                   2037: 	$result.=$sub_result;
1.41      ng       2038:     }
1.44      ng       2039:     $request->print($result."\n");
1.468     albertel 2040:     $request->print('</div>'."\n");
1.44      ng       2041:     # print student answer/submission
                   2042:     # Options are (1) Handgaded submission only
                   2043:     #             (2) Last submission, includes submission that is not handgraded 
                   2044:     #                  (for multi-response type part)
                   2045:     #             (3) Last submission plus the parts info
                   2046:     #             (4) The whole record for this student
1.257     albertel 2047:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2048: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2049: 	
                   2050: 	my $lastsubonly;
                   2051: 
1.151     albertel 2052: 	if ($$timestamp eq '') {
1.468     albertel 2053: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2054: 	} else {
1.468     albertel 2055: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2056: 
1.151     albertel 2057: 	    my %seenparts;
1.375     albertel 2058: 	    my @part_response_id = &flatten_responseType($responseType);
                   2059: 	    foreach my $part (@part_response_id) {
1.393     albertel 2060: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2061: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2062: 
1.375     albertel 2063: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2064: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2065: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2066: 		    if (exists($seenparts{$partid})) { next; }
                   2067: 		    $seenparts{$partid}=1;
1.207     albertel 2068: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2069: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2070: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2071: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2072: 			'\');" target="_self">'.
1.257     albertel 2073: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2074: 		    $request->print($submitby);
                   2075: 		    next;
                   2076: 		}
                   2077: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2078: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2079: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2080: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2081: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2082: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2083: 		    next;
                   2084: 		}
1.468     albertel 2085: 		foreach my $submission (@$string) {
                   2086: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2087: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2088: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2089: 		    # Similarity check
                   2090: 		    my $similar='';
1.257     albertel 2091: 		    if($env{'form.checkPlag'}){
1.151     albertel 2092: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2093: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2094: 			if ($osim) {
                   2095: 			    $osim=int($osim*100.0);
1.426     albertel 2096: 			    my %old_course_desc = 
                   2097: 				&Apache::lonnet::coursedescription($ocrsid,
                   2098: 								   {'one_time' => 1});
                   2099: 
                   2100: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2101: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2102: 				    $osim,
                   2103: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2104: 				    $oname,$odom,
1.426     albertel 2105: 				    $old_course_desc{'description'},
1.427     albertel 2106: 				    $old_course_desc{'num'},
1.426     albertel 2107: 				    $old_course_desc{'domain'}).
1.398     albertel 2108: 				'</span></h3><blockquote><i>'.
1.151     albertel 2109: 				&keywords_highlight($oessay).
                   2110: 				'</i></blockquote><hr />';
                   2111: 			}
1.150     albertel 2112: 		    }
1.151     albertel 2113: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2114: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2115: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2116: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2117: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2118: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2119: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2120: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2121: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2122: 			if (@$files) {
1.468     albertel 2123: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2124: 			    my $file_counter = 0;
1.313     banghart 2125: 			    foreach my $file (@$files) {
1.468     albertel 2126: 			        $file_counter++;
1.232     albertel 2127: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2128: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2129: 			    }
1.236     albertel 2130: 			    $lastsubonly.='<br />';
1.41      ng       2131: 			}
1.468     albertel 2132: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2133: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2134: 					 $respid,\%record,$order);
                   2135: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2136: 			$lastsubonly.='</div>';
1.41      ng       2137: 		    }
                   2138: 		}
                   2139: 	    }
1.468     albertel 2140: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2141: 	}
                   2142: 	$request->print($lastsubonly);
1.468     albertel 2143:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2144: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2145: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2146:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2147: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2148: 								 $env{'request.course.id'},
1.44      ng       2149: 								 $last,'.submission',
                   2150: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2151:     }
1.120     ng       2152: 
1.121     ng       2153:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2154: 	.$udom.'" />'."\n");
1.44      ng       2155:     # return if view submission with no grading option
1.257     albertel 2156:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2157: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2158: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2159: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2160: 	$toGrade.='</div>'."\n";
1.257     albertel 2161: 	if (($env{'form.command'} eq 'submission') || 
                   2162: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2163: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2164: 	}
1.180     albertel 2165: 	$request->print($toGrade);
1.41      ng       2166: 	return;
1.180     albertel 2167:     } else {
1.468     albertel 2168: 	$request->print('</div>'."\n");
1.41      ng       2169:     }
1.33      ng       2170: 
1.121     ng       2171:     # essay grading message center
1.257     albertel 2172:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2173: 	my $result='<div class="LC_grade_message_center">';
                   2174:     
                   2175: 	$result.='<div class="LC_grade_message_center_header">'.
                   2176: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2177: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2178: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2179: 	if (scalar(@$col_fullnames) > 0) {
                   2180: 	    my $lastone = pop(@$col_fullnames);
                   2181: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2182: 	}
                   2183: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2184: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2185: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2186: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2187: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2188: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2189: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2190: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2191: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2192: 	    '<br />&nbsp;('.
1.468     albertel 2193: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2194: 	$result.='</div></div>';
1.121     ng       2195: 	$request->print($result);
1.118     ng       2196:     }
1.41      ng       2197: 
                   2198:     my %seen = ();
                   2199:     my @partlist;
1.129     ng       2200:     my @gradePartRespid;
1.375     albertel 2201:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2202:     $request->print('<div class="LC_grade_assign">'.
                   2203: 		    
                   2204: 		    '<div class="LC_grade_assign_header">'.
                   2205: 		    &mt('Assign Grades').'</div>'.
                   2206: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2207:     foreach my $part_response_id (@part_response_id) {
                   2208:     	my ($partid,$respid) = @{ $part_response_id };
                   2209: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2210: 	next if ($seen{$partid} > 0);
1.41      ng       2211: 	$seen{$partid}++;
1.393     albertel 2212: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2213: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2214: 	push @partlist,$partid;
1.129     ng       2215: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2216: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2217:     }
1.468     albertel 2218:     $request->print('</div></div>');
                   2219: 
                   2220:     $request->print('<div class="LC_grade_info_links">');
                   2221:     if ($perm{'vgr'}) {
                   2222: 	$request->print(
                   2223: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2224: 						   $uname,$udom,'check'));
                   2225:     }
                   2226:     if ($perm{'opa'}) {
                   2227: 	$request->print(
                   2228: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2229: 					 $uname,$udom,$symb,'check'));
                   2230:     }
                   2231:     $request->print('</div>');
                   2232: 
1.45      ng       2233:     $result='<input type="hidden" name="partlist'.$counter.
                   2234: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2235:     $result.='<input type="hidden" name="gradePartRespid'.
                   2236: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2237:     my $ctr = 0;
                   2238:     while ($ctr < scalar(@partlist)) {
                   2239: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2240: 	    $partlist[$ctr].'" />'."\n";
                   2241: 	$ctr++;
                   2242:     }
1.468     albertel 2243:     $request->print($result.''."\n");
1.41      ng       2244: 
1.441     www      2245: # Done with printing info for one student
                   2246: 
1.468     albertel 2247:     $request->print('</div>');#LC_grade_show_user_body
                   2248:     $request->print('</div>');#LC_grade_show_user
1.441     www      2249: 
                   2250: 
1.41      ng       2251:     # print end of form
                   2252:     if ($counter == $total) {
1.297     www      2253: 	my $endform='<table border="0"><tr><td>'."\n";
1.485   ! albertel 2254: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2255: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2256: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2257: 	my $ntstu ='<select name="NTSTU">'.
                   2258: 	    '<option>1</option><option>2</option>'.
                   2259: 	    '<option>3</option><option>5</option>'.
                   2260: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2261: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2262: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485   ! albertel 2263: 	$endform.=&mt('[_1]student(s)',$ntstu);
        !          2264: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2265: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485   ! albertel 2266: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2267: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485   ! albertel 2268: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2269:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2270:             "' name='increment' />";
1.485   ! albertel 2271: 	$endform.='</td></tr></table></form>';
1.324     albertel 2272: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2273: 	$request->print($endform);
                   2274:     }
                   2275:     return '';
1.38      ng       2276: }
                   2277: 
1.464     albertel 2278: sub check_collaborators {
                   2279:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2280:     my ($result,@col_fullnames);
                   2281:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2282:     foreach my $part (keys(%$handgrade)) {
                   2283: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2284: 					'.maxcollaborators',
                   2285: 					$symb,$udom,$uname);
                   2286: 	next if ($ncol <= 0);
                   2287: 	$part =~ s/\_/\./g;
                   2288: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2289: 	my (@good_collaborators, @bad_collaborators);
                   2290: 	foreach my $possible_collaborator
                   2291: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2292: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2293: 	    next if ($possible_collaborator eq '');
                   2294: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2295: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2296: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2297: 	    # Doing this grep allows 'fuzzy' specification
                   2298: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2299: 			       keys(%$classlist));
                   2300: 	    if (! scalar(@matches)) {
                   2301: 		push(@bad_collaborators, $possible_collaborator);
                   2302: 	    } else {
                   2303: 		push(@good_collaborators, @matches);
                   2304: 	    }
                   2305: 	}
                   2306: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2307: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2308: 	    foreach my $name (@good_collaborators) {
                   2309: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2310: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2311: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2312: 	    }
                   2313: 	    $result.='<br />'."\n";
1.466     albertel 2314: 	    my ($part)=split(/\./,$part);
1.464     albertel 2315: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2316: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2317: 		"\n";
                   2318: 	}
                   2319: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2320: 	    $result.='<div class="LC_warning">';
1.464     albertel 2321: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2322: 	    $result .= '</div>';
                   2323: 	}         
                   2324: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2325: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2326: 	    $result .= &mt('This student has submitted too many '.
                   2327: 		'collaborators.  Maximum is [_1].',$ncol);
                   2328: 	    $result .= '</div>';
                   2329: 	}
                   2330:     }
                   2331:     return ($result,$fullname,\@col_fullnames);
                   2332: }
                   2333: 
1.44      ng       2334: #--- Retrieve the last submission for all the parts
1.38      ng       2335: sub get_last_submission {
1.119     ng       2336:     my ($returnhash)=@_;
1.46      ng       2337:     my (@string,$timestamp);
1.119     ng       2338:     if ($$returnhash{'version'}) {
1.46      ng       2339: 	my %lasthash=();
                   2340: 	my ($version);
1.119     ng       2341: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2342: 	    foreach my $key (sort(split(/\:/,
                   2343: 					$$returnhash{$version.':keys'}))) {
                   2344: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2345: 		$timestamp = 
                   2346: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2347: 	    }
                   2348: 	}
1.397     albertel 2349: 	foreach my $key (keys(%lasthash)) {
                   2350: 	    next if ($key !~ /\.submission$/);
                   2351: 
                   2352: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2353: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2354: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2355: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2356: 	}
                   2357:     }
1.397     albertel 2358:     if (!@string) {
                   2359: 	$string[0] =
1.398     albertel 2360: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2361:     }
                   2362:     return (\@string,\$timestamp);
1.38      ng       2363: }
1.35      ng       2364: 
1.44      ng       2365: #--- High light keywords, with style choosen by user.
1.38      ng       2366: sub keywords_highlight {
1.44      ng       2367:     my $string    = shift;
1.257     albertel 2368:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2369:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2370:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2371:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2372:     foreach my $keyword (@keylist) {
                   2373: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2374:     }
                   2375:     return $string;
1.38      ng       2376: }
1.36      ng       2377: 
1.44      ng       2378: #--- Called from submission routine
1.38      ng       2379: sub processHandGrade {
1.41      ng       2380:     my ($request) = shift;
1.324     albertel 2381:     my $symb   = &get_symb($request);
                   2382:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2383:     my $button = $env{'form.gradeOpt'};
                   2384:     my $ngrade = $env{'form.NCT'};
                   2385:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2386:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2387:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2388: 
1.44      ng       2389:     if ($button eq 'Save & Next') {
                   2390: 	my $ctr = 0;
                   2391: 	while ($ctr < $ngrade) {
1.257     albertel 2392: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2393: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2394: 	    if ($errorflag eq 'no_score') {
                   2395: 		$ctr++;
                   2396: 		next;
                   2397: 	    }
1.104     albertel 2398: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2399: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2400: 		$ctr++;
                   2401: 		next;
                   2402: 	    }
1.257     albertel 2403: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2404: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2405: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2406:             my ($feedurl,$showsymb) =
                   2407: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2408: 	    my $messagetail;
1.62      albertel 2409: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2410: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2411: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2412: 		$subject.=' ['.$restitle.']';
1.44      ng       2413: 		my (@msgnum) = split(/,/,$includemsg);
                   2414: 		foreach (@msgnum) {
1.257     albertel 2415: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2416: 		}
1.80      ng       2417: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2418: 		if ($env{'form.withgrades'.$ctr}) {
                   2419: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2420: 		    $messagetail = " for <a href=\"".
1.418     albertel 2421: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2422: 		}
                   2423: 		$msgstatus = 
                   2424:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2425: 						     $message.$messagetail,
1.418     albertel 2426:                                                      undef,$feedurl,undef,
1.386     raeburn  2427:                                                      undef,undef,$showsymb,
                   2428:                                                      $restitle);
                   2429: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2430: 				$msgstatus);
1.44      ng       2431: 	    }
1.257     albertel 2432: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2433: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2434: 		foreach my $collabstr (@collabstrs) {
                   2435: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2436: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2437: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2438: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2439: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2440: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2441: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2442: 			    next;
1.418     albertel 2443: 			} elsif ($message ne '') {
                   2444: 			    my ($baseurl,$showsymb) = 
                   2445: 				&get_feedurl_and_symb($symb,$collaborator,
                   2446: 						      $udom);
                   2447: 			    if ($env{'form.withgrades'.$ctr}) {
                   2448: 				$messagetail = " for <a href=\"".
1.386     raeburn  2449:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2450: 			    }
1.418     albertel 2451: 			    $msgstatus = 
                   2452: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2453: 			}
1.44      ng       2454: 		    }
                   2455: 		}
                   2456: 	    }
                   2457: 	    $ctr++;
                   2458: 	}
                   2459:     }
                   2460: 
1.257     albertel 2461:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2462: 	# Keywords sorted in alphabatical order
1.257     albertel 2463: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2464: 	my %keyhash = ();
1.257     albertel 2465: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2466: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2467: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2468: 	$env{'form.keywords'} = join(' ',@keywords);
                   2469: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2470: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2471: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2472: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2473: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2474: 
                   2475: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2476: 	# New messages are saved in env for the next student.
1.119     ng       2477: 	# All messages are saved in nohist_handgrade.db
                   2478: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2479: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2480: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2481: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2482: 		$idx++;
                   2483: 	    }
                   2484: 	    $ctr++;
1.41      ng       2485: 	}
1.119     ng       2486: 	$ctr = 0;
                   2487: 	while ($ctr < $ngrade) {
1.257     albertel 2488: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2489: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2490: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2491: 		$idx++;
                   2492: 	    }
                   2493: 	    $ctr++;
1.41      ng       2494: 	}
1.257     albertel 2495: 	$env{'form.savemsgN'} = --$idx;
                   2496: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2497: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2498: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2499:     }
1.44      ng       2500:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2501:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2502:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2503: 	my ($ctr,$total) = (0,0);
                   2504: 	while ($ctr < $ngrade) {
1.257     albertel 2505: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2506: 	    $ctr++;
                   2507: 	}
1.257     albertel 2508: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2509: 	$ctr = 0;
                   2510: 	while ($ctr < $total) {
1.257     albertel 2511: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2512: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2513: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2514: 	    &submission($request,$ctr,$total-1);
1.41      ng       2515: 	    $ctr++;
                   2516: 	}
                   2517: 	return '';
                   2518:     }
1.36      ng       2519: 
1.121     ng       2520: # Go directly to grade student - from submission or link from chart page
1.120     ng       2521:     if ($button eq 'Grade Student') {
1.324     albertel 2522: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2523: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2524: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2525: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2526: 	&submission($request,0,0);
                   2527: 	return '';
                   2528:     }
                   2529: 
1.44      ng       2530:     # Get the next/previous one or group of students
1.257     albertel 2531:     my $firststu = $env{'form.unamedom0'};
                   2532:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2533:     my $ctr = 2;
1.41      ng       2534:     while ($laststu eq '') {
1.257     albertel 2535: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2536: 	$ctr++;
                   2537: 	$laststu = $firststu if ($ctr > $ngrade);
                   2538:     }
1.44      ng       2539: 
1.41      ng       2540:     my (@parsedlist,@nextlist);
                   2541:     my ($nextflg) = 0;
1.294     albertel 2542:     foreach (sort 
                   2543: 	     {
                   2544: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2545: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2546: 		 }
                   2547: 		 return $a cmp $b;
                   2548: 	     } (keys(%$fullname))) {
1.41      ng       2549: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2550: 	    push @parsedlist,$_;
                   2551: 	}
                   2552: 	$nextflg = 1 if ($_ eq $laststu);
                   2553: 	if ($button eq 'Previous') {
                   2554: 	    last if ($_ eq $firststu);
                   2555: 	    push @parsedlist,$_;
                   2556: 	}
                   2557:     }
                   2558:     $ctr = 0;
                   2559:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2560:     my ($partlist) = &response_type($symb);
1.41      ng       2561:     foreach my $student (@parsedlist) {
1.257     albertel 2562: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2563: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2564: 	
                   2565: 	if ($submitonly eq 'queued') {
                   2566: 	    my %queue_status = 
                   2567: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2568: 							$udom,$uname);
                   2569: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2570: 	}
                   2571: 
1.156     albertel 2572: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2573: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2574: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2575: 	    my $submitted = 0;
1.248     albertel 2576: 	    my $ungraded = 0;
                   2577: 	    my $incorrect = 0;
1.145     albertel 2578: 	    foreach (keys(%status)) {
                   2579: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2580: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2581: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2582: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2583: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2584: 		    $submitted = 0;
                   2585: 		}
1.41      ng       2586: 	    }
1.156     albertel 2587: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2588: 				     $submitonly eq 'incorrect' ||
                   2589: 				     $submitonly eq 'graded'));
1.248     albertel 2590: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2591: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2592: 	}
                   2593: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2594: 	last if ($ctr == $ntstu);
1.41      ng       2595: 	$ctr++;
                   2596:     }
1.36      ng       2597: 
1.41      ng       2598:     $ctr = 0;
                   2599:     my $total = scalar(@nextlist)-1;
1.39      ng       2600: 
1.41      ng       2601:     foreach (sort @nextlist) {
                   2602: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2603: 	$env{'form.student'}  = $uname;
                   2604: 	$env{'form.userdom'}  = $udom;
                   2605: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2606: 	&submission($request,$ctr,$total);
                   2607: 	$ctr++;
                   2608:     }
                   2609:     if ($total < 0) {
1.485   ! albertel 2610: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
        !          2611: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
        !          2612: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2613: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2614: 	$request->print($the_end);
                   2615:     }
                   2616:     return '';
1.38      ng       2617: }
1.36      ng       2618: 
1.44      ng       2619: #---- Save the score and award for each student, if changed
1.38      ng       2620: sub saveHandGrade {
1.324     albertel 2621:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2622:     my @version_parts;
1.104     albertel 2623:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2624: 					   $env{'request.course.id'});
1.104     albertel 2625:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2626:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2627:     my @parts_graded;
1.77      ng       2628:     my %newrecord  = ();
                   2629:     my ($pts,$wgt) = ('','');
1.269     raeburn  2630:     my %aggregate = ();
                   2631:     my $aggregateflag = 0;
1.301     albertel 2632:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2633:     foreach my $new_part (@parts) {
1.337     banghart 2634: 	#collaborator ($submi may vary for different parts
1.259     banghart 2635: 	if ($submitter && $new_part ne $part) { next; }
                   2636: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2637: 	if ($dropMenu eq 'excused') {
1.259     banghart 2638: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2639: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2640: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2641: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2642: 		}
1.364     banghart 2643: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2644: 	    }
1.125     ng       2645: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2646: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2647: 	    foreach my $key (keys (%record)) {
1.259     banghart 2648: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2649: 	    }
1.259     banghart 2650: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2651: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2652:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2653: 
                   2654:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2655: 					       [$new_part]);
                   2656:             my $aggtries =$totaltries;
1.269     raeburn  2657:             if ($last_resets{$new_part}) {
1.270     albertel 2658:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2659: 					   $new_part);
1.269     raeburn  2660:             }
1.270     albertel 2661: 
                   2662:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2663:             if ($aggtries > 0) {
1.327     albertel 2664:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2665:                 $aggregateflag = 1;
                   2666:             }
1.125     ng       2667: 	} elsif ($dropMenu eq '') {
1.259     banghart 2668: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2669: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2670: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2671: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2672: 		next;
                   2673: 	    }
1.259     banghart 2674: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2675: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2676: 	    my $partial= $pts/$wgt;
1.259     banghart 2677: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2678: 		#do not update score for part if not changed.
1.346     banghart 2679:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2680: 		next;
1.251     banghart 2681: 	    } else {
1.259     banghart 2682: 	        push @parts_graded, $new_part;
1.153     albertel 2683: 	    }
1.259     banghart 2684: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2685: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2686: 	    }
1.259     banghart 2687: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2688: 	    if ($partial == 0) {
1.153     albertel 2689: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2690: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2691: 		}
1.41      ng       2692: 	    } else {
1.153     albertel 2693: 		if ($record{$reckey} ne 'correct_by_override') {
                   2694: 		    $newrecord{$reckey} = 'correct_by_override';
                   2695: 		}
                   2696: 	    }	    
                   2697: 	    if ($submitter && 
1.259     banghart 2698: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2699: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2700: 	    }
1.259     banghart 2701: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2702: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2703: 	}
1.259     banghart 2704: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2705: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2706: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2707: 	        $dropMenu eq 'reset status')
                   2708: 	   {
1.342     banghart 2709: 	    push (@version_parts,$new_part);
1.259     banghart 2710: 	}
1.41      ng       2711:     }
1.301     albertel 2712:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2713:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2714: 
1.344     albertel 2715:     if (%newrecord) {
                   2716:         if (@version_parts) {
1.364     banghart 2717:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2718:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2719: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2720: 	    foreach my $new_part (@version_parts) {
                   2721: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2722: 				$new_part,\%newrecord);
                   2723: 	    }
1.259     banghart 2724:         }
1.44      ng       2725: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2726: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2727: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2728: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2729:     }
1.269     raeburn  2730:     if ($aggregateflag) {
                   2731:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2732: 			      $cdom,$cnum);
1.269     raeburn  2733:     }
1.301     albertel 2734:     return ('',$pts,$wgt);
1.36      ng       2735: }
1.322     albertel 2736: 
1.380     albertel 2737: sub check_and_remove_from_queue {
                   2738:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2739:     my @ungraded_parts;
                   2740:     foreach my $part (@{$parts}) {
                   2741: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2742: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2743: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2744: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2745: 		) {
                   2746: 	    push(@ungraded_parts, $part);
                   2747: 	}
                   2748:     }
                   2749:     if ( !@ungraded_parts ) {
                   2750: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2751: 					       $cnum,$domain,$stuname);
                   2752:     }
                   2753: }
                   2754: 
1.337     banghart 2755: sub handback_files {
                   2756:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2757:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2758:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2759: 
                   2760:     my @part_response_id = &flatten_responseType($responseType);
                   2761:     foreach my $part_response_id (@part_response_id) {
                   2762:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2763: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2764:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2765:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2766:                 my $file_counter = 1;
1.367     albertel 2767: 		my $file_msg;
1.337     banghart 2768:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2769:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2770:                     my ($directory,$answer_file) = 
                   2771:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2772:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2773: 		        &file_name_version_ext($answer_file);
1.355     banghart 2774: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2775: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2776: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2777:                     # fix file name
                   2778:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2779:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2780:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2781:             	                                $save_file_name);
1.337     banghart 2782:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2783:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2784:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2785:                     } else {
1.360     banghart 2786:                         # mark the file as read only
                   2787:                         my @files = ($save_file_name);
1.372     albertel 2788:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2789:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2790: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2791: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2792: 			}
                   2793:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2794: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2795: 
1.337     banghart 2796:                     }
                   2797:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2798:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2799:                     $file_counter++;
                   2800:                 }
1.367     albertel 2801: 		my $subject = "File Handed Back by Instructor ";
                   2802: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2803: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2804: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2805: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2806: 		my ($feedurl,$showsymb) = 
                   2807: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2808:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2809: 		my $msgstatus = 
                   2810:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2811: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2812:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2813:             }
                   2814:         }
1.338     banghart 2815:     return;
1.337     banghart 2816: }
                   2817: 
1.418     albertel 2818: sub get_feedurl_and_symb {
                   2819:     my ($symb,$uname,$udom) = @_;
                   2820:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2821:     $url = &Apache::lonnet::clutter($url);
                   2822:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2823: 					$symb,$udom,$uname);
                   2824:     if ($encrypturl =~ /^yes$/i) {
                   2825: 	&Apache::lonenc::encrypted(\$url,1);
                   2826: 	&Apache::lonenc::encrypted(\$symb,1);
                   2827:     }
                   2828:     return ($url,$symb);
                   2829: }
                   2830: 
1.313     banghart 2831: sub get_submitted_files {
                   2832:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2833:     my @files;
                   2834:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2835:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2836:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2837:     	    push(@files,$file_url.$file);
                   2838:         }
                   2839:     }
                   2840:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2841:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2842:     }
                   2843:     return (\@files);
                   2844: }
1.322     albertel 2845: 
1.269     raeburn  2846: # ----------- Provides number of tries since last reset.
                   2847: sub get_num_tries {
                   2848:     my ($record,$last_reset,$part) = @_;
                   2849:     my $timestamp = '';
                   2850:     my $num_tries = 0;
                   2851:     if ($$record{'version'}) {
                   2852:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2853:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2854:                 $timestamp = $$record{$version.':timestamp'};
                   2855:                 if ($timestamp > $last_reset) {
                   2856:                     $num_tries ++;
                   2857:                 } else {
                   2858:                     last;
                   2859:                 }
                   2860:             }
                   2861:         }
                   2862:     }
                   2863:     return $num_tries;
                   2864: }
                   2865: 
                   2866: # ----------- Determine decrements required in aggregate totals 
                   2867: sub decrement_aggs {
                   2868:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2869:     my %decrement = (
                   2870:                         attempts => 0,
                   2871:                         users => 0,
                   2872:                         correct => 0
                   2873:                     );
                   2874:     $decrement{'attempts'} = $aggtries;
                   2875:     if ($solvedstatus =~ /^correct/) {
                   2876:         $decrement{'correct'} = 1;
                   2877:     }
                   2878:     if ($aggtries == $totaltries) {
                   2879:         $decrement{'users'} = 1;
                   2880:     }
                   2881:     foreach my $type (keys (%decrement)) {
                   2882:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2883:     }
                   2884:     return;
                   2885: }
                   2886: 
                   2887: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2888: sub get_last_resets {
1.270     albertel 2889:     my ($symb,$courseid,$partids) =@_;
                   2890:     my %last_resets;
1.269     raeburn  2891:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2892:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2893:     my @keys;
                   2894:     foreach my $part (@{$partids}) {
                   2895: 	push(@keys,"$symb\0$part\0resettime");
                   2896:     }
                   2897:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2898: 				     $cdom,$cname);
                   2899:     foreach my $part (@{$partids}) {
                   2900: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2901:     }
1.270     albertel 2902:     return %last_resets;
1.269     raeburn  2903: }
                   2904: 
1.251     banghart 2905: # ----------- Handles creating versions for portfolio files as answers
                   2906: sub version_portfiles {
1.343     banghart 2907:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2908:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2909:     my @returned_keys;
1.255     banghart 2910:     my $parts = join('|', @$parts_graded);
1.359     www      2911:     my $portfolio_root = &propath($domain,$stu_name).
                   2912: 	'/userfiles/portfolio';
1.277     albertel 2913:     foreach my $key (keys(%$record)) {
1.259     banghart 2914:         my $new_portfiles;
1.263     banghart 2915:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2916:             my @versioned_portfiles;
1.367     albertel 2917:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2918:             foreach my $file (@portfiles) {
1.306     banghart 2919:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2920:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2921: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2922: 		    &file_name_version_ext($answer_file);
1.306     banghart 2923:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2924:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2925:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2926:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2927:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2928:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2929:                         [$directory.$new_answer],
1.306     banghart 2930:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2931:                 }
1.252     banghart 2932:             }
1.343     banghart 2933:             $$record{$key} = join(',',@versioned_portfiles);
                   2934:             push(@returned_keys,$key);
1.251     banghart 2935:         }
                   2936:     } 
1.343     banghart 2937:     return (@returned_keys);   
1.305     banghart 2938: }
                   2939: 
1.307     banghart 2940: sub get_next_version {
1.341     banghart 2941:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2942:     my $version;
                   2943:     foreach my $row (@$dir_list) {
                   2944:         my ($file) = split(/\&/,$row,2);
                   2945:         my ($file_name,$file_version,$file_ext) =
                   2946: 	    &file_name_version_ext($file);
                   2947:         if (($file_name eq $answer_name) && 
                   2948: 	    ($file_ext eq $answer_ext)) {
                   2949:                 # gets here if filename and extension match, regardless of version
                   2950:                 if ($file_version ne '') {
                   2951:                 # a versioned file is found  so save it for later
                   2952:                 if ($file_version > $version) {
                   2953: 		    $version = $file_version;
                   2954: 	        }
                   2955:             }
                   2956:         }
                   2957:     } 
                   2958:     $version ++;
                   2959:     return($version);
                   2960: }
                   2961: 
1.305     banghart 2962: sub version_selected_portfile {
1.306     banghart 2963:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2964:     my ($answer_name,$answer_ver,$answer_ext) =
                   2965:         &file_name_version_ext($file_name);
                   2966:     my $new_answer;
                   2967:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2968:     if($env{'form.copy'} eq '-1') {
                   2969:         $new_answer = 'problem getting file';
                   2970:     } else {
                   2971:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2972:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2973:                             $stu_name,$domain,'copy',
                   2974: 		        '/portfolio'.$directory.$new_answer);
                   2975:     }    
                   2976:     return ($new_answer);
1.251     banghart 2977: }
                   2978: 
1.304     albertel 2979: sub file_name_version_ext {
                   2980:     my ($file)=@_;
                   2981:     my @file_parts = split(/\./, $file);
                   2982:     my ($name,$version,$ext);
                   2983:     if (@file_parts > 1) {
                   2984: 	$ext=pop(@file_parts);
                   2985: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2986: 	    $version=pop(@file_parts);
                   2987: 	}
                   2988: 	$name=join('.',@file_parts);
                   2989:     } else {
                   2990: 	$name=join('.',@file_parts);
                   2991:     }
                   2992:     return($name,$version,$ext);
                   2993: }
                   2994: 
1.44      ng       2995: #--------------------------------------------------------------------------------------
                   2996: #
                   2997: #-------------------------- Next few routines handles grading by section or whole class
                   2998: #
                   2999: #--- Javascript to handle grading by section or whole class
1.42      ng       3000: sub viewgrades_js {
                   3001:     my ($request) = shift;
                   3002: 
1.41      ng       3003:     $request->print(<<VIEWJAVASCRIPT);
                   3004: <script type="text/javascript" language="javascript">
1.45      ng       3005:    function writePoint(partid,weight,point) {
1.125     ng       3006: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3007: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3008: 	if (point == "textval") {
1.125     ng       3009: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3010: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3011: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3012: 		var resetbox = false;
                   3013: 		for (var i=0; i<radioButton.length; i++) {
                   3014: 		    if (radioButton[i].checked) {
                   3015: 			textbox.value = i;
                   3016: 			resetbox = true;
                   3017: 		    }
                   3018: 		}
                   3019: 		if (!resetbox) {
                   3020: 		    textbox.value = "";
                   3021: 		}
                   3022: 		return;
                   3023: 	    }
1.109     matthew  3024: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3025: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3026: 				   ") greater than the weight for the part. Accept?");
                   3027: 		if (resp == false) {
                   3028: 		    textbox.value = "";
                   3029: 		    return;
                   3030: 		}
                   3031: 	    }
1.42      ng       3032: 	    for (var i=0; i<radioButton.length; i++) {
                   3033: 		radioButton[i].checked=false;
1.109     matthew  3034: 		if (parseFloat(point) == i) {
1.42      ng       3035: 		    radioButton[i].checked=true;
                   3036: 		}
                   3037: 	    }
1.41      ng       3038: 
1.42      ng       3039: 	} else {
1.125     ng       3040: 	    textbox.value = parseFloat(point);
1.42      ng       3041: 	}
1.41      ng       3042: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3043: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3044: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3045: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3046: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3047: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3048: 	    if (saveval != "correct") {
                   3049: 		scorename.value = point;
1.43      ng       3050: 		if (selname[0].selected != true) {
                   3051: 		    selname[0].selected = true;
                   3052: 		}
1.42      ng       3053: 	    }
                   3054: 	}
1.125     ng       3055: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3056:     }
                   3057: 
                   3058:     function writeRadText(partid,weight) {
1.125     ng       3059: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3060: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3061:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3062: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3063: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3064: 	    for (var i=0; i<radioButton.length; i++) {
                   3065: 		radioButton[i].checked=false;
                   3066: 
                   3067: 	    }
                   3068: 	    textbox.value = "";
                   3069: 
                   3070: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3071: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3072: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3073: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3074: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3075: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3076: 		if ((saveval != "correct") || override) {
1.42      ng       3077: 		    scorename.value = "";
1.125     ng       3078: 		    if (selval[1].selected) {
                   3079: 			selname[1].selected = true;
                   3080: 		    } else {
                   3081: 			selname[2].selected = true;
                   3082: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3083: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3084: 		    }
1.42      ng       3085: 		}
                   3086: 	    }
1.43      ng       3087: 	} else {
                   3088: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3089: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3090: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3091: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3092: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3093: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3094: 		if ((saveval != "correct") || override) {
1.125     ng       3095: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3096: 		    selname[0].selected = true;
                   3097: 		}
                   3098: 	    }
                   3099: 	}	    
1.42      ng       3100:     }
                   3101: 
                   3102:     function changeSelect(partid,user) {
1.125     ng       3103: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3104: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3105: 	var point  = textbox.value;
1.125     ng       3106: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3107: 
1.109     matthew  3108: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3109: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3110: 	    textbox.value = "";
                   3111: 	    return;
                   3112: 	}
1.109     matthew  3113: 	if (parseFloat(point) > parseFloat(weight)) {
                   3114: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3115: 			       ") greater than the weight of the part. Accept?");
                   3116: 	    if (resp == false) {
                   3117: 		textbox.value = "";
                   3118: 		return;
                   3119: 	    }
                   3120: 	}
1.42      ng       3121: 	selval[0].selected = true;
                   3122:     }
                   3123: 
                   3124:     function changeOneScore(partid,user) {
1.125     ng       3125: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3126: 	if (selval[1].selected || selval[2].selected) {
                   3127: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3128: 	    if (selval[2].selected) {
                   3129: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3130: 	    }
1.269     raeburn  3131:         }
1.42      ng       3132:     }
                   3133: 
                   3134:     function resetEntry(numpart) {
                   3135: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3136: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3137: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3138: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3139: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3140: 	    for (var i=0; i<radioButton.length; i++) {
                   3141: 		radioButton[i].checked=false;
                   3142: 
                   3143: 	    }
                   3144: 	    textbox.value = "";
                   3145: 	    selval[0].selected = true;
                   3146: 
                   3147: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3148: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3149: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3150: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3151: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3152: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3153: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3154: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3155: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3156: 		if (saveselval == "excused") {
1.43      ng       3157: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3158: 		} else {
1.43      ng       3159: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3160: 		}
                   3161: 	    }
1.41      ng       3162: 	}
1.42      ng       3163:     }
                   3164: 
1.41      ng       3165: </script>
                   3166: VIEWJAVASCRIPT
1.42      ng       3167: }
                   3168: 
1.44      ng       3169: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3170: sub viewgrades {
                   3171:     my ($request) = shift;
                   3172:     &viewgrades_js($request);
1.41      ng       3173: 
1.324     albertel 3174:     my ($symb) = &get_symb($request);
1.168     albertel 3175:     #need to make sure we have the correct data for later EXT calls, 
                   3176:     #thus invalidate the cache
                   3177:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3178:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3179:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3180:     &Apache::lonnet::clear_EXT_cache_status();
                   3181: 
1.398     albertel 3182:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485   ! albertel 3183:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3184: 
                   3185:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3186:     $result.=&jscriptNform($symb);
1.41      ng       3187: 
1.44      ng       3188:     #beginning of class grading form
1.442     banghart 3189:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3190:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3191: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3192: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3193: 	&build_section_inputs().
1.257     albertel 3194: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3195: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3196: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3197: 
1.126     ng       3198:     my $sectionClass;
1.430     banghart 3199:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3200:     if ($env{'form.section'} eq 'all') {
1.485   ! albertel 3201: 	$sectionClass='Class';
1.257     albertel 3202:     } elsif ($env{'form.section'} eq 'none') {
1.485   ! albertel 3203: 	$sectionClass='Students in no Section';
1.52      albertel 3204:     } else {
1.485   ! albertel 3205: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3206:     }
1.485   ! albertel 3207:     $result.=
        !          3208: 	'<h3>'.
        !          3209: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3210:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3211:     #radio buttons/text box for assigning points for a section or class.
                   3212:     #handles different parts of a problem
1.375     albertel 3213:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3214:     my %weight = ();
                   3215:     my $ctsparts = 0;
1.45      ng       3216:     my %seen = ();
1.375     albertel 3217:     my @part_response_id = &flatten_responseType($responseType);
                   3218:     foreach my $part_response_id (@part_response_id) {
                   3219:     	my ($partid,$respid) = @{ $part_response_id };
                   3220: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3221: 	next if $seen{$partid};
                   3222: 	$seen{$partid}++;
1.375     albertel 3223: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3224: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3225: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3226: 
1.324     albertel 3227: 	my $display_part=&get_display_part($partid,$symb);
1.485   ! albertel 3228: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3229: 	my $ctr = 0;
1.42      ng       3230: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485   ! albertel 3231: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3232: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3233: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3234: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3235: 	    $ctr++;
                   3236: 	}
1.485   ! albertel 3237: 	$radio.='</tr></table>';
        !          3238: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3239: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3240: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3241: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485   ! albertel 3242: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3243: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3244: 		$weight{$partid}.')"> '.
1.401     albertel 3245: 	    '<option selected="selected"> </option>'.
1.485   ! albertel 3246: 	    '<option value="excused">'.&mt('excused').'</option>'.
        !          3247: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
        !          3248: 	    '</select></td>'.
        !          3249:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
        !          3250: 	$line.='<input type="hidden" name="partid_'.
        !          3251: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
        !          3252: 	$line.='<input type="hidden" name="weight_'.
        !          3253: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
        !          3254: 
        !          3255: 	$result.=
        !          3256: 	    &Apache::loncommon::start_data_table_row()."\n".
        !          3257: 	    &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).
        !          3258: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3259: 	$ctsparts++;
1.41      ng       3260:     }
1.474     albertel 3261:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3262: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485   ! albertel 3263:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3264: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3265: 
1.44      ng       3266:     #table listing all the students in a section/class
                   3267:     #header of table
1.485   ! albertel 3268:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
        !          3269: 			 $section_display).'</h3>';
1.474     albertel 3270:     $result.= &Apache::loncommon::start_data_table().
                   3271: 	&Apache::loncommon::start_data_table_header_row().
1.485   ! albertel 3272: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3273: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3274:     my (@parts) = sort(&getpartlist($symb));
                   3275:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3276:     my @partids = ();
1.41      ng       3277:     foreach my $part (@parts) {
                   3278: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3279: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3280: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3281: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3282:         push(@partids, $partid);
1.324     albertel 3283: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3284: 	if ($display =~ /^Partial Credit Factor/) {
1.485   ! albertel 3285: 	    $result.='<th>'.
        !          3286: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
        !          3287: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3288: 	    next;
1.485   ! albertel 3289: 	    
1.207     albertel 3290: 	} else {
1.485   ! albertel 3291: 	    if ($display =~ /Problem Status/) {
        !          3292: 		my $grade_status_mt = &mt('Grade Status');
        !          3293: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
        !          3294: 	    }
        !          3295: 	    my $part_mt = &mt('Part:');
        !          3296: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3297: 	}
1.485   ! albertel 3298: 
1.474     albertel 3299: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3300:     }
1.474     albertel 3301:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3302: 
1.270     albertel 3303:     my %last_resets = 
                   3304: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3305: 
1.41      ng       3306:     #get info for each student
1.44      ng       3307:     #list all the students - with points and grade status
1.257     albertel 3308:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3309:     my $ctr = 0;
1.294     albertel 3310:     foreach (sort 
                   3311: 	     {
                   3312: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3313: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3314: 		 }
                   3315: 		 return $a cmp $b;
                   3316: 	     } (keys(%$fullname))) {
1.126     ng       3317: 	$ctr++;
1.324     albertel 3318: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3319: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3320:     }
1.474     albertel 3321:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3322:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485   ! albertel 3323:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3324: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3325:     if (scalar(%$fullname) eq 0) {
                   3326: 	my $colspan=3+scalar(@parts);
1.433     banghart 3327: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3328:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3329: 	$result='<span class="LC_warning">'.
1.485   ! albertel 3330: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3331: 	        $section_display, $stu_status).
1.433     banghart 3332: 	    '</span>';
1.96      albertel 3333:     }
1.324     albertel 3334:     $result.=&show_grading_menu_form($symb);
1.41      ng       3335:     return $result;
                   3336: }
                   3337: 
1.44      ng       3338: #--- call by previous routine to display each student
1.41      ng       3339: sub viewstudentgrade {
1.324     albertel 3340:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3341:     my ($uname,$udom) = split(/:/,$student);
                   3342:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3343:     my %aggregates = (); 
1.474     albertel 3344:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3345: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3346: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3347: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3348: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3349: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3350:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3351:     foreach my $apart (@$parts) {
                   3352: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3353: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3354:         $result.='<td align="center">';
1.269     raeburn  3355:         my ($aggtries,$totaltries);
                   3356:         unless (exists($aggregates{$part})) {
1.270     albertel 3357: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3358: 
                   3359: 	    $aggtries = $totaltries;
1.269     raeburn  3360:             if ($$last_resets{$part}) {  
1.270     albertel 3361:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3362: 					   $part);
                   3363:             }
1.269     raeburn  3364:             $result.='<input type="hidden" name="'.
                   3365:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3366:             $result.='<input type="hidden" name="'.
                   3367:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3368:             $aggregates{$part} = 1;
                   3369:         }
1.41      ng       3370: 	if ($type eq 'awarded') {
1.320     albertel 3371: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3372: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3373: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3374: 	    $result.='<input type="text" name="'.
1.89      albertel 3375: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3376: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3377: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3378: 	} elsif ($type eq 'solved') {
                   3379: 	    my ($status,$foo)=split(/_/,$score,2);
                   3380: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3381: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3382: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3383: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3384: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3385: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485   ! albertel 3386: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
        !          3387: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
        !          3388: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3389: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3390: 	} else {
                   3391: 	    $result.='<input type="hidden" name="'.
                   3392: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3393: 		    "\n";
1.233     albertel 3394: 	    $result.='<input type="text" name="'.
1.122     ng       3395: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3396: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3397: 	}
                   3398:     }
1.474     albertel 3399:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3400:     return $result;
1.38      ng       3401: }
                   3402: 
1.44      ng       3403: #--- change scores for all the students in a section/class
                   3404: #    record does not get update if unchanged
1.38      ng       3405: sub editgrades {
1.41      ng       3406:     my ($request) = @_;
                   3407: 
1.324     albertel 3408:     my $symb=&get_symb($request);
1.433     banghart 3409:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3410:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3411:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3412:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3413: 
1.477     albertel 3414:     my $result= &Apache::loncommon::start_data_table().
                   3415: 	&Apache::loncommon::start_data_table_header_row().
                   3416: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3417: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3418:     my %scoreptr = (
                   3419: 		    'correct'  =>'correct_by_override',
                   3420: 		    'incorrect'=>'incorrect_by_override',
                   3421: 		    'excused'  =>'excused',
                   3422: 		    'ungraded' =>'ungraded_attempted',
                   3423: 		    'nothing'  => '',
                   3424: 		    );
1.257     albertel 3425:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3426: 
1.44      ng       3427:     my (@partid);
                   3428:     my %weight = ();
1.54      albertel 3429:     my %columns = ();
1.44      ng       3430:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3431: 
1.324     albertel 3432:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3433:     my $header;
1.257     albertel 3434:     while ($ctr < $env{'form.totalparts'}) {
                   3435: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3436: 	push @partid,$partid;
1.257     albertel 3437: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3438: 	$ctr++;
1.54      albertel 3439:     }
1.324     albertel 3440:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3441:     foreach my $partid (@partid) {
1.478     albertel 3442: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3443: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3444: 	$columns{$partid}=2;
                   3445: 	foreach my $stores (@parts) {
                   3446: 	    my ($part,$type) = &split_part_type($stores);
                   3447: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3448: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3449: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3450: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3451: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3452: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3453: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3454: 	    $columns{$partid}+=2;
                   3455: 	}
                   3456:     }
                   3457:     foreach my $partid (@partid) {
1.324     albertel 3458: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3459: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3460: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3461: 	    '</th>';
1.54      albertel 3462: 
1.44      ng       3463:     }
1.477     albertel 3464:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3465: 	&Apache::loncommon::start_data_table_header_row().
                   3466: 	$header.
                   3467: 	&Apache::loncommon::end_data_table_header_row();
                   3468:     my @noupdate;
1.126     ng       3469:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3470:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3471: 	my $line;
1.257     albertel 3472: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3473: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3474: 	my %newrecord;
                   3475: 	my $updateflag = 0;
1.281     albertel 3476: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3477: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3478: 	if (!&canmodify($usec)) {
1.126     ng       3479: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3480: 	    push(@noupdate,
1.478     albertel 3481: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3482: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3483: 	    next;
                   3484: 	}
1.269     raeburn  3485:         my %aggregate = ();
                   3486:         my $aggregateflag = 0;
1.281     albertel 3487: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3488: 	foreach (@partid) {
1.257     albertel 3489: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3490: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3491: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3492: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3493: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3494: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3495: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3496: 	    my $score;
                   3497: 	    if ($partial eq '') {
1.257     albertel 3498: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3499: 	    } elsif ($partial > 0) {
                   3500: 		$score = 'correct_by_override';
                   3501: 	    } elsif ($partial == 0) {
                   3502: 		$score = 'incorrect_by_override';
                   3503: 	    }
1.257     albertel 3504: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3505: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3506: 
1.292     albertel 3507: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3508: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3509: 	    if ($dropMenu eq 'reset status' &&
                   3510: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3511: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3512: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3513: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3514: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3515: 		$updateflag = 1;
1.269     raeburn  3516:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3517:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3518:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3519:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3520:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3521:                     $aggregateflag = 1;
                   3522:                 }
1.139     albertel 3523: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3524: 		$updateflag = 1;
                   3525: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3526: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3527: 		$rec_update++;
1.125     ng       3528: 	    }
                   3529: 
1.93      albertel 3530: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3531: 		'<td align="center">'.$awarded.
                   3532: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3533: 
1.54      albertel 3534: 
                   3535: 	    my $partid=$_;
                   3536: 	    foreach my $stores (@parts) {
                   3537: 		my ($part,$type) = &split_part_type($stores);
                   3538: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3539: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3540: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3541: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3542: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3543: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3544: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3545: 		    $updateflag=1;
                   3546: 		}
1.93      albertel 3547: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3548: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3549: 	    }
1.44      ng       3550: 	}
1.477     albertel 3551: 	$line.="\n";
1.301     albertel 3552: 
                   3553: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3554: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3555: 
1.44      ng       3556: 	if ($updateflag) {
                   3557: 	    $count++;
1.257     albertel 3558: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3559: 				    $udom,$uname);
1.301     albertel 3560: 
                   3561: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3562: 					      $cnum,$udom,$uname)) {
                   3563: 		# need to figure out if should be in queue.
                   3564: 		my %record =  
                   3565: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3566: 					     $udom,$uname);
                   3567: 		my $all_graded = 1;
                   3568: 		my $none_graded = 1;
                   3569: 		foreach my $part (@parts) {
                   3570: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3571: 			$all_graded = 0;
                   3572: 		    } else {
                   3573: 			$none_graded = 0;
                   3574: 		    }
                   3575: 		}
                   3576: 
                   3577: 		if ($all_graded || $none_graded) {
                   3578: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3579: 							   $symb,$cdom,$cnum,
                   3580: 							   $udom,$uname);
                   3581: 		}
                   3582: 	    }
                   3583: 
1.477     albertel 3584: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3585: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3586: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3587: 	    $updateCtr++;
1.93      albertel 3588: 	} else {
1.477     albertel 3589: 	    push(@noupdate,
                   3590: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3591: 	    $noupdateCtr++;
1.44      ng       3592: 	}
1.269     raeburn  3593:         if ($aggregateflag) {
                   3594:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3595: 				  $cdom,$cnum);
1.269     raeburn  3596:         }
1.93      albertel 3597:     }
1.477     albertel 3598:     if (@noupdate) {
1.126     ng       3599: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3600: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3601: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3602: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3603: 	    &mt('No Changes Occurred For the Students Below').
                   3604: 	    '</td>'.
1.477     albertel 3605: 	    &Apache::loncommon::end_data_table_row();
                   3606: 	foreach my $line (@noupdate) {
                   3607: 	    $result.=
                   3608: 		&Apache::loncommon::start_data_table_row().
                   3609: 		$line.
                   3610: 		&Apache::loncommon::end_data_table_row();
                   3611: 	}
1.44      ng       3612:     }
1.477     albertel 3613:     $result .= &Apache::loncommon::end_data_table().
                   3614: 	&show_grading_menu_form($symb);
1.478     albertel 3615:     my $msg = '<p><b>'.
                   3616: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3617: 	    $rec_update,$count).'</b><br />'.
                   3618: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3619: 	'</b></p>';
1.44      ng       3620:     return $title.$msg.$result;
1.5       albertel 3621: }
1.54      albertel 3622: 
                   3623: sub split_part_type {
                   3624:     my ($partstr) = @_;
                   3625:     my ($temp,@allparts)=split(/_/,$partstr);
                   3626:     my $type=pop(@allparts);
1.439     albertel 3627:     my $part=join('_',@allparts);
1.54      albertel 3628:     return ($part,$type);
                   3629: }
                   3630: 
1.44      ng       3631: #------------- end of section for handling grading by section/class ---------
                   3632: #
                   3633: #----------------------------------------------------------------------------
                   3634: 
1.5       albertel 3635: 
1.44      ng       3636: #----------------------------------------------------------------------------
                   3637: #
                   3638: #-------------------------- Next few routines handles grading by csv upload
                   3639: #
                   3640: #--- Javascript to handle csv upload
1.27      albertel 3641: sub csvupload_javascript_reverse_associate {
1.246     albertel 3642:     my $error1=&mt('You need to specify the username or ID');
                   3643:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3644:   return(<<ENDPICK);
                   3645:   function verify(vf) {
                   3646:     var foundsomething=0;
                   3647:     var founduname=0;
1.243     albertel 3648:     var foundID=0;
1.27      albertel 3649:     for (i=0;i<=vf.nfields.value;i++) {
                   3650:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3651:       if (i==0 && tw!=0) { foundID=1; }
                   3652:       if (i==1 && tw!=0) { founduname=1; }
                   3653:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3654:     }
1.246     albertel 3655:     if (founduname==0 && foundID==0) {
                   3656: 	alert('$error1');
                   3657: 	return;
1.27      albertel 3658:     }
                   3659:     if (foundsomething==0) {
1.246     albertel 3660: 	alert('$error2');
                   3661: 	return;
1.27      albertel 3662:     }
                   3663:     vf.submit();
                   3664:   }
                   3665:   function flip(vf,tf) {
                   3666:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3667:     var i;
                   3668:     for (i=0;i<=vf.nfields.value;i++) {
                   3669:       //can not pick the same destination field for both name and domain
                   3670:       if (((i ==0)||(i ==1)) && 
                   3671:           ((tf==0)||(tf==1)) && 
                   3672:           (i!=tf) &&
                   3673:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3674:         eval('vf.f'+i+'.selectedIndex=0;')
                   3675:       }
                   3676:     }
                   3677:   }
                   3678: ENDPICK
                   3679: }
                   3680: 
                   3681: sub csvupload_javascript_forward_associate {
1.246     albertel 3682:     my $error1=&mt('You need to specify the username or ID');
                   3683:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3684:   return(<<ENDPICK);
                   3685:   function verify(vf) {
                   3686:     var foundsomething=0;
                   3687:     var founduname=0;
1.243     albertel 3688:     var foundID=0;
1.27      albertel 3689:     for (i=0;i<=vf.nfields.value;i++) {
                   3690:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3691:       if (tw==1) { foundID=1; }
                   3692:       if (tw==2) { founduname=1; }
                   3693:       if (tw>3) { foundsomething=1; }
1.27      albertel 3694:     }
1.246     albertel 3695:     if (founduname==0 && foundID==0) {
                   3696: 	alert('$error1');
                   3697: 	return;
1.27      albertel 3698:     }
                   3699:     if (foundsomething==0) {
1.246     albertel 3700: 	alert('$error2');
                   3701: 	return;
1.27      albertel 3702:     }
                   3703:     vf.submit();
                   3704:   }
                   3705:   function flip(vf,tf) {
                   3706:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3707:     var i;
                   3708:     //can not pick the same destination field twice
                   3709:     for (i=0;i<=vf.nfields.value;i++) {
                   3710:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3711:         eval('vf.f'+i+'.selectedIndex=0;')
                   3712:       }
                   3713:     }
                   3714:   }
                   3715: ENDPICK
                   3716: }
                   3717: 
1.26      albertel 3718: sub csvuploadmap_header {
1.324     albertel 3719:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3720:     my $javascript;
1.257     albertel 3721:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3722: 	$javascript=&csvupload_javascript_reverse_associate();
                   3723:     } else {
                   3724: 	$javascript=&csvupload_javascript_forward_associate();
                   3725:     }
1.45      ng       3726: 
1.324     albertel 3727:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3728:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3729:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3730:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3731:     $request->print(<<ENDPICK);
1.26      albertel 3732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3733: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3734: $result
1.326     albertel 3735: <hr />
1.26      albertel 3736: <h3>Identify fields</h3>
                   3737: Total number of records found in file: $distotal <hr />
                   3738: Enter as many fields as you can. The system will inform you and bring you back
                   3739: to this page if the data selected is insufficient to run your class.<hr />
                   3740: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3741: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3742: <input type="hidden" name="associate"  value="" />
                   3743: <input type="hidden" name="phase"      value="three" />
                   3744: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3745: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3746: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3747: <input type="hidden" name="upfile_associate" 
1.257     albertel 3748:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3749: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3750: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3751: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3752: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3753: <hr />
                   3754: <script type="text/javascript" language="Javascript">
                   3755: $javascript
                   3756: </script>
                   3757: ENDPICK
1.118     ng       3758:     return '';
1.26      albertel 3759: 
                   3760: }
                   3761: 
                   3762: sub csvupload_fields {
1.324     albertel 3763:     my ($symb) = @_;
                   3764:     my (@parts) = &getpartlist($symb);
1.243     albertel 3765:     my @fields=(['ID','Student ID'],
                   3766: 		['username','Student Username'],
                   3767: 		['domain','Student Domain']);
1.324     albertel 3768:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3769:     foreach my $part (sort(@parts)) {
                   3770: 	my @datum;
                   3771: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3772: 	my $name=$part;
                   3773: 	if  (!$display) { $display = $name; }
                   3774: 	@datum=($name,$display);
1.244     albertel 3775: 	if ($name=~/^stores_(.*)_awarded/) {
                   3776: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3777: 	}
1.41      ng       3778: 	push(@fields,\@datum);
                   3779:     }
                   3780:     return (@fields);
1.26      albertel 3781: }
                   3782: 
                   3783: sub csvuploadmap_footer {
1.41      ng       3784:     my ($request,$i,$keyfields) =@_;
                   3785:     $request->print(<<ENDPICK);
1.26      albertel 3786: </table>
                   3787: <input type="hidden" name="nfields" value="$i" />
                   3788: <input type="hidden" name="keyfields" value="$keyfields" />
                   3789: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3790: </form>
                   3791: ENDPICK
                   3792: }
                   3793: 
1.283     albertel 3794: sub checkforfile_js {
1.86      ng       3795:     my $result =<<CSVFORMJS;
                   3796: <script type="text/javascript" language="javascript">
                   3797:     function checkUpload(formname) {
                   3798: 	if (formname.upfile.value == "") {
                   3799: 	    alert("Please use the browse button to select a file from your local directory.");
                   3800: 	    return false;
                   3801: 	}
                   3802: 	formname.submit();
                   3803:     }
                   3804:     </script>
                   3805: CSVFORMJS
1.283     albertel 3806:     return $result;
                   3807: }
                   3808: 
                   3809: sub upcsvScores_form {
                   3810:     my ($request) = shift;
1.324     albertel 3811:     my ($symb)=&get_symb($request);
1.283     albertel 3812:     if (!$symb) {return '';}
                   3813:     my $result=&checkforfile_js();
1.257     albertel 3814:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3815:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3816:     $result.=$table;
1.326     albertel 3817:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3818:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3819:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3820: 	'.</b></td></tr>'."\n";
                   3821:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3822:     my $upload=&mt("Upload Scores");
1.86      ng       3823:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3824:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3825:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3826:     $result.=<<ENDUPFORM;
1.106     albertel 3827: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3828: <input type="hidden" name="symb" value="$symb" />
                   3829: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3830: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3831: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3832: $upfile_select
1.370     www      3833: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3834: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3835: </form>
                   3836: ENDUPFORM
1.370     www      3837:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3838:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3839:     .'</td></tr></table>'."\n";
1.86      ng       3840:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3841:     $result.=&show_grading_menu_form($symb);
1.86      ng       3842:     return $result;
                   3843: }
                   3844: 
                   3845: 
1.26      albertel 3846: sub csvuploadmap {
1.41      ng       3847:     my ($request)= @_;
1.324     albertel 3848:     my ($symb)=&get_symb($request);
1.41      ng       3849:     if (!$symb) {return '';}
1.72      ng       3850: 
1.41      ng       3851:     my $datatoken;
1.257     albertel 3852:     if (!$env{'form.datatoken'}) {
1.41      ng       3853: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3854:     } else {
1.257     albertel 3855: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3856: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3857:     }
1.41      ng       3858:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3859:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3860:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3861:     my ($i,$keyfields);
                   3862:     if (@records) {
1.324     albertel 3863: 	my @fields=&csvupload_fields($symb);
1.45      ng       3864: 
1.257     albertel 3865: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3866: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3867: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3868: 							  \@fields);
                   3869: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3870: 	    chop($keyfields);
                   3871: 	} else {
                   3872: 	    unshift(@fields,['none','']);
                   3873: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3874: 							    \@fields);
1.311     banghart 3875:             foreach my $rec (@records) {
                   3876:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3877:                 if (%temp) {
                   3878:                     $keyfields=join(',',sort(keys(%temp)));
                   3879:                     last;
                   3880:                 }
                   3881:             }
1.41      ng       3882: 	}
                   3883:     }
                   3884:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3885:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3886: 
1.41      ng       3887:     return '';
1.27      albertel 3888: }
                   3889: 
1.246     albertel 3890: sub csvuploadoptions {
1.41      ng       3891:     my ($request)= @_;
1.324     albertel 3892:     my ($symb)=&get_symb($request);
1.257     albertel 3893:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3894:     my $ignore=&mt('Ignore First Line');
                   3895:     $request->print(<<ENDPICK);
                   3896: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3897: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3898: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3899: <!--
1.246     albertel 3900: <p>
                   3901: <label>
                   3902:    <input type="checkbox" name="show_full_results" />
                   3903:    Show a table of all changes
                   3904: </label>
                   3905: </p>
1.302     albertel 3906: -->
1.246     albertel 3907: <p>
                   3908: <label>
                   3909:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3910:    Overwrite any existing score
                   3911: </label>
                   3912: </p>
                   3913: ENDPICK
                   3914:     my %fields=&get_fields();
                   3915:     if (!defined($fields{'domain'})) {
1.257     albertel 3916: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3917: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3918:     }
1.257     albertel 3919:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3920: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3921: 	my $cleankey=$1;
                   3922: 	if ($cleankey eq 'command') { next; }
                   3923: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3924: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3925:     }
                   3926:     # FIXME do a check for any duplicated user ids...
                   3927:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3928:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3929: <hr /></form>'."\n");
1.324     albertel 3930:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3931:     return '';
                   3932: }
                   3933: 
                   3934: sub get_fields {
                   3935:     my %fields;
1.257     albertel 3936:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3937:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3938: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3939: 	    if ($env{'form.f'.$i} ne 'none') {
                   3940: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3941: 	    }
                   3942: 	} else {
1.257     albertel 3943: 	    if ($env{'form.f'.$i} ne 'none') {
                   3944: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3945: 	    }
                   3946: 	}
1.27      albertel 3947:     }
1.246     albertel 3948:     return %fields;
                   3949: }
                   3950: 
                   3951: sub csvuploadassign {
                   3952:     my ($request)= @_;
1.324     albertel 3953:     my ($symb)=&get_symb($request);
1.246     albertel 3954:     if (!$symb) {return '';}
1.345     bowersj2 3955:     my $error_msg = '';
1.246     albertel 3956:     &Apache::loncommon::load_tmp_file($request);
                   3957:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3958:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3959:     my %fields=&get_fields();
1.41      ng       3960:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3961:     my $courseid=$env{'request.course.id'};
1.97      albertel 3962:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3963:     my @notallowed;
1.41      ng       3964:     my @skipped;
                   3965:     my $countdone=0;
                   3966:     foreach my $grade (@gradedata) {
                   3967: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3968: 	my $domain;
                   3969: 	if ($entries{$fields{'domain'}}) {
                   3970: 	    $domain=$entries{$fields{'domain'}};
                   3971: 	} else {
1.257     albertel 3972: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3973: 	}
1.243     albertel 3974: 	$domain=~s/\s//g;
1.41      ng       3975: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3976: 	$username=~s/\s//g;
1.243     albertel 3977: 	if (!$username) {
                   3978: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3979: 	    $id=~s/\s//g;
1.243     albertel 3980: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3981: 	    $username=$ids{$id};
                   3982: 	}
1.41      ng       3983: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3984: 	    my $id=$entries{$fields{'ID'}};
                   3985: 	    $id=~s/\s//g;
                   3986: 	    if ($id) {
                   3987: 		push(@skipped,"$id:$domain");
                   3988: 	    } else {
                   3989: 		push(@skipped,"$username:$domain");
                   3990: 	    }
1.41      ng       3991: 	    next;
                   3992: 	}
1.108     albertel 3993: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3994: 	if (!&canmodify($usec)) {
                   3995: 	    push(@notallowed,"$username:$domain");
                   3996: 	    next;
                   3997: 	}
1.244     albertel 3998: 	my %points;
1.41      ng       3999: 	my %grades;
                   4000: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4001: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4002: 		$dest eq 'domain') { next; }
                   4003: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4004: 	    if ($dest=~/stores_(.*)_points/) {
                   4005: 		my $part=$1;
                   4006: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4007: 					      $symb,$domain,$username);
1.345     bowersj2 4008:                 if ($wgt) {
                   4009:                     $entries{$fields{$dest}}=~s/\s//g;
                   4010:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4011:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4012:                                           : 'correct_by_override';
1.345     bowersj2 4013:                     $grades{"resource.$part.awarded"}=$pcr;
                   4014:                     $grades{"resource.$part.solved"}=$award;
                   4015:                     $points{$part}=1;
                   4016:                 } else {
                   4017:                     $error_msg = "<br />" .
                   4018:                         &mt("Some point values were assigned"
                   4019:                             ." for problems with a weight "
                   4020:                             ."of zero. These values were "
                   4021:                             ."ignored.");
                   4022:                 }
1.244     albertel 4023: 	    } else {
                   4024: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4025: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4026: 		my $store_key=$dest;
                   4027: 		$store_key=~s/^stores/resource/;
                   4028: 		$store_key=~s/_/\./g;
                   4029: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4030: 	    }
1.41      ng       4031: 	}
1.398     albertel 4032: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 4033: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 4034: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   4035: 					   $env{'request.course.id'},
                   4036: 					   $domain,$username);
                   4037: 	if ($result eq 'ok') {
                   4038: 	    $request->print('.');
                   4039: 	} else {
                   4040: 	    $request->print("<p>
1.398     albertel 4041:                               <span class=\"LC_error\">
                   4042:                                  Failed to save student $username:$domain.
                   4043:                                  Message when trying to save was ($result)
                   4044:                               </span>
1.302     albertel 4045:                              </p>" );
                   4046: 	}
1.41      ng       4047: 	$request->rflush();
                   4048: 	$countdone++;
                   4049:     }
1.398     albertel 4050:     $request->print("<br />Saved $countdone students\n");
1.41      ng       4051:     if (@skipped) {
1.398     albertel 4052: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 4053: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4054:     }
                   4055:     if (@notallowed) {
1.398     albertel 4056: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 4057: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4058:     }
1.106     albertel 4059:     $request->print("<br />\n");
1.324     albertel 4060:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4061:     return $error_msg;
1.26      albertel 4062: }
1.44      ng       4063: #------------- end of section for handling csv file upload ---------
                   4064: #
                   4065: #-------------------------------------------------------------------
                   4066: #
1.122     ng       4067: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4068: #
                   4069: #--- Select a page/sequence and a student to grade
1.68      ng       4070: sub pickStudentPage {
                   4071:     my ($request) = shift;
                   4072: 
                   4073:     $request->print(<<LISTJAVASCRIPT);
                   4074: <script type="text/javascript" language="javascript">
                   4075: 
                   4076: function checkPickOne(formname) {
1.76      ng       4077:     if (radioSelection(formname.student) == null) {
1.68      ng       4078: 	alert("Please select the student you wish to grade.");
                   4079: 	return;
                   4080:     }
1.125     ng       4081:     ptr = pullDownSelection(formname.selectpage);
                   4082:     formname.page.value = formname["page"+ptr].value;
                   4083:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4084:     formname.submit();
                   4085: }
                   4086: 
                   4087: </script>
                   4088: LISTJAVASCRIPT
1.118     ng       4089:     &commonJSfunctions($request);
1.324     albertel 4090:     my ($symb) = &get_symb($request);
1.257     albertel 4091:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4092:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4093:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4094: 
1.398     albertel 4095:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485   ! albertel 4096: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4097: 
1.80      ng       4098:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4099:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4100:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4101: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4102: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485   ! albertel 4103:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4104:     my $ctr=0;
1.68      ng       4105:     foreach (@$titles) {
                   4106: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485   ! albertel 4107: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4108: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4109: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4110: 	$ctr++;
1.68      ng       4111:     }
1.485   ! albertel 4112:     $select.= '</select>';
        !          4113:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
        !          4114: 
1.70      ng       4115:     $ctr=0;
                   4116:     foreach (@$titles) {
                   4117: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4118: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4119: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4120: 	$ctr++;
                   4121:     }
1.72      ng       4122:     $result.='<input type="hidden" name="page" />'."\n".
                   4123: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4124: 
1.485   ! albertel 4125:     my $options =
        !          4126: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
        !          4127: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
        !          4128:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
        !          4129: 
        !          4130:     $options =
        !          4131: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
        !          4132: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
        !          4133: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
        !          4134:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4135:     
                   4136:     $result.=&build_section_inputs();
1.442     banghart 4137:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4138:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4139: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4140: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4141: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4142: 
1.485   ! albertel 4143:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
        !          4144: 			  '<input type="text" name="CODE" value="" />').
        !          4145: 			      '<br />'."\n";
1.382     albertel 4146: 
1.80      ng       4147:     $result.='&nbsp;<input type="button" '.
1.485   ! albertel 4148: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4149: 
1.68      ng       4150:     $request->print($result);
                   4151: 
1.485   ! albertel 4152:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4153: 	&Apache::loncommon::start_data_table().
                   4154: 	&Apache::loncommon::start_data_table_header_row().
1.485   ! albertel 4155: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4156: 	'<th>'.&nameUserString('header').'</th>'.
1.485   ! albertel 4157: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4158: 	'<th>'.&nameUserString('header').'</th>'.
                   4159: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4160:  
1.76      ng       4161:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4162:     my $ptr = 1;
1.294     albertel 4163:     foreach my $student (sort 
                   4164: 			 {
                   4165: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4166: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4167: 			     }
                   4168: 			     return $a cmp $b;
                   4169: 			 } (keys(%$fullname))) {
1.68      ng       4170: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4171: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4172:                                   : '</td>');
1.126     ng       4173: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4174: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4175: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4176: 	$studentTable.=
                   4177: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4178:                          : '');
1.68      ng       4179: 	$ptr++;
                   4180:     }
1.484     albertel 4181:     if ($ptr%2 == 0) {
                   4182: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4183: 	    &Apache::loncommon::end_data_table_row();
                   4184:     }
                   4185:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4186:     $studentTable.='<input type="button" '.
1.485   ! albertel 4187: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4188: 
1.324     albertel 4189:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4190:     $request->print($studentTable);
                   4191: 
                   4192:     return '';
                   4193: }
                   4194: 
                   4195: sub getSymbMap {
1.132     bowersj2 4196:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4197: 
                   4198:     my %symbx = ();
                   4199:     my @titles = ();
1.117     bowersj2 4200:     my $minder = 0;
                   4201: 
                   4202:     # Gather every sequence that has problems.
1.240     albertel 4203:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4204: 					       1,0,1);
1.117     bowersj2 4205:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4206: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4207: 	    my $title = $minder.'.'.
                   4208: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4209: 	    push(@titles, $title); # minder in case two titles are identical
                   4210: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4211: 	    $minder++;
1.241     albertel 4212: 	}
1.68      ng       4213:     }
                   4214:     return \@titles,\%symbx;
                   4215: }
                   4216: 
1.72      ng       4217: #
                   4218: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4219: sub displayPage {
                   4220:     my ($request) = shift;
                   4221: 
1.324     albertel 4222:     my ($symb) = &get_symb($request);
1.257     albertel 4223:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4224:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4225:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4226:     my $pageTitle = $env{'form.page'};
1.103     albertel 4227:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4228:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4229:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4230: 
                   4231:     #need to make sure we have the correct data for later EXT calls, 
                   4232:     #thus invalidate the cache
                   4233:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4234:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4235:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4236:     &Apache::lonnet::clear_EXT_cache_status();
                   4237: 
1.103     albertel 4238:     if (!&canview($usec)) {
1.485   ! albertel 4239: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4240: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4241: 	return;
                   4242:     }
1.398     albertel 4243:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485   ! albertel 4244:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4245: 	'</h3>'."\n";
1.382     albertel 4246:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
1.485   ! albertel 4247: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4248:     } else {
                   4249: 	delete($env{'form.CODE'});
                   4250:     }
1.71      ng       4251:     &sub_page_js($request);
                   4252:     $request->print($result);
                   4253: 
1.132     bowersj2 4254:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4255:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4256:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4257:     if (!$map) {
1.485   ! albertel 4258: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4259: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4260: 	return; 
                   4261:     }
1.68      ng       4262:     my $iterator = $navmap->getIterator($map->map_start(),
                   4263: 					$map->map_finish());
                   4264: 
1.71      ng       4265:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4266: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4267: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4268: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4269: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4270: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4271: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4272: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4273: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4274: 
1.382     albertel 4275:     if (defined($env{'form.CODE'})) {
                   4276: 	$studentTable.=
                   4277: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4278:     }
1.381     albertel 4279:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485   ! albertel 4280: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4281: 
1.485   ! albertel 4282:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4283: 	&Apache::loncommon::start_data_table().
                   4284: 	&Apache::loncommon::start_data_table_header_row().
                   4285: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485   ! albertel 4286: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4287: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4288: 
1.329     albertel 4289:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4290:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4291:     $iterator->next(); # skip the first BEGIN_MAP
                   4292:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4293:     while ($depth > 0) {
1.68      ng       4294:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4295:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4296: 
1.385     albertel 4297:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4298: 	    my $parts = $curRes->parts();
1.68      ng       4299:             my $title = $curRes->compTitle();
1.71      ng       4300: 	    my $symbx = $curRes->symb();
1.484     albertel 4301: 	    $studentTable.=
                   4302: 		&Apache::loncommon::start_data_table_row().
                   4303: 		'<td align="center" valign="top" >'.$prob.
1.485   ! albertel 4304: 		(scalar(@{$parts}) == 1 ? '' 
        !          4305: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
        !          4306: 							scalar(@{$parts}))
        !          4307: 		 ).
        !          4308: 		 '</td>';
1.71      ng       4309: 	    $studentTable.='<td valign="top">';
1.382     albertel 4310: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4311: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4312: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4313: 					     undef,'both',\%form);
1.71      ng       4314: 	    } else {
1.382     albertel 4315: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4316: 		$companswer =~ s|<form(.*?)>||g;
                   4317: 		$companswer =~ s|</form>||g;
1.71      ng       4318: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4319: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4320: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4321: #		}
1.116     ng       4322: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485   ! albertel 4323: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4324: 	    }
                   4325: 
1.257     albertel 4326: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4327: 
1.257     albertel 4328: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4329: 		if ($record{'version'} eq '') {
1.485   ! albertel 4330: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4331: 		} else {
1.116     ng       4332: 		    my %responseType = ();
                   4333: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4334: 			my @responseIds =$curRes->responseIds($partid);
                   4335: 			my @responseType =$curRes->responseType($partid);
                   4336: 			my %responseIds;
                   4337: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4338: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4339: 			}
                   4340: 			$responseType{$partid} = \%responseIds;
1.116     ng       4341: 		    }
1.148     albertel 4342: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4343: 
1.71      ng       4344: 		}
1.257     albertel 4345: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4346: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4347: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4348: 									$env{'request.course.id'},
1.71      ng       4349: 									'','.submission');
                   4350:  
                   4351: 	    }
1.103     albertel 4352: 	    if (&canmodify($usec)) {
                   4353: 		foreach my $partid (@{$parts}) {
                   4354: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4355: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4356: 		    $question++;
                   4357: 		}
1.196     albertel 4358: 		$prob++;
1.71      ng       4359: 	    }
                   4360: 	    $studentTable.='</td></tr>';
1.68      ng       4361: 
1.103     albertel 4362: 	}
1.68      ng       4363:         $curRes = $iterator->next();
                   4364:     }
                   4365: 
1.485   ! albertel 4366:     $studentTable.='</table>'."\n".
        !          4367: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4368: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4369: 	'</form>'."\n";
1.324     albertel 4370:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4371:     $request->print($studentTable);
                   4372: 
                   4373:     return '';
1.119     ng       4374: }
                   4375: 
                   4376: sub displaySubByDates {
1.148     albertel 4377:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4378:     my $isCODE=0;
1.335     albertel 4379:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4380:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4381:     my $studentTable=&Apache::loncommon::start_data_table().
                   4382: 	&Apache::loncommon::start_data_table_header_row().
                   4383: 	'<th>'.&mt('Date/Time').'</th>'.
                   4384: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4385: 	'<th>'.&mt('Submission').'</th>'.
                   4386: 	'<th>'.&mt('Status').'</th>'.
                   4387: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4388:     my ($version);
                   4389:     my %mark;
1.148     albertel 4390:     my %orders;
1.119     ng       4391:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4392:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4393: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4394:     }
1.335     albertel 4395: 
                   4396:     my $interaction;
1.119     ng       4397:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4398: 	my $timestamp = 
                   4399: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4400: 	if (exists($$record{$version.':resource.0.version'})) {
                   4401: 	    $interaction = $$record{$version.':resource.0.version'};
                   4402: 	}
                   4403: 
                   4404: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4405: 		             : "$version:resource");
1.467     albertel 4406: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4407: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4408: 	if ($isCODE) {
                   4409: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4410: 	}
1.119     ng       4411: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4412: 	my @displaySub = ();
                   4413: 	foreach my $partid (@{$parts}) {
1.335     albertel 4414: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4415: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4416: 	    
                   4417: 
1.122     ng       4418: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4419: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4420: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4421: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4422: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4423: 
                   4424: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4425: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4426: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4427: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4428: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4429: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4430: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4431: 		    } else {
1.467     albertel 4432: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4433: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4434: 		    }
1.335     albertel 4435: 		    my $responseType=($isTask ? 'Task'
                   4436:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4437: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4438: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4439: 			$orders{$partid}->{$responseId}=
                   4440: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4441: 		    }
1.147     albertel 4442: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4443: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4444: 		}
                   4445: 	    }
1.335     albertel 4446: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485   ! albertel 4447: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
        !          4448: 				    $$record{"$where.$partid.checkedin"},
        !          4449: 				    $$record{"$where.$partid.checkedin.slot"}).
        !          4450: 					'<br />';
1.335     albertel 4451: 	    }
                   4452: 	    if (exists $$record{"$where.$partid.award"}) {
1.485   ! albertel 4453: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4454: 		    lc($$record{"$where.$partid.award"}).' '.
                   4455: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4456: 		    '<br />';
                   4457: 	    }
1.335     albertel 4458: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4459: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4460: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4461: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4462: 		$displaySub[2].=
                   4463: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4464: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4465: 	    }
                   4466: 	}
                   4467: 	# needed because old essay regrader has not parts info
                   4468: 	if (exists $$record{"$version:resource.regrader"}) {
                   4469: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4470: 	}
                   4471: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4472: 	if ($displaySub[2]) {
1.467     albertel 4473: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4474: 	}
1.467     albertel 4475: 	$studentTable.='&nbsp;</td>'.
                   4476: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4477:     }
1.467     albertel 4478:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4479:     return $studentTable;
1.71      ng       4480: }
                   4481: 
                   4482: sub updateGradeByPage {
                   4483:     my ($request) = shift;
                   4484: 
1.257     albertel 4485:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4486:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4487:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4488:     my $pageTitle = $env{'form.page'};
1.103     albertel 4489:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4490:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4491:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4492:     if (!&canmodify($usec)) {
1.398     albertel 4493: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4494: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4495: 	return;
                   4496:     }
1.398     albertel 4497:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4498:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4499: 	'</h3>'."\n";
1.70      ng       4500: 
1.68      ng       4501:     $request->print($result);
                   4502: 
1.132     bowersj2 4503:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4504:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4505:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4506:     if (!$map) {
1.398     albertel 4507: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4508: 	my ($symb)=&get_symb($request);
                   4509: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4510: 	return; 
                   4511:     }
1.71      ng       4512:     my $iterator = $navmap->getIterator($map->map_start(),
                   4513: 					$map->map_finish());
1.70      ng       4514: 
1.484     albertel 4515:     my $studentTable=
                   4516: 	&Apache::loncommon::start_data_table().
                   4517: 	&Apache::loncommon::start_data_table_header_row().
1.485   ! albertel 4518: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
        !          4519: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
        !          4520: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
        !          4521: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4522: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4523: 
                   4524:     $iterator->next(); # skip the first BEGIN_MAP
                   4525:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4526:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4527:     while ($depth > 0) {
1.71      ng       4528:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4529:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4530: 
1.385     albertel 4531:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4532: 	    my $parts = $curRes->parts();
1.71      ng       4533:             my $title = $curRes->compTitle();
                   4534: 	    my $symbx = $curRes->symb();
1.484     albertel 4535: 	    $studentTable.=
                   4536: 		&Apache::loncommon::start_data_table_row().
                   4537: 		'<td align="center" valign="top" >'.$prob.
1.485   ! albertel 4538: 		(scalar(@{$parts}) == 1 ? '' 
        !          4539:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
        !          4540: 		 ).')</td>';
1.71      ng       4541: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4542: 
                   4543: 	    my %newrecord=();
                   4544: 	    my @displayPts=();
1.269     raeburn  4545:             my %aggregate = ();
                   4546:             my $aggregateflag = 0;
1.71      ng       4547: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4548: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4549: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4550: 
1.257     albertel 4551: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4552: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4553: 		my $partial = $newpts/$wgt;
                   4554: 		my $score;
                   4555: 		if ($partial > 0) {
                   4556: 		    $score = 'correct_by_override';
1.125     ng       4557: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4558: 		    $score = 'incorrect_by_override';
                   4559: 		}
1.257     albertel 4560: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4561: 		if ($dropMenu eq 'excused') {
1.71      ng       4562: 		    $partial = '';
                   4563: 		    $score = 'excused';
1.125     ng       4564: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4565: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4566: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4567: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4568: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4569: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4570: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4571: 		    $changeflag++;
                   4572: 		    $newpts = '';
1.269     raeburn  4573:                     
                   4574:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4575:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4576:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4577:                     if ($aggtries > 0) {
                   4578:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4579:                         $aggregateflag = 1;
                   4580:                     }
1.71      ng       4581: 		}
1.324     albertel 4582: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4583: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4584: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4585: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4586: 		    '&nbsp;<br />';
1.207     albertel 4587: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4588: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4589: 		    '&nbsp;<br />';
1.71      ng       4590: 		$question++;
1.380     albertel 4591: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4592: 
1.71      ng       4593: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4594: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4595: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4596: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4597: 
                   4598: 		$changeflag++;
                   4599: 	    }
                   4600: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4601: 		my %record = 
                   4602: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4603: 					     $udom,$uname);
                   4604: 
                   4605: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4606: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4607: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4608: 		    $newrecord{'resource.CODE'} = '';
                   4609: 		}
1.257     albertel 4610: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4611: 					$udom,$uname);
1.382     albertel 4612: 		%record = &Apache::lonnet::restore($symbx,
                   4613: 						   $env{'request.course.id'},
                   4614: 						   $udom,$uname);
1.380     albertel 4615: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4616: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4617: 	    }
1.380     albertel 4618: 	    
1.269     raeburn  4619:             if ($aggregateflag) {
                   4620:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4621:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4622:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4623:             }
1.125     ng       4624: 
1.71      ng       4625: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4626: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4627: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4628: 
1.196     albertel 4629: 	    $prob++;
1.68      ng       4630: 	}
1.71      ng       4631:         $curRes = $iterator->next();
1.68      ng       4632:     }
1.98      albertel 4633: 
1.484     albertel 4634:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4635:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4636:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4637: 		  'The scores were changed for '.
                   4638: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4639:     $request->print($grademsg.$studentTable);
1.68      ng       4640: 
1.70      ng       4641:     return '';
                   4642: }
                   4643: 
1.72      ng       4644: #-------- end of section for handling grading by page/sequence ---------
                   4645: #
                   4646: #-------------------------------------------------------------------
                   4647: 
1.75      albertel 4648: #--------------------Scantron Grading-----------------------------------
                   4649: #
                   4650: #------ start of section for handling grading by page/sequence ---------
                   4651: 
1.423     albertel 4652: =pod
                   4653: 
                   4654: =head1 Bubble sheet grading routines
                   4655: 
1.424     albertel 4656:   For this documentation:
                   4657: 
                   4658:    'scanline' refers to the full line of characters
                   4659:    from the file that we are parsing that represents one entire sheet
                   4660: 
                   4661:    'bubble line' refers to the data
                   4662:    representing the line of bubbles that are on the physical bubble sheet
                   4663: 
                   4664: 
                   4665: The overall process is that a scanned in bubble sheet data is uploaded
                   4666: into a course. When a user wants to grade, they select a
                   4667: sequence/folder of resources, a file of bubble sheet info, and pick
                   4668: one of the predefined configurations for what each scanline looks
                   4669: like.
                   4670: 
                   4671: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4672: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4673: because too light bubbling), 'double bubble' (each bubble line should
                   4674: have no more that one letter picked), invalid or duplicated CODE,
                   4675: invalid student ID
                   4676: 
                   4677: If the CODE option is used that determines the randomization of the
                   4678: homework problems, either way the student ID is looked up into a
                   4679: username:domain.
                   4680: 
                   4681: During the validation phase the instructor can choose to skip scanlines. 
                   4682: 
1.435     foxr     4683: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4684: 
                   4685:   scantron_original_filename (unmodified original file)
                   4686:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4687:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4688: 
                   4689: Also there is a separate hash nohist_scantrondata that contains extra
                   4690: correction information that isn't representable in the bubble sheet
                   4691: file (see &scantron_getfile() for more information)
                   4692: 
                   4693: After all scanlines are either valid, marked as valid or skipped, then
                   4694: foreach line foreach problem in the picked sequence, an ssi request is
                   4695: made that simulates a user submitting their selected letter(s) against
                   4696: the homework problem.
1.423     albertel 4697: 
                   4698: =over 4
                   4699: 
                   4700: 
                   4701: 
                   4702: =item defaultFormData
                   4703: 
                   4704:   Returns html hidden inputs used to hold context/default values.
                   4705: 
                   4706:  Arguments:
                   4707:   $symb - $symb of the current resource 
                   4708: 
                   4709: =cut
1.422     foxr     4710: 
1.81      albertel 4711: sub defaultFormData {
1.324     albertel 4712:     my ($symb)=@_;
1.447     foxr     4713:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4714:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4715:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4716: }
                   4717: 
1.447     foxr     4718: 
1.423     albertel 4719: =pod 
                   4720: 
                   4721: =item getSequenceDropDown
                   4722: 
                   4723:    Return html dropdown of possible sequences to grade
                   4724:  
                   4725:  Arguments:
                   4726:    $symb - $symb of the current resource 
                   4727: 
                   4728: =cut
1.422     foxr     4729: 
1.75      albertel 4730: sub getSequenceDropDown {
1.423     albertel 4731:     my ($symb)=@_;
1.75      albertel 4732:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4733:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4734:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4735:     my $ctr=0;
                   4736:     foreach (@$titles) {
                   4737: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4738: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4739: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4740: 	    '>'.$showtitle.'</option>'."\n";
                   4741: 	$ctr++;
                   4742:     }
                   4743:     $result.= '</select>';
                   4744:     return $result;
                   4745: }
                   4746: 
1.423     albertel 4747: 
                   4748: =pod 
                   4749: 
                   4750: =item scantron_filenames
                   4751: 
                   4752:    Returns a list of the scantron files in the current course 
                   4753: 
                   4754: =cut
1.422     foxr     4755: 
1.202     albertel 4756: sub scantron_filenames {
1.257     albertel 4757:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4758:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4759:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4760: 				    &propath($cdom,$cname));
1.202     albertel 4761:     my @possiblenames;
1.201     albertel 4762:     foreach my $filename (sort(@files)) {
1.157     albertel 4763: 	($filename)=split(/&/,$filename);
                   4764: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4765: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4766: 	push(@possiblenames,$filename);
                   4767:     }
                   4768:     return @possiblenames;
                   4769: }
                   4770: 
1.423     albertel 4771: =pod 
                   4772: 
                   4773: =item scantron_uploads
                   4774: 
                   4775:    Returns  html drop-down list of scantron files in current course.
                   4776: 
                   4777:  Arguments:
                   4778:    $file2grade - filename to set as selected in the dropdown
                   4779: 
                   4780: =cut
1.422     foxr     4781: 
1.202     albertel 4782: sub scantron_uploads {
1.209     ng       4783:     my ($file2grade) = @_;
1.202     albertel 4784:     my $result=	'<select name="scantron_selectfile">';
                   4785:     $result.="<option></option>";
                   4786:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4787: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4788:     }
                   4789:     $result.="</select>";
                   4790:     return $result;
                   4791: }
                   4792: 
1.423     albertel 4793: =pod 
                   4794: 
                   4795: =item scantron_scantab
                   4796: 
                   4797:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4798:   file.
                   4799: 
                   4800: =cut
1.422     foxr     4801: 
1.82      albertel 4802: sub scantron_scantab {
                   4803:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4804:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4805:     $result.='<option></option>'."\n";
1.82      albertel 4806:     foreach my $line (<$fh>) {
                   4807: 	my ($name,$descrip)=split(/:/,$line);
                   4808: 	if ($name =~ /^\#/) { next; }
                   4809: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4810:     }
                   4811:     $result.='</select>'."\n";
                   4812: 
                   4813:     return $result;
                   4814: }
                   4815: 
1.423     albertel 4816: =pod 
                   4817: 
                   4818: =item scantron_CODElist
                   4819: 
                   4820:   Returns html drop down of the saved CODE lists from current course,
                   4821:   generated from earlier printings.
                   4822: 
                   4823: =cut
1.422     foxr     4824: 
1.186     albertel 4825: sub scantron_CODElist {
1.257     albertel 4826:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4827:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4828:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4829:     my $namechoice='<option></option>';
1.225     albertel 4830:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4831: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4832: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4833: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4834:     }
                   4835:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4836:     return $namechoice;
                   4837: }
                   4838: 
1.423     albertel 4839: =pod 
                   4840: 
                   4841: =item scantron_CODEunique
                   4842: 
                   4843:   Returns the html for "Each CODE to be used once" radio.
                   4844: 
                   4845: =cut
1.422     foxr     4846: 
1.186     albertel 4847: sub scantron_CODEunique {
1.381     albertel 4848:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4849:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4850:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4851:                 </span>
                   4852:                 <span style="white-space: nowrap;">
1.272     albertel 4853:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4854:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4855:                 </span>';
1.186     albertel 4856:     return $result;
                   4857: }
1.423     albertel 4858: 
                   4859: =pod 
                   4860: 
                   4861: =item scantron_selectphase
                   4862: 
                   4863:   Generates the initial screen to start the bubble sheet process.
                   4864:   Allows for - starting a grading run.
1.424     albertel 4865:              - downloading existing scan data (original, corrected
1.423     albertel 4866:                                                 or skipped info)
                   4867: 
                   4868:              - uploading new scan data
                   4869: 
                   4870:  Arguments:
                   4871:   $r          - The Apache request object
                   4872:   $file2grade - name of the file that contain the scanned data to score
                   4873: 
                   4874: =cut
1.186     albertel 4875: 
1.75      albertel 4876: sub scantron_selectphase {
1.209     ng       4877:     my ($r,$file2grade) = @_;
1.324     albertel 4878:     my ($symb)=&get_symb($r);
1.75      albertel 4879:     if (!$symb) {return '';}
1.423     albertel 4880:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4881:     my $default_form_data=&defaultFormData($symb);
                   4882:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4883:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4884:     my $format_selector=&scantron_scantab();
1.186     albertel 4885:     my $CODE_selector=&scantron_CODElist();
                   4886:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4887:     my $result;
1.422     foxr     4888: 
                   4889:     # Chunk of form to prompt for a file to grade and how:
                   4890: 
1.75      albertel 4891:     $result.= <<SCANTRONFORM;
1.162     albertel 4892:     <table width="100%" border="0">
1.75      albertel 4893:     <tr>
1.226     albertel 4894:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4895:       <td bgcolor="#777777">
1.203     albertel 4896:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4897:         $default_form_data
1.75      albertel 4898:         <table width="100%" border="0">
                   4899:           <tr bgcolor="#e6ffff">
1.174     albertel 4900:             <td colspan="2">
                   4901:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4902:             </td>
                   4903:           </tr>
                   4904:           <tr bgcolor="#ffffe6">
1.174     albertel 4905:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4906:           </tr>
                   4907:           <tr bgcolor="#ffffe6">
1.174     albertel 4908:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4909:           </tr>
1.82      albertel 4910:           <tr bgcolor="#ffffe6">
1.174     albertel 4911:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4912:           </tr>
1.157     albertel 4913:           <tr bgcolor="#ffffe6">
1.186     albertel 4914:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4915:           </tr>
                   4916:           <tr bgcolor="#ffffe6">
                   4917:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4918:           </tr>
                   4919:           <tr bgcolor="#ffffe6">
1.187     albertel 4920: 	    <td> Options: </td>
                   4921:             <td>
1.272     albertel 4922: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4923:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4924:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4925: 	    </td>
                   4926:           </tr>
                   4927:           <tr bgcolor="#ffffe6">
1.174     albertel 4928:             <td colspan="2">
1.265     www      4929:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4930:             </td>
                   4931:           </tr>
                   4932:         </table>
1.226     albertel 4933:        </td>
                   4934:      </form>
1.162     albertel 4935:     </tr>
                   4936: SCANTRONFORM
                   4937:    
                   4938:     $r->print($result);
                   4939: 
1.257     albertel 4940:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4941:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4942: 
1.422     foxr     4943: 	# Chunk of form to prompt for a scantron file upload.
                   4944: 
1.162     albertel 4945:         $r->print(<<SCANTRONFORM);
                   4946:     <tr>
                   4947:       <td bgcolor="#777777">
                   4948:         <table width="100%" border="0">
                   4949:           <tr bgcolor="#e6ffff">
                   4950:             <td>
1.174     albertel 4951:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4952:             </td>
                   4953:           </tr>
                   4954:           <tr bgcolor="#ffffe6">
                   4955:             <td>
                   4956: SCANTRONFORM
1.324     albertel 4957:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4958:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4959:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4960:     $r->print(<<UPLOAD);
                   4961:               <script type="text/javascript" language="javascript">
                   4962:     function checkUpload(formname) {
                   4963: 	if (formname.upfile.value == "") {
                   4964: 	    alert("Please use the browse button to select a file from your local directory.");
                   4965: 	    return false;
                   4966: 	}
                   4967: 	formname.submit();
                   4968:     }
                   4969:               </script>
                   4970: 
                   4971:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4972:                 $default_form_data
                   4973:                 <input name='courseid' type='hidden' value='$cnum' />
                   4974:                 <input name='domainid' type='hidden' value='$cdom' />
                   4975:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4976:                 File to upload:<input type="file" name="upfile" size="50" />
                   4977:                 <br />
                   4978:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4979:               </form>
                   4980: UPLOAD
1.162     albertel 4981: 
                   4982:         $r->print(<<SCANTRONFORM);
                   4983:             </td>
                   4984:           </tr>
1.75      albertel 4985:         </table>
                   4986:       </td>
                   4987:     </tr>
1.162     albertel 4988: SCANTRONFORM
                   4989:     }
1.422     foxr     4990: 
                   4991:     # Chunk of the form that prompts to view a scoring office file,
                   4992:     # corrected file, skipped records in a file.
                   4993: 
1.187     albertel 4994:     $r->print(<<SCANTRONFORM);
                   4995:     <tr>
1.226     albertel 4996:       <form action='/adm/grades' name='scantron_download'>
                   4997:         <td bgcolor="#777777">
1.379     albertel 4998: 	  $default_form_data
1.187     albertel 4999:           <input type="hidden" name="command" value="scantron_download" />
                   5000:           <table width="100%" border="0">
                   5001:             <tr bgcolor="#e6ffff">
                   5002:               <td colspan="2">
                   5003:                 &nbsp;<b>Download a scoring office file</b>
                   5004:               </td>
                   5005:             </tr>
                   5006:             <tr bgcolor="#ffffe6">
                   5007:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   5008:             </tr>
                   5009:             <tr bgcolor="#ffffe6">
                   5010:               <td colspan="2">
1.293     www      5011:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 5012:               </td>
                   5013:             </tr>
                   5014:           </table>
1.226     albertel 5015:         </td>
                   5016:       </form>
1.187     albertel 5017:     </tr>
                   5018: SCANTRONFORM
1.162     albertel 5019: 
1.457     banghart 5020:     $r->print('<tr><td bgcolor="#777777">');
                   5021:     &Apache::lonpickcode::code_list($r,2);
                   5022:     $r->print('</td></tr></table>');
                   5023:     $r->print($grading_menu_button);
1.162     albertel 5024:     return
1.75      albertel 5025: }
                   5026: 
1.423     albertel 5027: =pod
                   5028: 
                   5029: =item get_scantron_config
                   5030: 
                   5031:    Parse and return the scantron configuration line selected as a
                   5032:    hash of configuration file fields.
                   5033: 
                   5034:  Arguments:
                   5035:     which - the name of the configuration to parse from the file.
                   5036: 
                   5037: 
                   5038:  Returns:
                   5039:             If the named configuration is not in the file, an empty
                   5040:             hash is returned.
                   5041:     a hash with the fields
                   5042:       name         - internal name for the this configuration setup
                   5043:       description  - text to display to operator that describes this config
                   5044:       CODElocation - if 0 or the string 'none'
                   5045:                           - no CODE exists for this config
                   5046:                      if -1 || the string 'letter'
                   5047:                           - a CODE exists for this config and is
                   5048:                             a string of letters
                   5049:                      Unsupported value (but planned for future support)
                   5050:                           if a positive integer
                   5051:                                - The CODE exists as the first n items from
                   5052:                                  the question section of the form
                   5053:                           if the string 'number'
                   5054:                                - The CODE exists for this config and is
                   5055:                                  a string of numbers
                   5056:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5057:                      the CODE starts
                   5058:       CODElength  - length of the CODE
                   5059:       IDstart     - column where the student ID number starts
                   5060:       IDlength    - length of the student ID info
                   5061:       Qstart      - column where the information from the bubbled
                   5062:                     'questions' start
                   5063:       Qlength     - number of columns comprising a single bubble line from
                   5064:                     the sheet. (usually either 1 or 10)
1.424     albertel 5065:       Qon         - either a single character representing the character used
1.423     albertel 5066:                     to signal a bubble was chosen in the positional setup, or
                   5067:                     the string 'letter' if the letter of the chosen bubble is
                   5068:                     in the final, or 'number' if a number representing the
                   5069:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5070:       Qoff        - the character used to represent that a bubble was
                   5071:                     left blank
1.423     albertel 5072:       PaperID     - if the scanning process generates a unique number for each
                   5073:                     sheet scanned the column that this ID number starts in
                   5074:       PaperIDlength - number of columns that comprise the unique ID number
                   5075:                       for the sheet of paper
1.424     albertel 5076:       FirstName   - column that the first name starts in
1.423     albertel 5077:       FirstNameLength - number of columns that the first name spans
                   5078:  
                   5079:       LastName    - column that the last name starts in
                   5080:       LastNameLength - number of columns that the last name spans
                   5081: 
                   5082: =cut
1.422     foxr     5083: 
1.82      albertel 5084: sub get_scantron_config {
                   5085:     my ($which) = @_;
                   5086:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5087:     my %config;
1.157     albertel 5088:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5089:     foreach my $line (<$fh>) {
                   5090: 	my ($name,$descrip)=split(/:/,$line);
                   5091: 	if ($name ne $which ) { next; }
                   5092: 	chomp($line);
                   5093: 	my @config=split(/:/,$line);
                   5094: 	$config{'name'}=$config[0];
                   5095: 	$config{'description'}=$config[1];
                   5096: 	$config{'CODElocation'}=$config[2];
                   5097: 	$config{'CODEstart'}=$config[3];
                   5098: 	$config{'CODElength'}=$config[4];
                   5099: 	$config{'IDstart'}=$config[5];
                   5100: 	$config{'IDlength'}=$config[6];
                   5101: 	$config{'Qstart'}=$config[7];
                   5102: 	$config{'Qlength'}=$config[8];
                   5103: 	$config{'Qoff'}=$config[9];
                   5104: 	$config{'Qon'}=$config[10];
1.157     albertel 5105: 	$config{'PaperID'}=$config[11];
                   5106: 	$config{'PaperIDlength'}=$config[12];
                   5107: 	$config{'FirstName'}=$config[13];
                   5108: 	$config{'FirstNamelength'}=$config[14];
                   5109: 	$config{'LastName'}=$config[15];
                   5110: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5111: 	last;
                   5112:     }
                   5113:     return %config;
                   5114: }
                   5115: 
1.423     albertel 5116: =pod 
                   5117: 
                   5118: =item username_to_idmap
                   5119: 
                   5120:     creates a hash keyed by student id with values of the corresponding
                   5121:     student username:domain.
                   5122: 
                   5123:   Arguments:
                   5124: 
                   5125:     $classlist - reference to the class list hash. This is a hash
                   5126:                  keyed by student name:domain  whose elements are references
1.424     albertel 5127:                  to arrays containing various chunks of information
1.423     albertel 5128:                  about the student. (See loncoursedata for more info).
                   5129: 
                   5130:   Returns
                   5131:     %idmap - the constructed hash
                   5132: 
                   5133: =cut
                   5134: 
1.82      albertel 5135: sub username_to_idmap {
                   5136:     my ($classlist)= @_;
                   5137:     my %idmap;
                   5138:     foreach my $student (keys(%$classlist)) {
                   5139: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5140: 	    $student;
                   5141:     }
                   5142:     return %idmap;
                   5143: }
1.423     albertel 5144: 
                   5145: =pod
                   5146: 
1.424     albertel 5147: =item scantron_fixup_scanline
1.423     albertel 5148: 
                   5149:    Process a requested correction to a scanline.
                   5150: 
                   5151:   Arguments:
                   5152:     $scantron_config   - hash from &get_scantron_config()
                   5153:     $scan_data         - hash of correction information 
                   5154:                           (see &scantron_getfile())
                   5155:     $line              - existing scanline
                   5156:     $whichline         - line number of the passed in scanline
                   5157:     $field             - type of change to process 
                   5158:                          (either 
                   5159:                           'ID'     -> correct the student ID number
                   5160:                           'CODE'   -> correct the CODE
                   5161:                           'answer' -> fixup the submitted answers)
                   5162:     
                   5163:    $args               - hash of additional info,
                   5164:                           - 'ID' 
                   5165:                                'newid' -> studentID to use in replacement
1.424     albertel 5166:                                           of existing one
1.423     albertel 5167:                           - 'CODE' 
                   5168:                                'CODE_ignore_dup' - set to true if duplicates
                   5169:                                                    should be ignored.
                   5170: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5171:                                         if the existing unfound code should
1.423     albertel 5172:                                         be used as is
                   5173:                           - 'answer'
                   5174:                                'response' - new answer or 'none' if blank
                   5175:                                'question' - the bubble line to change
                   5176: 
                   5177:   Returns:
                   5178:     $line - the modified scanline
                   5179: 
                   5180:   Side effects: 
                   5181:     $scan_data - may be updated
                   5182: 
                   5183: =cut
                   5184: 
1.82      albertel 5185: 
1.157     albertel 5186: sub scantron_fixup_scanline {
                   5187:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.479     foxr     5188:     
                   5189:     
1.157     albertel 5190:     if ($field eq 'ID') {
                   5191: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5192: 	    return ($line,1,'New value too large');
1.157     albertel 5193: 	}
                   5194: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5195: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5196: 				     $args->{'newid'});
                   5197: 	}
                   5198: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5199: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5200: 	if ($args->{'newid'}=~/^\s*$/) {
                   5201: 	    &scan_data($scan_data,"$whichline.user",
                   5202: 		       $args->{'username'}.':'.$args->{'domain'});
                   5203: 	}
1.186     albertel 5204:     } elsif ($field eq 'CODE') {
1.192     albertel 5205: 	if ($args->{'CODE_ignore_dup'}) {
                   5206: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5207: 	}
                   5208: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5209: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5210: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5211: 		return ($line,1,'New CODE value too large');
                   5212: 	    }
                   5213: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5214: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5215: 	    }
                   5216: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5217: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5218: 	}
1.157     albertel 5219:     } elsif ($field eq 'answer') {
1.479     foxr     5220: 	&scantron_get_maxbubble(); # Need the bubble counter info.
1.482     foxr     5221: 	my $length =$scantron_config->{'Qlength'};
1.157     albertel 5222: 	my $off=$scantron_config->{'Qoff'};
                   5223: 	my $on=$scantron_config->{'Qon'};
1.479     foxr     5224:         my $question_number = $args->{'question'} -1;
                   5225:         my $first_position  = $first_bubble_line{$question_number};
                   5226: 	my $bubble_count    = $bubble_lines_per_response{$question_number};
                   5227:         my $bubbles_per_line= $$scantron_config{'Qlength'};
1.482     foxr     5228: 	my $answer=${off}x($bubbles_per_line*$bubble_count);
1.479     foxr     5229:         my $final_answer;
                   5230:         if ($$scantron_config{'Qon'} eq 'letter'  ||
                   5231: 	    $$scantron_config{'Qon'} eq 'number') { 
                   5232: 	    $bubbles_per_line = 10;
                   5233: 	}
                   5234: 	if (defined $args->{'response'}) {
                   5235: 	    
                   5236: 	    if ($args->{'response'} eq 'none') {
                   5237: 		&scan_data($scan_data,
                   5238: 			   "$whichline.no_bubble.".$args->{'question'},'1');
1.274     albertel 5239: 	    } else {
1.479     foxr     5240: 		my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
                   5241: 		if ($on eq 'letter') {
                   5242: 		    my @alphabet=('A'..'Z');
                   5243: 		    $answer=$alphabet[$bubble_number];
                   5244: 		} elsif ($on eq 'number') {
1.482     foxr     5245: 		    $answer= $bubble_number+1;
1.479     foxr     5246: 		    if ($answer == 10) { $answer = '0'; }
                   5247: 		} else {
1.482     foxr     5248: 		    substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
                   5249: 		    $final_answer = $answer;
1.479     foxr     5250: 		}
                   5251: 		&scan_data($scan_data,
                   5252: 			   "$whichline.no_bubble.".$args->{'question'},undef,'1');
1.482     foxr     5253: 		
                   5254: 		# Positional notation already has the right final answer length..
                   5255: 
                   5256: 		if (($on eq 'letter') || ($on eq 'number')) {
                   5257: 		    for (my $l = 0; $l < $bubble_count; $l++) {
                   5258: 			if ($l eq $bubble_line) {
                   5259: 			    $final_answer .= $answer;
                   5260: 			} else {
                   5261: 			    $final_answer .= ' ';
                   5262: 			}
1.479     foxr     5263: 		    }
                   5264: 		}
1.274     albertel 5265: 	    }
1.479     foxr     5266: 	    # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5267: 	    #substr($line,$where-1,$length)=$answer;
                   5268: 	    substr($line, 
                   5269: 		   $scantron_config->{'Qstart'}+$first_position-1,
1.482     foxr     5270: 		   $bubbles_per_line*$length) = $final_answer;
1.157     albertel 5271: 	}
                   5272:     }
                   5273:     return $line;
                   5274: }
1.423     albertel 5275: 
                   5276: =pod
                   5277: 
                   5278: =item scan_data
                   5279: 
                   5280:     Edit or look up  an item in the scan_data hash.
                   5281: 
                   5282:   Arguments:
                   5283:     $scan_data  - The hash (see scantron_getfile)
                   5284:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5285:                   scantronfilename_key).
1.423     albertel 5286:     $data        - New value of the hash entry.
                   5287:     $delete      - If true, the entry is removed from the hash.
                   5288: 
                   5289:   Returns:
                   5290:     The new value of the hash table field (undefined if deleted).
                   5291: 
                   5292: =cut
                   5293: 
                   5294: 
1.157     albertel 5295: sub scan_data {
                   5296:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5297:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5298:     if (defined($value)) {
                   5299: 	$scan_data->{$filename.'_'.$key} = $value;
                   5300:     }
                   5301:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5302:     return $scan_data->{$filename.'_'.$key};
                   5303: }
1.423     albertel 5304: 
                   5305: =pod 
                   5306: 
                   5307: =item scantron_parse_scanline
                   5308: 
                   5309:   Decodes a scanline from the selected scantron file
                   5310: 
                   5311:  Arguments:
                   5312:     line             - The text of the scantron file line to process
                   5313:     whichline        - Line number
                   5314:     scantron_config  - Hash describing the format of the scantron lines.
                   5315:     scan_data        - Hash of extra information about the scanline
                   5316:                        (see scantron_getfile for more information)
                   5317:     just_header      - True if should not process question answers but only
                   5318:                        the stuff to the left of the answers.
                   5319:  Returns:
                   5320:    Hash containing the result of parsing the scanline
                   5321: 
                   5322:    Keys are all proceeded by the string 'scantron.'
                   5323: 
                   5324:        CODE    - the CODE in use for this scanline
                   5325:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5326:                  by the operator
                   5327:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5328:                             CODEs were selected, but the usage has been
                   5329:                             forced by the operator
                   5330:        ID  - student ID
                   5331:        PaperID - if used, the ID number printed on the sheet when the 
                   5332:                  paper was scanned
                   5333:        FirstName - first name from the sheet
                   5334:        LastName  - last name from the sheet
                   5335: 
                   5336:      if just_header was not true these key may also exist
                   5337: 
1.447     foxr     5338:        missingerror - a list of bubble ranges that are considered to be answers
                   5339:                       to a single question that don't have any bubbles filled in.
                   5340:                       Of the form questionnumber:firstbubblenumber:count.
                   5341:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5342:                       to a single question that have more than one bubble filled in.
                   5343:                       Of the form questionnumber::firstbubblenumber:count
                   5344:    
                   5345:                 In the above, count is the number of bubble responses in the
                   5346:                 input line needed to represent the possible answers to the question.
                   5347:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5348:                 per line would have count = 2.
                   5349: 
1.423     albertel 5350:        maxquest     - the number of the last bubble line that was parsed
                   5351: 
                   5352:        (<number> starts at 1)
                   5353:        <number>.answer - zero or more letters representing the selected
                   5354:                          letters from the scanline for the bubble line 
                   5355:                          <number>.
                   5356:                          if blank there was either no bubble or there where
                   5357:                          multiple bubbles, (consult the keys missingerror and
                   5358:                          doubleerror if this is an error condition)
                   5359: 
                   5360: =cut
                   5361: 
1.82      albertel 5362: sub scantron_parse_scanline {
1.423     albertel 5363:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5364: 
1.82      albertel 5365:     my %record;
1.422     foxr     5366:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5367:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5368:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5369: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5370: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5371: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5372: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5373: 	    $record{'scantron.CODE'}=substr($data,
                   5374: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5375: 					    $$scantron_config{'CODElength'});
1.191     albertel 5376: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5377: 		$record{'scantron.useCODE'}=1;
                   5378: 	    }
1.192     albertel 5379: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5380: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5381: 	    }
1.82      albertel 5382: 	} else {
                   5383: 	    #FIXME interpret first N questions
                   5384: 	}
                   5385:     }
1.83      albertel 5386:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5387: 				  $$scantron_config{'IDlength'});
1.157     albertel 5388:     $record{'scantron.PaperID'}=
                   5389: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5390: 	       $$scantron_config{'PaperIDlength'});
                   5391:     $record{'scantron.FirstName'}=
                   5392: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5393: 	       $$scantron_config{'FirstNamelength'});
                   5394:     $record{'scantron.LastName'}=
                   5395: 	substr($data,$$scantron_config{'LastName'}-1,
                   5396: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5397:     if ($just_header) { return \%record; }
1.194     albertel 5398: 
1.82      albertel 5399:     my @alphabet=('A'..'Z');
                   5400:     my $questnum=0;
1.447     foxr     5401:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5402: 
1.470     foxr     5403:     chomp($questions);		# Get rid of any trailing \n.
                   5404:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5405:     while (length($questions)) {
1.447     foxr     5406: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5407: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5408: 
                   5409: 
                   5410: 
1.82      albertel 5411: 	$questnum++;
1.447     foxr     5412: 	my $currentquest = substr($questions,0,$answer_length);
                   5413: 	$questions       = substr($questions,0,$answer_length)='';
                   5414: 	if (length($currentquest) < $answer_length) { next; }
                   5415: 
                   5416: 	# Qon letter implies for each slot in currentquest we have:
                   5417: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5418:         #    about anything else (esp. a value of Qoff for missing
                   5419: 	#    bubbles.
                   5420: 
                   5421: 
1.239     albertel 5422: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5423: 
                   5424: 	    if ($currentquest =~ /\?/
                   5425: 		|| $currentquest =~ /\*/
                   5426: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5427: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5428: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5429: 		    my $bubble = substr($currentquest, $ans, 1);
                   5430: 		    if ($bubble =~ /[A-Z]/ ) {
                   5431: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5432: 		    } else {
                   5433: 			$record{"scantron.$ansnum.answer"}='';
                   5434: 		    }
1.447     foxr     5435: 		    $ansnum++;
                   5436: 		}
                   5437: 
1.389     albertel 5438: 	    } elsif (!defined($currentquest)
1.447     foxr     5439: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5440: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5441: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5442: 		    $record{"scantron.$ansnum.answer"}='';
                   5443: 		    $ansnum++;
                   5444: 
                   5445: 		}
1.239     albertel 5446: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5447: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5448: 		   #  $ansnum += $answers_needed;
1.239     albertel 5449: 		}
                   5450: 	    } else {
1.447     foxr     5451: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5452: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5453: 		    $ansnum++;
                   5454: 		}
1.239     albertel 5455: 	    }
1.447     foxr     5456: 
                   5457: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5458: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5459:         #    and *? for double bubbles on a line.
                   5460: 	#    these answers are also stored as letters.
                   5461: 
1.239     albertel 5462: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5463: 	    if ($currentquest =~ /\?/
                   5464: 		|| $currentquest =~ /\*/
                   5465: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5466: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5467: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5468: 		    my $bubble = substr($currentquest, $ans, 1);
                   5469: 		    if ($bubble =~ /\d/) {
                   5470: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5471: 		    } else {
1.461     foxr     5472: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5473: 		    }
1.447     foxr     5474: 		    $ansnum++;
                   5475: 		}
                   5476: 
1.389     albertel 5477: 	    } elsif (!defined($currentquest)
1.447     foxr     5478: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5479: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5480: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5481: 		    $record{"scantron.$ansnum.answer"}='';
                   5482: 		    $ansnum++;
                   5483: 
                   5484: 		}
1.239     albertel 5485: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5486: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5487: 		    $ansnum += $answers_needed;
1.239     albertel 5488: 		}
1.447     foxr     5489: 
1.239     albertel 5490: 	    } else {
1.447     foxr     5491: 		$currentquest = &digits_to_letters($currentquest);
                   5492: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5493: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5494: 		    $ansnum++;
1.371     albertel 5495: 		}
1.239     albertel 5496: 	    }
1.82      albertel 5497: 	} else {
1.447     foxr     5498: 
                   5499: 	    # Otherwise there's a positional notation;
                   5500: 	    # each bubble line requires Qlength items, and there are filled in
                   5501: 	    # bubbles for each case where there 'Qon' characters.
                   5502: 	    #
                   5503: 
1.239     albertel 5504: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5505: 
                   5506: 	    # If the split only  giveas us one element.. the full length of the
                   5507: 	    # answser string, no bubbles are filled in:
                   5508: 
                   5509: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5510: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5511: 		    $record{"scantron.$ansnum.answer"}='';
                   5512: 		    $ansnum++;
                   5513: 
                   5514: 		}
1.239     albertel 5515: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5516: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5517: 		}
1.482     foxr     5518: 		
                   5519: 		#  If the bubble is not the last position, there will be
                   5520: 		# 2 elements.  If it is the last position, there will be 1 element.
                   5521: 
                   5522: 	    } elsif (scalar(@array) le 2) {
1.447     foxr     5523: 
1.459     foxr     5524: 		my $location      = length($array[0]);
1.483     foxr     5525: 		my $line_num      = int($location / $$scantron_config{'Qlength'});
1.447     foxr     5526: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
1.483     foxr     5527: 		
1.447     foxr     5528: 
                   5529: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5530: 		    if ($ans eq $line_num) {
                   5531: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5532: 		    } else {
                   5533: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5534: 		    }
                   5535: 		    $ansnum++;
                   5536: 		}
1.239     albertel 5537: 	    }
1.447     foxr     5538: 	    #  If there's more than one instance of a bubble character
                   5539: 	    #  That's a double bubble; with positional notation we can
                   5540: 	    #  record all the bubbles filled in as well as the 
                   5541: 	    #  fact this response consists of multiple bubbles.
                   5542: 	    #
                   5543: 	    else {
1.239     albertel 5544: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5545: 
                   5546: 		my $first_answer = $ansnum;
                   5547: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5548: 		    my $item = $first_answer+$ans;
                   5549: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5550: 		}
                   5551: 
1.239     albertel 5552: 		my @ans=@array;
1.462     foxr     5553: 		my $i=0;
                   5554: 		my $increment = 0;
1.239     albertel 5555: 		while ($#ans) {
1.462     foxr     5556: 		    $i+=length($ans[0]) + $increment;
                   5557: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5558: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5559: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5560: 		    shift(@ans);
1.462     foxr     5561: 		    $increment = 1;
1.239     albertel 5562: 		}
1.462     foxr     5563: 		$ansnum += $answers_needed;
1.239     albertel 5564: 	    }
1.82      albertel 5565: 	}
                   5566:     }
1.83      albertel 5567:     $record{'scantron.maxquest'}=$questnum;
                   5568:     return \%record;
1.82      albertel 5569: }
                   5570: 
1.423     albertel 5571: =pod
                   5572: 
                   5573: =item scantron_add_delay
                   5574: 
                   5575:    Adds an error message that occurred during the grading phase to a
                   5576:    queue of messages to be shown after grading pass is complete
                   5577: 
                   5578:  Arguments:
1.424     albertel 5579:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5580:    $scanline    - the scanline that caused the error
                   5581:    $errormesage - the error message
                   5582:    $errorcode   - a numeric code for the error
                   5583: 
                   5584:  Side Effects:
1.424     albertel 5585:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5586: 
                   5587: =cut
                   5588: 
1.82      albertel 5589: sub scantron_add_delay {
1.140     albertel 5590:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5591:     push(@$delayqueue,
                   5592: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5593: 	  'ecode' => $errorcode }
                   5594: 	 );
1.82      albertel 5595: }
                   5596: 
1.423     albertel 5597: =pod
                   5598: 
                   5599: =item scantron_find_student
                   5600: 
1.424     albertel 5601:    Finds the username for the current scanline
                   5602: 
                   5603:   Arguments:
                   5604:    $scantron_record - hash result from scantron_parse_scanline
                   5605:    $scan_data       - hash of correction information 
                   5606:                       (see &scantron_getfile() form more information)
                   5607:    $idmap           - hash from &username_to_idmap()
                   5608:    $line            - number of current scanline
                   5609:  
                   5610:   Returns:
                   5611:    Either 'username:domain' or undef if unknown
                   5612: 
1.423     albertel 5613: =cut
                   5614: 
1.82      albertel 5615: sub scantron_find_student {
1.157     albertel 5616:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5617:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5618:     if ($scanID =~ /^\s*$/) {
                   5619:  	return &scan_data($scan_data,"$line.user");
                   5620:     }
1.83      albertel 5621:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5622:  	if (lc($id) eq lc($scanID)) {
                   5623:  	    return $$idmap{$id};
                   5624:  	}
1.83      albertel 5625:     }
                   5626:     return undef;
                   5627: }
                   5628: 
1.423     albertel 5629: =pod
                   5630: 
                   5631: =item scantron_filter
                   5632: 
1.424     albertel 5633:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5634:    hidden resources was selected
                   5635: 
1.423     albertel 5636: =cut
                   5637: 
1.83      albertel 5638: sub scantron_filter {
                   5639:     my ($curres)=@_;
1.331     albertel 5640: 
                   5641:     if (ref($curres) && $curres->is_problem()) {
                   5642: 	# if the user has asked to not have either hidden
                   5643: 	# or 'randomout' controlled resources to be graded
                   5644: 	# don't include them
                   5645: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5646: 	    && $curres->randomout) {
                   5647: 	    return 0;
                   5648: 	}
1.83      albertel 5649: 	return 1;
                   5650:     }
                   5651:     return 0;
1.82      albertel 5652: }
                   5653: 
1.423     albertel 5654: =pod
                   5655: 
                   5656: =item scantron_process_corrections
                   5657: 
1.424     albertel 5658:    Gets correction information out of submitted form data and corrects
                   5659:    the scanline
                   5660: 
1.423     albertel 5661: =cut
                   5662: 
1.157     albertel 5663: sub scantron_process_corrections {
                   5664:     my ($r) = @_;
1.257     albertel 5665:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5666:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5667:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5668:     my $which=$env{'form.scantron_line'};
1.200     albertel 5669:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5670:     my ($skip,$err,$errmsg);
1.257     albertel 5671:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5672: 	$skip=1;
1.257     albertel 5673:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5674: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5675: 	    $env{'form.scantron_domain'};
1.157     albertel 5676: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5677: 	($line,$err,$errmsg)=
                   5678: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5679: 				     'ID',{'newid'=>$newid,
1.257     albertel 5680: 				    'username'=>$env{'form.scantron_username'},
                   5681: 				    'domain'=>$env{'form.scantron_domain'}});
                   5682:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5683: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5684: 	my $newCODE;
1.192     albertel 5685: 	my %args;
1.190     albertel 5686: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5687: 	    $newCODE='use_unfound';
1.190     albertel 5688: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5689: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5690: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5691: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5692: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5693: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5694: 	}
1.257     albertel 5695: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5696: 	    $args{'CODE_ignore_dup'}=1;
                   5697: 	}
                   5698: 	$args{'CODE'}=$newCODE;
1.186     albertel 5699: 	($line,$err,$errmsg)=
                   5700: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5701: 				     'CODE',\%args);
1.257     albertel 5702:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5703: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5704: 	    ($line,$err,$errmsg)=
                   5705: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5706: 					 $which,'answer',
                   5707: 					 { 'question'=>$question,
1.257     albertel 5708: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5709: 	    if ($err) { last; }
                   5710: 	}
                   5711:     }
                   5712:     if ($err) {
1.398     albertel 5713: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5714:     } else {
1.200     albertel 5715: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5716: 	&scantron_putfile($scanlines,$scan_data);
                   5717:     }
                   5718: }
                   5719: 
1.423     albertel 5720: =pod
                   5721: 
                   5722: =item reset_skipping_status
                   5723: 
1.424     albertel 5724:    Forgets the current set of remember skipped scanlines (and thus
                   5725:    reverts back to considering all lines in the
                   5726:    scantron_skipped_<filename> file)
                   5727: 
1.423     albertel 5728: =cut
                   5729: 
1.200     albertel 5730: sub reset_skipping_status {
                   5731:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5732:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5733:     &scantron_putfile(undef,$scan_data);
                   5734: }
                   5735: 
1.423     albertel 5736: =pod
                   5737: 
                   5738: =item start_skipping
                   5739: 
1.424     albertel 5740:    Marks a scanline to be skipped. 
                   5741: 
1.423     albertel 5742: =cut
                   5743: 
1.376     albertel 5744: sub start_skipping {
1.200     albertel 5745:     my ($scan_data,$i)=@_;
                   5746:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5747:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5748: 	$remembered{$i}=2;
                   5749:     } else {
                   5750: 	$remembered{$i}=1;
                   5751:     }
1.200     albertel 5752:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5753: }
                   5754: 
1.423     albertel 5755: =pod
                   5756: 
                   5757: =item should_be_skipped
                   5758: 
1.424     albertel 5759:    Checks whether a scanline should be skipped.
                   5760: 
1.423     albertel 5761: =cut
                   5762: 
1.200     albertel 5763: sub should_be_skipped {
1.376     albertel 5764:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5765:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5766: 	# not redoing old skips
1.376     albertel 5767: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5768: 	return 0;
                   5769:     }
                   5770:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5771: 
                   5772:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5773: 	return 0;
                   5774:     }
1.200     albertel 5775:     return 1;
                   5776: }
                   5777: 
1.423     albertel 5778: =pod
                   5779: 
                   5780: =item remember_current_skipped
                   5781: 
1.424     albertel 5782:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5783:    file and remembers them into scan_data for later use.
                   5784: 
1.423     albertel 5785: =cut
                   5786: 
1.200     albertel 5787: sub remember_current_skipped {
                   5788:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5789:     my %to_remember;
                   5790:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5791: 	if ($scanlines->{'skipped'}[$i]) {
                   5792: 	    $to_remember{$i}=1;
                   5793: 	}
                   5794:     }
1.376     albertel 5795: 
1.200     albertel 5796:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5797:     &scantron_putfile(undef,$scan_data);
                   5798: }
                   5799: 
1.423     albertel 5800: =pod
                   5801: 
                   5802: =item check_for_error
                   5803: 
1.424     albertel 5804:     Checks if there was an error when attempting to remove a specific
                   5805:     scantron_.. bubble sheet data file. Prints out an error if
                   5806:     something went wrong.
                   5807: 
1.423     albertel 5808: =cut
                   5809: 
1.200     albertel 5810: sub check_for_error {
                   5811:     my ($r,$result)=@_;
                   5812:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5813: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5814:     }
                   5815: }
1.157     albertel 5816: 
1.423     albertel 5817: =pod
                   5818: 
                   5819: =item scantron_warning_screen
                   5820: 
1.424     albertel 5821:    Interstitial screen to make sure the operator has selected the
                   5822:    correct options before we start the validation phase.
                   5823: 
1.423     albertel 5824: =cut
                   5825: 
1.203     albertel 5826: sub scantron_warning_screen {
                   5827:     my ($button_text)=@_;
1.257     albertel 5828:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5829:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5830:     my $CODElist;
1.284     albertel 5831:     if ($scantron_config{'CODElocation'} &&
                   5832: 	$scantron_config{'CODEstart'} &&
                   5833: 	$scantron_config{'CODElength'}) {
                   5834: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5835: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5836: 	$CODElist=
                   5837: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5838: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5839:     }
1.203     albertel 5840:     return (<<STUFF);
                   5841: <p>
1.398     albertel 5842: <span class="LC_warning">Please double check the information
                   5843:                  below before clicking on '$button_text'</span>
1.203     albertel 5844: </p>
                   5845: <table>
1.284     albertel 5846: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5847: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5848: $CODElist
1.203     albertel 5849: </table>
                   5850: <br />
                   5851: <p> If this information is correct, please click on '$button_text'.</p>
                   5852: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5853: 
                   5854: <br />
                   5855: STUFF
                   5856: }
                   5857: 
1.423     albertel 5858: =pod
                   5859: 
                   5860: =item scantron_do_warning
                   5861: 
1.424     albertel 5862:    Check if the operator has picked something for all required
                   5863:    fields. Error out if something is missing.
                   5864: 
1.423     albertel 5865: =cut
                   5866: 
1.203     albertel 5867: sub scantron_do_warning {
                   5868:     my ($r)=@_;
1.324     albertel 5869:     my ($symb)=&get_symb($r);
1.203     albertel 5870:     if (!$symb) {return '';}
1.324     albertel 5871:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5872:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5873:     if ( $env{'form.selectpage'} eq '' ||
                   5874: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5875: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5876: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5877: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5878: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5879: 	} 
1.257     albertel 5880: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5881: 	    $r->print('<p><span class="LC_error">You have not selected a file that contains the student\'s response data.</span></p>');
1.237     albertel 5882: 	} 
1.257     albertel 5883: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5884: 	    $r->print('<p><span class="LC_error">You have not selected a the format of the student\'s response data.</span></p>');
1.237     albertel 5885: 	} 
                   5886:     } else {
1.265     www      5887: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5888: 	$r->print(<<STUFF);
1.203     albertel 5889: $warning
1.265     www      5890: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5891: <input type="hidden" name="command" value="scantron_validate" />
                   5892: STUFF
1.237     albertel 5893:     }
1.352     albertel 5894:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5895:     return '';
                   5896: }
                   5897: 
1.423     albertel 5898: =pod
                   5899: 
                   5900: =item scantron_form_start
                   5901: 
1.424     albertel 5902:     html hidden input for remembering all selected grading options
                   5903: 
1.423     albertel 5904: =cut
                   5905: 
1.203     albertel 5906: sub scantron_form_start {
                   5907:     my ($max_bubble)=@_;
                   5908:     my $result= <<SCANTRONFORM;
                   5909: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5910:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5911:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5912:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5913:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5914:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5915:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5916:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5917:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5918:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5919: SCANTRONFORM
1.447     foxr     5920: 
                   5921:   my $line = 0;
                   5922:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5923:        my $chunk =
                   5924: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5925:        $chunk .=
                   5926: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5927:        $result .= $chunk;
                   5928:        $line++;
                   5929:    }
1.203     albertel 5930:     return $result;
                   5931: }
                   5932: 
1.423     albertel 5933: =pod
                   5934: 
                   5935: =item scantron_validate_file
                   5936: 
1.424     albertel 5937:     Dispatch routine for doing validation of a bubble sheet data file.
                   5938: 
                   5939:     Also processes any necessary information resets that need to
                   5940:     occur before validation begins (ignore previous corrections,
                   5941:     restarting the skipped records processing)
                   5942: 
1.423     albertel 5943: =cut
                   5944: 
1.157     albertel 5945: sub scantron_validate_file {
                   5946:     my ($r) = @_;
1.324     albertel 5947:     my ($symb)=&get_symb($r);
1.157     albertel 5948:     if (!$symb) {return '';}
1.324     albertel 5949:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5950:     
                   5951:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5952:     # them when doing the corrections reset
1.257     albertel 5953:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5954: 	&reset_skipping_status();
                   5955:     }
1.257     albertel 5956:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5957: 	&remember_current_skipped();
1.257     albertel 5958: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5959:     }
                   5960: 
1.257     albertel 5961:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5962: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5963: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5964: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5965: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5966:     }
1.200     albertel 5967: 
1.257     albertel 5968:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5969: 	&scantron_process_corrections($r);
                   5970:     }
1.424     albertel 5971:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5972:     #get the student pick code ready
                   5973:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5974:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5975:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5976:     $r->print($result);
                   5977:     
1.334     albertel 5978:     my @validate_phases=( 'sequence',
                   5979: 			  'ID',
1.157     albertel 5980: 			  'CODE',
                   5981: 			  'doublebubble',
                   5982: 			  'missingbubbles');
1.257     albertel 5983:     if (!$env{'form.validatepass'}) {
                   5984: 	$env{'form.validatepass'} = 0;
1.157     albertel 5985:     }
1.257     albertel 5986:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5987: 
1.448     foxr     5988: 
1.157     albertel 5989:     my $stop=0;
                   5990:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5991: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5992: 	$r->rflush();
                   5993: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5994: 	{
                   5995: 	    no strict 'refs';
                   5996: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5997: 	}
                   5998:     }
                   5999:     if (!$stop) {
1.203     albertel 6000: 	my $warning=&scantron_warning_screen('Start Grading');
                   6001: 	$r->print(<<STUFF);
                   6002: Validation process complete.<br />
                   6003: $warning
                   6004: <input type="submit" name="submit" value="Start Grading" />
                   6005: <input type="hidden" name="command" value="scantron_process" />
                   6006: STUFF
                   6007: 
1.157     albertel 6008:     } else {
                   6009: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6010: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6011:     }
                   6012:     if ($stop) {
1.334     albertel 6013: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   6014: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   6015: 	    $r->print(' this error <br />');
                   6016: 
                   6017: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   6018: 	} else {
                   6019: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   6020: 	    $r->print(' using corrected info <br />');
                   6021: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   6022: 	    $r->print(" this scanline saving it for later.");
                   6023: 	}
1.157     albertel 6024:     }
1.352     albertel 6025:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6026:     return '';
                   6027: }
                   6028: 
1.423     albertel 6029: 
                   6030: =pod
                   6031: 
                   6032: =item scantron_remove_file
                   6033: 
1.424     albertel 6034:    Removes the requested bubble sheet data file, makes sure that
                   6035:    scantron_original_<filename> is never removed
                   6036: 
                   6037: 
1.423     albertel 6038: =cut
                   6039: 
1.200     albertel 6040: sub scantron_remove_file {
1.192     albertel 6041:     my ($which)=@_;
1.257     albertel 6042:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6043:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6044:     my $file='scantron_';
1.200     albertel 6045:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6046: 	$file.=$which.'_';
1.192     albertel 6047:     } else {
                   6048: 	return 'refused';
                   6049:     }
1.257     albertel 6050:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6051:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6052: }
                   6053: 
1.423     albertel 6054: 
                   6055: =pod
                   6056: 
                   6057: =item scantron_remove_scan_data
                   6058: 
1.424     albertel 6059:    Removes all scan_data correction for the requested bubble sheet
                   6060:    data file.  (In the case that both the are doing skipped records we need
                   6061:    to remember the old skipped lines for the time being so that element
                   6062:    persists for a while.)
                   6063: 
1.423     albertel 6064: =cut
                   6065: 
1.200     albertel 6066: sub scantron_remove_scan_data {
1.257     albertel 6067:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6068:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6069:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6070:     my @todelete;
1.257     albertel 6071:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6072:     foreach my $key (@keys) {
                   6073: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6074: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6075: 		$key=~/remember_skipping/) {
                   6076: 		next;
                   6077: 	    }
1.192     albertel 6078: 	    push(@todelete,$key);
                   6079: 	}
                   6080:     }
1.200     albertel 6081:     my $result;
1.192     albertel 6082:     if (@todelete) {
1.200     albertel 6083: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
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.161     albertel 6503:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6504:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6505: 	$r->print(" for PaperID <tt>".
                   6506: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6507:     } else {
                   6508: 	$r->print(" in scanline $i <pre>".
                   6509: 		  $line."</pre> \n");
                   6510:     }
1.242     albertel 6511:     my $message="<p>The ID on the form is  <tt>".
                   6512: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6513: 	"The name on the paper is ".
                   6514: 	$$scan_record{'scantron.LastName'}.",".
                   6515: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6516: 
1.157     albertel 6517:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6518:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6519:     if ($error =~ /ID$/) {
1.186     albertel 6520: 	if ($error eq 'incorrectID') {
1.157     albertel 6521: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6522: 	} elsif ($error eq 'duplicateID') {
                   6523: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6524: 	}
1.242     albertel 6525: 	$r->print($message);
1.157     albertel 6526: 	$r->print("<p>How should I handle this? <br /> \n");
                   6527: 	$r->print("\n<ul><li> ");
                   6528: 	#FIXME it would be nice if this sent back the user ID and
                   6529: 	#could do partial userID matches
                   6530: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6531: 				       'scantron_username','scantron_domain'));
                   6532: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6533: 	$r->print("\n@".
1.257     albertel 6534: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6535: 
                   6536: 	$r->print('</li>');
1.186     albertel 6537:     } elsif ($error =~ /CODE$/) {
                   6538: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6539: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6540: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6541: 	    $r->print("</p><p>The encoded CODE has also been used by a previous paper ".join(', ',@{$arg}).", and CODEs are supposed to be unique</p>\n");
1.186     albertel 6542: 	}
1.224     albertel 6543: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6544: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6545: 	$r->print($message);
1.186     albertel 6546: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6547: 	$r->print("\n<br /> ");
1.194     albertel 6548: 	my $i=0;
1.273     albertel 6549: 	if ($error eq 'incorrectCODE' 
                   6550: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6551: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6552: 	    if ($closest > 0) {
                   6553: 		foreach my $testcode (@{$closest}) {
                   6554: 		    my $checked='';
1.401     albertel 6555: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6556: 		    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_closest_$i' $checked /> Use the similar CODE <b><tt>".$testcode."</tt></b> instead.</label><input type='hidden' name='scantron_CODE_closest_$i' value='$testcode' />");
                   6557: 		    $r->print("\n<br />");
                   6558: 		    $i++;
                   6559: 		}
1.194     albertel 6560: 	    }
                   6561: 	}
1.273     albertel 6562: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6563: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6564: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_unfound' $checked /> Use the CODE <b><tt>".$$scan_record{'scantron.CODE'}."</tt></b> that is was on the paper, ignoring the error.</label>");
                   6565: 	    $r->print("\n<br />");
                   6566: 	}
1.194     albertel 6567: 
1.188     albertel 6568: 	$r->print(<<ENDSCRIPT);
                   6569: <script type="text/javascript">
                   6570: function change_radio(field) {
1.190     albertel 6571:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6572:     var i;
                   6573:     for (i=0;i<slct.length;i++) {
                   6574:         if (slct[i].value==field) { slct[i].checked=true; }
                   6575:     }
                   6576: }
                   6577: </script>
                   6578: ENDSCRIPT
1.187     albertel 6579: 	my $href="/adm/pickcode?".
1.359     www      6580: 	   "form=".&escape("scantronupload").
                   6581: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6582: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6583: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6584: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6585: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6586: 	    $r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_found' /> <a target='_blank' href='$href'>Select</a> a CODE from the list of all CODEs and use it.</label> Selected CODE is <input readonly='true' type='text' size='8' name='scantron_CODE_selectedvalue' onfocus=\"javascript:change_radio('use_found')\" onchange=\"javascript:change_radio('use_found')\" />");
                   6587: 	    $r->print("\n<br />");
                   6588: 	}
1.272     albertel 6589: 	$r->print("<label><input type='radio' name='scantron_CODE_resolution' value='use_typed' /> Use </label><input type='text' size='8' name='scantron_CODE_newvalue' onfocus=\"javascript:change_radio('use_typed')\" onkeypress=\"javascript:change_radio('use_typed')\" /> as the CODE.");
1.187     albertel 6590: 	$r->print("\n<br /><br />");
1.157     albertel 6591:     } elsif ($error eq 'doublebubble') {
                   6592: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6593: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6594: 		  join(',',@{$arg}).'" />');
1.242     albertel 6595: 	$r->print($message);
1.157     albertel 6596: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6597: 	foreach my $question (@{$arg}) {
1.447     foxr     6598: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6599: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6600: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6601: 				      @select_array);
1.157     albertel 6602: 	}
                   6603:     } elsif ($error eq 'missingbubble') {
                   6604: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6605: 	$r->print($message);
1.157     albertel 6606: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6607: 	$r->print("Some questions have no scanned bubbles\n");
                   6608: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6609: 		  join(',',@{$arg}).'" />');
                   6610: 	foreach my $question (@{$arg}) {
1.448     foxr     6611: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6612: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6613: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6614: 	}
                   6615:     } else {
                   6616: 	$r->print("\n<ul>");
                   6617:     }
                   6618:     $r->print("\n</li></ul>");
                   6619: 
                   6620: }
1.423     albertel 6621: 
                   6622: =pod
                   6623: 
                   6624: =item scantron_bubble_selector
                   6625:   
                   6626:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6627:    possibly showing the existing the selected bubbles if known
1.423     albertel 6628: 
                   6629:  Arguments:
                   6630:     $r           - Apache request object
                   6631:     $scan_config - hash from &get_scantron_config()
                   6632:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6633:     @lines       - array of answer lines.
1.423     albertel 6634: 
                   6635: =cut
                   6636: 
1.157     albertel 6637: sub scantron_bubble_selector {
1.461     foxr     6638:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6639:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6640: 
1.461     foxr     6641: 
1.274     albertel 6642:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6643: 
1.461     foxr     6644:     my $bubble_length = scalar(@lines);
1.460     foxr     6645: 
1.447     foxr     6646: 
1.274     albertel 6647:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6648: 
1.448     foxr     6649:     my $response = $quest-1;
                   6650:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6651: 
1.422     foxr     6652:     my $total_lines = $lines*2;
1.157     albertel 6653:     my @alphabet=('A'..'Z');
1.479     foxr     6654: 
1.422     foxr     6655:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6656: 
                   6657:     for (my $l = 0; $l < $lines; $l++) {
                   6658: 	if ($l != 0) {
                   6659: 	    $r->print('<tr>');
                   6660: 	}
1.462     foxr     6661: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6662: 	for (my $i=0;$i<$max;$i++) {
                   6663: 	    $r->print("\n".'<td align="center">');
                   6664: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6665: 		$r->print('X'); 
                   6666: 		shift(@selected) ;
                   6667: 	    } else { 
                   6668: 		$r->print('&nbsp;'); 
                   6669: 	    }
                   6670: 	    $r->print('</td>');
                   6671: 	    
                   6672: 	}
                   6673: 
                   6674: 	if ($l == 0) {
                   6675: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6676: 
                   6677: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6678: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6679: 	
                   6680: 	}
                   6681: 
                   6682: 	$r->print('</tr><tr>');
                   6683: 
                   6684: 	# FIXME: This may have to be a bit more clever for
                   6685: 	#        multiline questions (different values e.g..).
                   6686: 
                   6687: 	for (my $i=0;$i<$max;$i++) {
1.479     foxr     6688: 	    my $value = "$l:$i";	# Relative bubble line #: Bubble in line.
1.422     foxr     6689: 	    $r->print("\n".
                   6690: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
1.479     foxr     6691: 		      $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
1.422     foxr     6692: 	}
                   6693: 	$r->print('</tr>');
                   6694: 
                   6695: 	    
1.157     albertel 6696:     }
1.422     foxr     6697:     $r->print('</table>');
1.157     albertel 6698: }
                   6699: 
1.423     albertel 6700: =pod
                   6701: 
                   6702: =item num_matches
                   6703: 
1.424     albertel 6704:    Counts the number of characters that are the same between the two arguments.
                   6705: 
                   6706:  Arguments:
                   6707:    $orig - CODE from the scanline
                   6708:    $code - CODE to match against
                   6709: 
                   6710:  Returns:
                   6711:    $count - integer count of the number of same characters between the
                   6712:             two arguments
                   6713: 
1.423     albertel 6714: =cut
                   6715: 
1.194     albertel 6716: sub num_matches {
                   6717:     my ($orig,$code) = @_;
                   6718:     my @code=split(//,$code);
                   6719:     my @orig=split(//,$orig);
                   6720:     my $same=0;
                   6721:     for (my $i=0;$i<scalar(@code);$i++) {
                   6722: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6723:     }
                   6724:     return $same;
                   6725: }
                   6726: 
1.423     albertel 6727: =pod
                   6728: 
                   6729: =item scantron_get_closely_matching_CODEs
                   6730: 
1.424     albertel 6731:    Cycles through all CODEs and finds the set that has the greatest
                   6732:    number of same characters as the provided CODE
                   6733: 
                   6734:  Arguments:
                   6735:    $allcodes - hash ref returned by &get_codes()
                   6736:    $CODE     - CODE from the current scanline
                   6737: 
                   6738:  Returns:
                   6739:    2 element list
                   6740:     - first elements is number of how closely matching the best fit is 
                   6741:       (5 means best set has 5 matching characters)
                   6742:     - second element is an arrary ref containing the set of valid CODEs
                   6743:       that best fit the passed in CODE
                   6744: 
1.423     albertel 6745: =cut
                   6746: 
1.194     albertel 6747: sub scantron_get_closely_matching_CODEs {
                   6748:     my ($allcodes,$CODE)=@_;
                   6749:     my @CODEs;
                   6750:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6751: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6752:     }
                   6753: 
                   6754:     return ($#CODEs,$CODEs[-1]);
                   6755: }
                   6756: 
1.423     albertel 6757: =pod
                   6758: 
                   6759: =item get_codes
                   6760: 
1.424     albertel 6761:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6762:    set of remembered CODEs.
                   6763: 
                   6764:  Arguments:
                   6765:   $old_name - name of the set of remembered CODEs
                   6766:   $cdom     - domain of the course
                   6767:   $cnum     - internal course name
                   6768: 
                   6769:  Returns:
                   6770:   %allcodes - keys are the valid CODEs, values are all 1
                   6771: 
1.423     albertel 6772: =cut
                   6773: 
1.194     albertel 6774: sub get_codes {
1.280     foxr     6775:     my ($old_name, $cdom, $cnum) = @_;
                   6776:     if (!$old_name) {
                   6777: 	$old_name=$env{'form.scantron_CODElist'};
                   6778:     }
                   6779:     if (!$cdom) {
                   6780: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6781:     }
                   6782:     if (!$cnum) {
                   6783: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6784:     }
1.278     albertel 6785:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6786: 				    $cdom,$cnum);
                   6787:     my %allcodes;
                   6788:     if ($result{"type\0$old_name"} eq 'number') {
                   6789: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6790:     } else {
                   6791: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6792:     }
1.194     albertel 6793:     return %allcodes;
                   6794: }
                   6795: 
1.423     albertel 6796: =pod
                   6797: 
                   6798: =item scantron_validate_CODE
                   6799: 
1.424     albertel 6800:    Validates all scanlines in the selected file to not have any
                   6801:    invalid or underspecified CODEs and that none of the codes are
                   6802:    duplicated if this was requested.
                   6803: 
1.423     albertel 6804: =cut
                   6805: 
1.157     albertel 6806: sub scantron_validate_CODE {
                   6807:     my ($r,$currentphase) = @_;
1.257     albertel 6808:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6809:     if ($scantron_config{'CODElocation'} &&
                   6810: 	$scantron_config{'CODEstart'} &&
                   6811: 	$scantron_config{'CODElength'}) {
1.257     albertel 6812: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6813: 	    &FIXME_blow_up()
                   6814: 	}
                   6815:     } else {
                   6816: 	return (0,$currentphase+1);
                   6817:     }
                   6818:     
                   6819:     my %usedCODEs;
                   6820: 
1.194     albertel 6821:     my %allcodes=&get_codes();
1.186     albertel 6822: 
1.447     foxr     6823:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6824: 
1.186     albertel 6825:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6826:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6827: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6828: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6829: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6830: 						 $scan_data);
                   6831: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6832: 	my $error=0;
1.224     albertel 6833: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6834: 	    &scantron_get_correction($r,$i,$scan_record,
                   6835: 				     \%scantron_config,
                   6836: 				     $line,'incorrectCODE',\%allcodes);
                   6837: 	    return(1,$currentphase);
                   6838: 	}
1.221     albertel 6839: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6840: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6841: 	    &scantron_get_correction($r,$i,$scan_record,
                   6842: 				     \%scantron_config,
1.194     albertel 6843: 				     $line,'incorrectCODE',\%allcodes);
                   6844: 	    return(1,$currentphase);
1.186     albertel 6845: 	}
1.214     albertel 6846: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6847: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6848: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6849: 	    &scantron_get_correction($r,$i,$scan_record,
                   6850: 				     \%scantron_config,
1.194     albertel 6851: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6852: 	    return(1,$currentphase);
1.186     albertel 6853: 	}
1.194     albertel 6854: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6855:     }
1.157     albertel 6856:     return (0,$currentphase+1);
                   6857: }
                   6858: 
1.423     albertel 6859: =pod
                   6860: 
                   6861: =item scantron_validate_doublebubble
                   6862: 
1.424     albertel 6863:    Validates all scanlines in the selected file to not have any
                   6864:    bubble lines with multiple bubbles marked.
                   6865: 
1.423     albertel 6866: =cut
                   6867: 
1.157     albertel 6868: sub scantron_validate_doublebubble {
                   6869:     my ($r,$currentphase) = @_;
                   6870:     #get student info
                   6871:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6872:     my %idmap=&username_to_idmap($classlist);
                   6873: 
                   6874:     #get scantron line setup
1.257     albertel 6875:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6876:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6877: 
                   6878:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6879: 
1.157     albertel 6880:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6881: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6882: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6883: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6884: 						 $scan_data);
                   6885: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6886: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6887: 				 'doublebubble',
                   6888: 				 $$scan_record{'scantron.doubleerror'});
                   6889:     	return (1,$currentphase);
                   6890:     }
                   6891:     return (0,$currentphase+1);
                   6892: }
                   6893: 
1.423     albertel 6894: =pod
                   6895: 
                   6896: =item scantron_get_maxbubble
                   6897: 
1.424     albertel 6898:    Returns the maximum number of bubble lines that are expected to
                   6899:    occur. Does this by walking the selected sequence rendering the
                   6900:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6901:    for what the current value of the problem counter is.
                   6902: 
1.447     foxr     6903:    Caches the results to $env{'form.scantron_maxbubble'},
                   6904:    $env{'form.scantron.bubble_lines.n'} and 
                   6905:    $env{'form.scantron.first_bubble_line.n'}
                   6906:    which are the total number of bubble, lines, the number of bubble
                   6907:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6908: 
1.423     albertel 6909: =cut
                   6910: 
1.330     albertel 6911: sub scantron_get_maxbubble {    
1.257     albertel 6912:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6913: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6914: 	&restore_bubble_lines();
1.257     albertel 6915: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6916:     }
1.330     albertel 6917: 
1.447     foxr     6918:     my (undef, undef, $sequence) =
1.257     albertel 6919: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6920: 
1.447     foxr     6921:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6922:     my $map=$navmap->getResourceByUrl($sequence);
                   6923:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6924: 
                   6925:     &Apache::lonxml::clear_problem_counter();
                   6926: 
1.435     foxr     6927:     my $uname       = $env{'form.student'};
                   6928:     my $udom        = $env{'form.userdom'};
                   6929:     my $cid         = $env{'request.course.id'};
                   6930:     my $total_lines = 0;
                   6931:     %bubble_lines_per_response = ();
1.447     foxr     6932:     %first_bubble_line         = ();
1.435     foxr     6933: 
1.447     foxr     6934:   
                   6935:     my $response_number = 0;
                   6936:     my $bubble_line     = 0;
1.191     albertel 6937:     foreach my $resource (@resources) {
1.435     foxr     6938: 	my $symb = $resource->symb();
1.447     foxr     6939: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6940: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6941: 					('symb' => $resource->symb()),
                   6942: 					('grade_target' => 'analyze'),
                   6943: 					('grade_courseid' => $cid),
                   6944: 					('grade_domain' => $udom),
                   6945: 					('grade_username' => $uname));
1.436     albertel 6946: 	my (undef, $an) =
1.435     foxr     6947: 	    split(/_HASH_REF__/,$result, 2);
                   6948: 
                   6949: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6950: 
                   6951: 
                   6952: 
                   6953: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6954: 
1.460     foxr     6955: 
                   6956: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
1.447     foxr     6957: 
                   6958: 	    # TODO - make this a persistent hash not an array.
                   6959: 
                   6960: 
                   6961: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6962: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6963: 	    $response_number++;
                   6964: 
                   6965: 	    $bubble_line +=  $lines;
                   6966: 	    $total_lines +=  $lines;
1.435     foxr     6967: 	}
                   6968: 
1.191     albertel 6969:     }
                   6970:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6971: 
                   6972:     &save_bubble_lines();
1.330     albertel 6973:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6974: 	$total_lines;
1.257     albertel 6975:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6976: }
                   6977: 
1.423     albertel 6978: =pod
                   6979: 
                   6980: =item scantron_validate_missingbubbles
                   6981: 
1.424     albertel 6982:    Validates all scanlines in the selected file to not have any
1.447     foxr     6983:     answers that don't have bubbles that have not been verified
                   6984:     to be bubble free.
1.424     albertel 6985: 
1.423     albertel 6986: =cut
                   6987: 
1.157     albertel 6988: sub scantron_validate_missingbubbles {
                   6989:     my ($r,$currentphase) = @_;
                   6990:     #get student info
                   6991:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6992:     my %idmap=&username_to_idmap($classlist);
                   6993: 
                   6994:     #get scantron line setup
1.257     albertel 6995:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6996:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6997:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6998:     if (!$max_bubble) { $max_bubble=2**31; }
                   6999:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7000: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7001: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7002: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7003: 						 $scan_data);
                   7004: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7005: 	my @to_correct;
1.470     foxr     7006: 	
                   7007: 	# Probably here's where the error is...
                   7008: 
1.157     albertel 7009: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   7010: 	    if ($missing > $max_bubble) { next; }
                   7011: 	    push(@to_correct,$missing);
                   7012: 	}
                   7013: 	if (@to_correct) {
                   7014: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7015: 				     $line,'missingbubble',\@to_correct);
                   7016: 	    return (1,$currentphase);
                   7017: 	}
                   7018: 
                   7019:     }
                   7020:     return (0,$currentphase+1);
                   7021: }
                   7022: 
1.423     albertel 7023: =pod
                   7024: 
                   7025: =item scantron_process_students
                   7026: 
                   7027:    Routine that does the actual grading of the bubble sheet information.
                   7028: 
                   7029:    The parsed scanline hash is added to %env 
                   7030: 
                   7031:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7032:    foreach resource , with the form data of
                   7033: 
                   7034: 	'submitted'     =>'scantron' 
                   7035: 	'grade_target'  =>'grade',
                   7036: 	'grade_username'=> username of student
                   7037: 	'grade_domain'  => domain of student
                   7038: 	'grade_courseid'=> of course
                   7039: 	'grade_symb'    => symb of resource to grade
                   7040: 
                   7041:     This triggers a grading pass. The problem grading code takes care
                   7042:     of converting the bubbled letter information (now in %env) into a
                   7043:     valid submission.
                   7044: 
                   7045: =cut
                   7046: 
1.82      albertel 7047: sub scantron_process_students {
1.75      albertel 7048:     my ($r) = @_;
1.257     albertel 7049:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7050:     my ($symb)=&get_symb($r);
1.81      albertel 7051:     if (!$symb) {return '';}
1.324     albertel 7052:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7053: 
1.257     albertel 7054:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7055:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7056:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7057:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7058:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7059:     my $map=$navmap->getResourceByUrl($sequence);
                   7060:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7061: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7062:     my $result= <<SCANTRONFORM;
1.81      albertel 7063: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7064:   <input type="hidden" name="command" value="scantron_configphase" />
                   7065:   $default_form_data
                   7066: SCANTRONFORM
1.82      albertel 7067:     $r->print($result);
                   7068: 
                   7069:     my @delayqueue;
1.140     albertel 7070:     my %completedstudents;
                   7071:     
1.200     albertel 7072:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7073:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7074:  				    'Scantron Progress',$count,
1.195     albertel 7075: 				    'inline',undef,'scantronupload');
1.140     albertel 7076:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7077: 					  'Processing first student');
                   7078:     my $start=&Time::HiRes::time();
1.158     albertel 7079:     my $i=-1;
1.200     albertel 7080:     my ($uname,$udom,$started);
1.447     foxr     7081: 
                   7082:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   7083: 
1.157     albertel 7084:     while ($i<$scanlines->{'count'}) {
                   7085:  	($uname,$udom)=('','');
                   7086:  	$i++;
1.200     albertel 7087:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7088:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7089: 	if ($started) {
                   7090: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7091: 						     'last student');
                   7092: 	}
                   7093: 	$started=1;
1.157     albertel 7094:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7095:  						 $scan_data);
                   7096:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7097:  					      \%idmap,$i)) {
                   7098:   	    &scantron_add_delay(\@delayqueue,$line,
                   7099:  				'Unable to find a student that matches',1);
                   7100:  	    next;
                   7101:   	}
                   7102:  	if (exists $completedstudents{$uname}) {
                   7103:  	    &scantron_add_delay(\@delayqueue,$line,
                   7104:  				'Student '.$uname.' has multiple sheets',2);
                   7105:  	    next;
                   7106:  	}
                   7107:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7108: 
                   7109: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7110:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7111: 
                   7112: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7113: 	    &scantron_putfile($scanlines,$scan_data);
                   7114: 	}
1.161     albertel 7115: 	
                   7116: 	my $i=0;
1.83      albertel 7117: 	foreach my $resource (@resources) {
1.85      albertel 7118: 	    $i++;
1.193     albertel 7119: 	    my %form=('submitted'     =>'scantron',
                   7120: 		      'grade_target'  =>'grade',
                   7121: 		      'grade_username'=>$uname,
                   7122: 		      'grade_domain'  =>$udom,
1.257     albertel 7123: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7124: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7125: 	    if (exists($scan_record->{'scantron.CODE'})
                   7126: 		&& 
                   7127: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7128: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7129: 	    } else {
                   7130: 		$form{'CODE'}='';
1.193     albertel 7131: 	    }
                   7132: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7133: 	    if ($result ne '') {
                   7134: 	    }
1.213     albertel 7135: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7136: 	}
1.140     albertel 7137: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7138: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7139:     } continue {
1.330     albertel 7140: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7141: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7142:     }
1.140     albertel 7143:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7144: #    my $lasttime = &Time::HiRes::time()-$start;
                   7145: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7146: 
1.200     albertel 7147:     $r->print("</form>");
1.324     albertel 7148:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7149:     return '';
1.75      albertel 7150: }
1.157     albertel 7151: 
1.423     albertel 7152: =pod
                   7153: 
                   7154: =item scantron_upload_scantron_data
                   7155: 
                   7156:     Creates the screen for adding a new bubble sheet data file to a course.
                   7157: 
                   7158: =cut
                   7159: 
1.157     albertel 7160: sub scantron_upload_scantron_data {
                   7161:     my ($r)=@_;
1.257     albertel 7162:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7163:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7164: 							  'domainid',
                   7165: 							  'coursename');
1.257     albertel 7166:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7167: 						   'domainid');
1.324     albertel 7168:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 7169:     $r->print(<<UPLOAD);
                   7170: <script type="text/javascript" language="javascript">
                   7171:     function checkUpload(formname) {
                   7172: 	if (formname.upfile.value == "") {
                   7173: 	    alert("Please use the browse button to select a file from your local directory.");
                   7174: 	    return false;
                   7175: 	}
                   7176: 	formname.submit();
                   7177:     }
                   7178: </script>
                   7179: 
                   7180: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7181: $default_form_data
1.181     albertel 7182: <table>
                   7183: <tr><td>$select_link </td></tr>
                   7184: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7185: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7186: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7187: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7188: </table>
1.157     albertel 7189: <input name='command' value='scantronupload_save' type='hidden' />
                   7190: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7191: </form>
                   7192: UPLOAD
                   7193:     return '';
                   7194: }
                   7195: 
1.423     albertel 7196: =pod
                   7197: 
                   7198: =item scantron_upload_scantron_data_save
                   7199: 
                   7200:    Adds a provided bubble information data file to the course if user
                   7201:    has the correct privileges to do so.  
                   7202: 
                   7203: =cut
                   7204: 
1.157     albertel 7205: sub scantron_upload_scantron_data_save {
                   7206:     my($r)=@_;
1.324     albertel 7207:     my ($symb)=&get_symb($r,1);
1.182     albertel 7208:     my $doanotherupload=
                   7209: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7210: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7211: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7212: 	'</form>'."\n";
1.257     albertel 7213:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7214: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7215: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7216: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7217: 	if ($symb) {
1.324     albertel 7218: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7219: 	} else {
                   7220: 	    $r->print($doanotherupload);
                   7221: 	}
1.162     albertel 7222: 	return '';
                   7223:     }
1.257     albertel 7224:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7225:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7226:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7227:     #FIXME
                   7228:     #copied from lonnet::userfileupload()
                   7229:     #make that function able to target a specified course
                   7230:     # Replace Windows backslashes by forward slashes
                   7231:     $fname=~s/\\/\//g;
                   7232:     # Get rid of everything but the actual filename
                   7233:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7234:     # Replace spaces by underscores
                   7235:     $fname=~s/\s+/\_/g;
                   7236:     # Replace all other weird characters by nothing
                   7237:     $fname=~s/[^\w\.\-]//g;
                   7238:     # See if there is anything left
                   7239:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7240:     my $uploadedfile=$fname;
1.157     albertel 7241:     $fname='scantron_orig_'.$fname;
1.257     albertel 7242:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7243: 	$r->print("<span class=\"LC_error\">Error:</span> The file you attempted to upload, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>, contained no information. Please check that you entered the correct filename.");
1.183     albertel 7244:     } else {
1.275     albertel 7245: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7246: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7247: 	    $r->print("<span class=\"LC_success\">Success:</span> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
1.210     albertel 7248: 	} else {
1.398     albertel 7249: 	    $r->print("<span class=\"LC_error\">Error:</span> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
1.183     albertel 7250: 	}
                   7251:     }
1.174     albertel 7252:     if ($symb) {
1.209     ng       7253: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7254:     } else {
1.182     albertel 7255: 	$r->print($doanotherupload);
1.174     albertel 7256:     }
1.157     albertel 7257:     return '';
                   7258: }
                   7259: 
1.423     albertel 7260: =pod
                   7261: 
                   7262: =item valid_file
                   7263: 
1.424     albertel 7264:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7265: 
                   7266: =cut
                   7267: 
1.202     albertel 7268: sub valid_file {
                   7269:     my ($requested_file)=@_;
                   7270:     foreach my $filename (sort(&scantron_filenames())) {
                   7271: 	if ($requested_file eq $filename) { return 1; }
                   7272:     }
                   7273:     return 0;
                   7274: }
                   7275: 
1.423     albertel 7276: =pod
                   7277: 
                   7278: =item scantron_download_scantron_data
                   7279: 
                   7280:    Shows a list of the three internal files (original, corrected,
                   7281:    skipped) for a specific bubble sheet data file that exists in the
                   7282:    course.
                   7283: 
                   7284: =cut
                   7285: 
1.202     albertel 7286: sub scantron_download_scantron_data {
                   7287:     my ($r)=@_;
1.324     albertel 7288:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7289:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7290:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7291:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7292:     if (! &valid_file($file)) {
                   7293: 	$r->print(<<ERROR);
                   7294: 	<p>
                   7295: 	    The requested file name was invalid.
                   7296:         </p>
                   7297: ERROR
1.324     albertel 7298: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7299: 	return;
                   7300:     }
                   7301:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7302:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7303:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7304:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7305:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7306:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7307:     $r->print(<<DOWNLOAD);
                   7308:     <p>
                   7309: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7310:     </p>
                   7311:     <p>
                   7312: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7313:     </p>
                   7314:     <p>
                   7315: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7316:     </p>
                   7317: DOWNLOAD
1.324     albertel 7318:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7319:     return '';
                   7320: }
1.157     albertel 7321: 
1.423     albertel 7322: =pod
                   7323: 
                   7324: =back
                   7325: 
                   7326: =cut
                   7327: 
1.75      albertel 7328: #-------- end of section for handling grading scantron forms -------
                   7329: #
                   7330: #-------------------------------------------------------------------
                   7331: 
1.72      ng       7332: #-------------------------- Menu interface -------------------------
                   7333: #
                   7334: #--- Show a Grading Menu button - Calls the next routine ---
                   7335: sub show_grading_menu_form {
1.324     albertel 7336:     my ($symb)=@_;
1.125     ng       7337:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7338: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7339: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7340: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7341: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7342: 	'</form>'."\n";
                   7343:     return $result;
                   7344: }
                   7345: 
1.77      ng       7346: # -- Retrieve choices for grading form
                   7347: sub savedState {
                   7348:     my %savedState = ();
1.257     albertel 7349:     if ($env{'form.saveState'}) {
                   7350: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7351: 	    my ($key,$value) = split(/=/,$_,2);
                   7352: 	    $savedState{$key} = $value;
                   7353: 	}
                   7354:     }
                   7355:     return \%savedState;
                   7356: }
1.76      ng       7357: 
1.443     banghart 7358: sub grading_menu {
                   7359:     my ($request) = @_;
                   7360:     my ($symb)=&get_symb($request);
                   7361:     if (!$symb) {return '';}
                   7362:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7363:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7364: 
1.444     banghart 7365:     $request->print($table);
1.443     banghart 7366:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7367:                   'handgrade'=>$hdgrade,
                   7368:                   'probTitle'=>$probTitle,
                   7369:                   'command'=>'submit_options',
                   7370:                   'saveState'=>"",
                   7371:                   'gradingMenu'=>1,
                   7372:                   'showgrading'=>"yes");
                   7373:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7374:     my @menu = ({ url => $url,
                   7375:                      name => &mt('Manual Grading/View Submissions'),
                   7376:                      short_description => 
                   7377:     &mt('Start the process of hand grading submissions.'),
                   7378:                  });
                   7379:     $fields{'command'} = 'csvform';
                   7380:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7381:     push (@menu, { url => $url,
                   7382:                    name => &mt('Upload Scores'),
                   7383:                    short_description => 
                   7384:             &mt('Specify a file containing the class scores for current resource.')});
                   7385:     $fields{'command'} = 'processclicker';
                   7386:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7387:     push (@menu, { url => $url,
                   7388:                    name => &mt('Process Clicker'),
                   7389:                    short_description => 
                   7390:             &mt('Specify a file containing the clicker information for this resource.')});
                   7391:     $fields{'command'} = 'scantron_selectphase';
                   7392:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7393:     push (@menu, { url => $url,
1.454     banghart 7394:                    name => &mt('Grade/Manage Scantron Forms'),
                   7395:                    short_description => 
                   7396:             &mt('')});
1.443     banghart 7397:     $fields{'command'} = 'verify';
                   7398:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7399:     push (@menu, { url => "",
1.443     banghart 7400:                    name => &mt('Verify Receipt'),
                   7401:                    short_description => 
                   7402:             &mt('')});
                   7403:     #
                   7404:     # Create the menu
                   7405:     my $Str;
1.444     banghart 7406:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7407:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7408:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7409:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7410: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7411: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7412: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7413: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7414: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7415: 
1.443     banghart 7416:     foreach my $menudata (@menu) {
1.445     banghart 7417:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7418:             $Str .='    <h3><a '.
                   7419:                 $menudata->{'jscript'}.
                   7420:                 ' href="'.
                   7421:                 $menudata->{'url'}.'" >'.
                   7422:                 $menudata->{'name'}."</a></h3>\n";
                   7423:         } else {
1.485   ! albertel 7424:             $Str .='    <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 7425:                 $menudata->{'jscript'}.
1.458     banghart 7426:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7427:                 ' /></h3>';
1.446     banghart 7428:             $Str .= ('&nbsp;'x8).
1.485   ! albertel 7429: 		&mt(' receipt: [_1]',
        !          7430: 		    &Apache::lonnet::recprefix($env{'request.course.id'}).
        !          7431:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
1.444     banghart 7432:         }
1.443     banghart 7433:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7434:             "\n";
                   7435:     }
1.444     banghart 7436:     $Str .="</form>\n";
1.443     banghart 7437:     $request->print(<<GRADINGMENUJS);
                   7438: <script type="text/javascript" language="javascript">
                   7439:     function checkChoice(formname,val,cmdx) {
                   7440: 	if (val <= 2) {
                   7441: 	    var cmd = radioSelection(formname.radioChoice);
                   7442: 	    var cmdsave = cmd;
                   7443: 	} else {
                   7444: 	    cmd = cmdx;
                   7445: 	    cmdsave = 'submission';
                   7446: 	}
                   7447: 	formname.command.value = cmd;
                   7448: 	if (val < 5) formname.submit();
                   7449: 	if (val == 5) {
1.458     banghart 7450: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7451: 	        return false;
                   7452: 	    } else {
                   7453: 	        formname.submit();
                   7454: 	    }
1.445     banghart 7455: 	}
                   7456:     }
1.443     banghart 7457: 
                   7458:     function checkReceiptNo(formname,nospace) {
                   7459: 	var receiptNo = formname.receipt.value;
                   7460: 	var checkOpt = false;
                   7461: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7462: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7463: 	if (checkOpt) {
                   7464: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7465: 	    formname.receipt.value = "";
                   7466: 	    formname.receipt.focus();
                   7467: 	    return false;
                   7468: 	}
                   7469: 	return true;
                   7470:     }
                   7471: </script>
                   7472: GRADINGMENUJS
                   7473:     &commonJSfunctions($request);
                   7474:     return $Str;    
                   7475: }
                   7476: 
                   7477: 
                   7478: #--- Displays the submissions first page -------
                   7479: sub submit_options {
1.72      ng       7480:     my ($request) = @_;
1.324     albertel 7481:     my ($symb)=&get_symb($request);
1.72      ng       7482:     if (!$symb) {return '';}
1.76      ng       7483:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7484: 
                   7485:     $request->print(<<GRADINGMENUJS);
                   7486: <script type="text/javascript" language="javascript">
1.116     ng       7487:     function checkChoice(formname,val,cmdx) {
                   7488: 	if (val <= 2) {
                   7489: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7490: 	    var cmdsave = cmd;
1.116     ng       7491: 	} else {
                   7492: 	    cmd = cmdx;
1.118     ng       7493: 	    cmdsave = 'submission';
1.116     ng       7494: 	}
                   7495: 	formname.command.value = cmd;
1.118     ng       7496: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7497: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7498: 	if (val < 5) formname.submit();
                   7499: 	if (val == 5) {
1.72      ng       7500: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7501: 	    formname.submit();
                   7502: 	}
1.238     albertel 7503: 	if (val < 7) formname.submit();
1.72      ng       7504:     }
                   7505: 
                   7506:     function checkReceiptNo(formname,nospace) {
                   7507: 	var receiptNo = formname.receipt.value;
                   7508: 	var checkOpt = false;
                   7509: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7510: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7511: 	if (checkOpt) {
                   7512: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7513: 	    formname.receipt.value = "";
                   7514: 	    formname.receipt.focus();
                   7515: 	    return false;
                   7516: 	}
                   7517: 	return true;
                   7518:     }
                   7519: </script>
                   7520: GRADINGMENUJS
1.118     ng       7521:     &commonJSfunctions($request);
1.324     albertel 7522:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7523:     my $result;
1.76      ng       7524:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7525:     my $savedState = &savedState();
1.118     ng       7526:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7527:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7528:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7529:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7530: 
                   7531:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7532: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7533: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7534: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7535: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7536: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7537: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7538: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7539: 
1.472     albertel 7540:     $result.='
                   7541:     <div class="LC_grade_select_mode">
1.473     albertel 7542:       <div class="LC_grade_select_mode_current">
                   7543:         <h2>
                   7544:           '.&mt('Grade Current Resource').'
                   7545:         </h2>
                   7546:         <div class="LC_grade_select_mode_body">
                   7547:           <div class="LC_grades_resource_info">
                   7548:            '.$table.'
                   7549:           </div>
                   7550:           <div class="LC_grade_select_mode_selector">
                   7551:              <div class="LC_grade_select_mode_selector_header">
                   7552:                 '.&mt('Sections').'
                   7553:              </div>
                   7554:              <div class="LC_grade_select_mode_selector_body">
                   7555: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7556:     if (ref($sections)) {
1.472     albertel 7557: 	foreach my $section (sort (@$sections)) {
                   7558: 	    $result.='<option value="'.$section.'" '.
                   7559: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7560: 	}
1.116     ng       7561:     }
1.401     albertel 7562:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7563:     $result.='
1.473     albertel 7564:              </div>
                   7565:           </div>
                   7566:           <div class="LC_grade_select_mode_selector">
                   7567:              <div class="LC_grade_select_mode_selector_header">
                   7568:                 '.&mt('Groups').'
                   7569:              </div>
                   7570:              <div class="LC_grade_select_mode_selector_body">
                   7571:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7572:              </div>
1.472     albertel 7573:           </div>
1.473     albertel 7574:           <div class="LC_grade_select_mode_selector">
                   7575:              <div class="LC_grade_select_mode_selector_header">
                   7576:                 '.&mt('Access Status').'
                   7577:              </div>
                   7578:              <div class="LC_grade_select_mode_selector_body">
                   7579:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7580:              </div>
1.472     albertel 7581:           </div>
1.473     albertel 7582:           <div class="LC_grade_select_mode_selector">
                   7583:              <div class="LC_grade_select_mode_selector_header">
                   7584:                 '.&mt('Submission Status').'
                   7585:              </div>
                   7586:              <div class="LC_grade_select_mode_selector_body">
                   7587:                <select name="submitonly" size="5">
                   7588: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7589: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7590: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7591: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7592:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7593:                </select>
                   7594:              </div>
1.472     albertel 7595:           </div>
1.473     albertel 7596:           <div class="LC_grade_select_mode_type_body">
                   7597:             <div class="LC_grade_select_mode_type">
                   7598:               <label>
                   7599:                 <input type="radio" name="radioChoice" value="submission" '.
                   7600:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7601:              &mt('Select individual students to grade and view submissions.').'
                   7602: 	      </label> 
                   7603:             </div>
                   7604:             <div class="LC_grade_select_mode_type">
                   7605: 	      <label>
                   7606:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7607:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7608:                     &mt('Grade all selected students in a grading table.').'
                   7609:               </label>
                   7610:             </div>
                   7611:             <div class="LC_grade_select_mode_type">
                   7612: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7613:             </div>
1.472     albertel 7614:           </div>
1.473     albertel 7615:         </div>
                   7616:       </div>
                   7617:       <div class="LC_grade_select_mode_page">
                   7618:         <h2>
                   7619:          '.&mt('Grade Complete Folder for One Student').'
                   7620:         </h2>
                   7621:         <div class="LC_grades_select_mode_body">
                   7622:           <div class="LC_grade_select_mode_type_body">
                   7623:             <div class="LC_grade_select_mode_type">
                   7624:               <label>
                   7625:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7626: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7627:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7628:               </label>
                   7629:             </div>
                   7630:             <div class="LC_grade_select_mode_type">
                   7631: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7632:             </div>
1.472     albertel 7633:           </div>
                   7634:         </div>
                   7635:       </div>
                   7636:     </div>
                   7637:   </form>';
1.44      ng       7638:     return $result;
1.2       albertel 7639: }
                   7640: 
1.285     albertel 7641: sub reset_perm {
                   7642:     undef(%perm);
                   7643: }
                   7644: 
                   7645: sub init_perm {
                   7646:     &reset_perm();
1.300     albertel 7647:     foreach my $test_perm ('vgr','mgr','opa') {
                   7648: 
                   7649: 	my $scope = $env{'request.course.id'};
                   7650: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7651: 
                   7652: 	    $scope .= '/'.$env{'request.course.sec'};
                   7653: 	    if ( $perm{$test_perm}=
                   7654: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7655: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7656: 	    } else {
                   7657: 		delete($perm{$test_perm});
                   7658: 	    }
1.285     albertel 7659: 	}
                   7660:     }
                   7661: }
                   7662: 
1.400     www      7663: sub gather_clicker_ids {
1.408     albertel 7664:     my %clicker_ids;
1.400     www      7665: 
                   7666:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7667: 
                   7668:     # Set up a couple variables.
1.407     albertel 7669:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7670:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7671:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7672: 
1.407     albertel 7673:     foreach my $student (keys(%$classlist)) {
1.438     www      7674:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7675:         my $username = $classlist->{$student}->[$username_idx];
                   7676:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7677:         my $clickers =
1.408     albertel 7678: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7679:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7680:             $id=~s/^[\#0]+//;
1.421     www      7681:             $id=~s/[\-\:]//g;
1.407     albertel 7682:             if (exists($clicker_ids{$id})) {
1.408     albertel 7683: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7684:             } else {
1.408     albertel 7685: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7686:             }
                   7687:         }
                   7688:     }
1.407     albertel 7689:     return %clicker_ids;
1.400     www      7690: }
                   7691: 
1.402     www      7692: sub gather_adv_clicker_ids {
1.408     albertel 7693:     my %clicker_ids;
1.402     www      7694:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7695:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7696:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7697:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7698:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7699:             my ($puname,$pudom)=split(/\:/,$person);
                   7700:             my $clickers =
1.408     albertel 7701: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7702:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7703: 		$id=~s/^[\#0]+//;
1.421     www      7704:                 $id=~s/[\-\:]//g;
1.408     albertel 7705: 		if (exists($clicker_ids{$id})) {
                   7706: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7707: 		} else {
                   7708: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7709: 		}
1.405     www      7710:             }
1.402     www      7711:         }
                   7712:     }
1.407     albertel 7713:     return %clicker_ids;
1.402     www      7714: }
                   7715: 
1.413     www      7716: sub clicker_grading_parameters {
                   7717:     return ('gradingmechanism' => 'scalar',
                   7718:             'upfiletype' => 'scalar',
                   7719:             'specificid' => 'scalar',
                   7720:             'pcorrect' => 'scalar',
                   7721:             'pincorrect' => 'scalar');
                   7722: }
                   7723: 
1.400     www      7724: sub process_clicker {
                   7725:     my ($r)=@_;
                   7726:     my ($symb)=&get_symb($r);
                   7727:     if (!$symb) {return '';}
                   7728:     my $result=&checkforfile_js();
                   7729:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7730:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7731:     $result.=$table;
                   7732:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7733:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7734:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7735:         '.</b></td></tr>'."\n";
                   7736:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7737: # Attempt to restore parameters from last session, set defaults if not present
                   7738:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7739:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7740:                                                  \%Saveable_Parameters);
                   7741:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7742:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7743:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7744:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7745: 
                   7746:     my %checked;
                   7747:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7748:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7749:           $checked{$gradingmechanism}="checked='checked'";
                   7750:        }
                   7751:     }
                   7752: 
1.400     www      7753:     my $upload=&mt("Upload File");
                   7754:     my $type=&mt("Type");
1.402     www      7755:     my $attendance=&mt("Award points just for participation");
                   7756:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7757:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7758:     my $pcorrect=&mt("Percentage points for correct solution");
                   7759:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7760:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7761: 						   ('iclicker' => 'i>clicker',
                   7762:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7763:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7764:     $result.=<<ENDUPFORM;
1.402     www      7765: <script type="text/javascript">
                   7766: function sanitycheck() {
                   7767: // Accept only integer percentages
                   7768:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7769:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7770: // Find out grading choice
                   7771:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7772:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7773:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7774:       }
                   7775:    }
                   7776: // By default, new choice equals user selection
                   7777:    newgradingchoice=gradingchoice;
                   7778: // Not good to give more points for false answers than correct ones
                   7779:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7780:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7781:    }
                   7782: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7783:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7784:       document.forms.gradesupload.pcorrect.value=100;
                   7785:       document.forms.gradesupload.pincorrect.value=100;
                   7786:    }
                   7787: // If the values are different, cannot be attendance only
                   7788:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7789:        (gradingchoice=='attendance')) {
                   7790:        newgradingchoice='personnel';
                   7791:    }
                   7792: // Change grading choice to new one
                   7793:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7794:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7795:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7796:       } else {
                   7797:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7798:       }
                   7799:    }
                   7800: // Remember the old state
                   7801:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7802: }
                   7803: </script>
1.400     www      7804: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7805: <input type="hidden" name="symb" value="$symb" />
                   7806: <input type="hidden" name="command" value="processclickerfile" />
                   7807: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7808: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7809: <input type="file" name="upfile" size="50" />
                   7810: <br /><label>$type: $selectform</label>
1.451     albertel 7811: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7812: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7813: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7814: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7815: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7816: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7817: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7818: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7819: </form>
                   7820: ENDUPFORM
                   7821:     $result.='</td></tr></table>'."\n".
                   7822:              '</td></tr></table><br /><br />'."\n";
                   7823:     $result.=&show_grading_menu_form($symb);
                   7824:     return $result;
                   7825: }
                   7826: 
                   7827: sub process_clicker_file {
                   7828:     my ($r)=@_;
                   7829:     my ($symb)=&get_symb($r);
                   7830:     if (!$symb) {return '';}
1.413     www      7831: 
                   7832:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7833:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7834:                                               \%Saveable_Parameters);
                   7835: 
1.400     www      7836:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7837:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7838: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7839: 	return $result.&show_grading_menu_form($symb);
1.404     www      7840:     }
1.407     albertel 7841:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7842:     my %correct_ids;
1.404     www      7843:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7844: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7845:     }
                   7846:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7847: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7848: 	   $correct_id=~tr/a-z/A-Z/;
                   7849: 	   $correct_id=~s/\s//gs;
                   7850: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7851:            $correct_id=~s/[\-\:]//g;
1.414     www      7852:            if ($correct_id) {
                   7853: 	      $correct_ids{$correct_id}='specified';
                   7854:            }
                   7855:         }
1.400     www      7856:     }
1.404     www      7857:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7858: 	$result.=&mt('Score based on attendance only');
1.404     www      7859:     } else {
1.408     albertel 7860: 	my $number=0;
1.411     www      7861: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7862: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7863: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7864: 	    if ($correct_ids{$id} eq 'specified') {
                   7865: 		$result.=&mt('specified');
                   7866: 	    } else {
                   7867: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7868: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7869: 	    }
                   7870: 	    $number++;
                   7871: 	}
1.411     www      7872:         $result.="</p>\n";
1.408     albertel 7873: 	if ($number==0) {
                   7874: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7875: 	    return $result.&show_grading_menu_form($symb);
                   7876: 	}
1.404     www      7877:     }
1.405     www      7878:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7879:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7880: 		     '<span class="LC_error">',
                   7881: 		     '</span>',
                   7882: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7883:         return $result.&show_grading_menu_form($symb);
                   7884:     }
1.410     www      7885: 
                   7886: # Were able to get all the info needed, now analyze the file
                   7887: 
1.411     www      7888:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7889:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7890:     my $heading=&mt('Scanning clicker file');
                   7891:     $result.=(<<ENDHEADER);
                   7892: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7893: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7894: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7895: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7896: <input type="hidden" name="symb" value="$symb" />
                   7897: <input type="hidden" name="command" value="assignclickergrades" />
                   7898: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7899: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7900: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7901: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7902: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7903: ENDHEADER
1.408     albertel 7904:     my %responses;
                   7905:     my @questiontitles;
1.405     www      7906:     my $errormsg='';
                   7907:     my $number=0;
                   7908:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7909: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7910:     }
1.419     www      7911:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7912:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7913:     }
1.411     www      7914:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7915:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7916:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7917:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7918:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7919:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7920:              '<br />';
1.414     www      7921: # Remember Question Titles
                   7922: # FIXME: Possibly need delimiter other than ":"
                   7923:     for (my $i=0;$i<$number;$i++) {
                   7924:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7925:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7926:     }
1.411     www      7927:     my $correct_count=0;
                   7928:     my $student_count=0;
                   7929:     my $unknown_count=0;
1.414     www      7930: # Match answers with usernames
                   7931: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7932:     foreach my $id (keys(%responses)) {
1.410     www      7933:        if ($correct_ids{$id}) {
1.414     www      7934:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7935:           $correct_count++;
1.410     www      7936:        } elsif ($clicker_ids{$id}) {
1.437     www      7937:           if ($clicker_ids{$id}=~/\,/) {
                   7938: # More than one user with the same clicker!
                   7939:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7940:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7941:                            "<select name='multi".$id."'>";
                   7942:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7943:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7944:              }
                   7945:              $result.='</select>';
                   7946:              $unknown_count++;
                   7947:           } else {
                   7948: # Good: found one and only one user with the right clicker
                   7949:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7950:              $student_count++;
                   7951:           }
1.410     www      7952:        } else {
1.411     www      7953:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7954:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7955:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7956:                    "\n".&mt("Domain").": ".
                   7957:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7958:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7959:           $unknown_count++;
1.410     www      7960:        }
1.405     www      7961:     }
1.412     www      7962:     $result.='<hr />'.
                   7963:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7964:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7965:        if ($correct_count==0) {
                   7966:           $errormsg.="Found no correct answers answers for grading!";
                   7967:        } elsif ($correct_count>1) {
1.414     www      7968:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7969:        }
                   7970:     }
1.428     www      7971:     if ($number<1) {
                   7972:        $errormsg.="Found no questions.";
                   7973:     }
1.412     www      7974:     if ($errormsg) {
                   7975:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7976:     } else {
                   7977:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7978:     }
                   7979:     $result.='</form></td></tr></table>'."\n".
1.410     www      7980:              '</td></tr></table><br /><br />'."\n";
1.404     www      7981:     return $result.&show_grading_menu_form($symb);
1.400     www      7982: }
                   7983: 
1.405     www      7984: sub iclicker_eval {
1.406     www      7985:     my ($questiontitles,$responses)=@_;
1.405     www      7986:     my $number=0;
                   7987:     my $errormsg='';
                   7988:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7989:         my %components=&Apache::loncommon::record_sep($line);
                   7990:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7991: 	if ($entries[0] eq 'Question') {
                   7992: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7993: 		$$questiontitles[$number]=$entries[$i];
                   7994: 		$number++;
                   7995: 	    }
                   7996: 	}
                   7997: 	if ($entries[0]=~/^\#/) {
                   7998: 	    my $id=$entries[0];
                   7999: 	    my @idresponses;
                   8000: 	    $id=~s/^[\#0]+//;
                   8001: 	    for (my $i=0;$i<$number;$i++) {
                   8002: 		my $idx=3+$i*6;
                   8003: 		push(@idresponses,$entries[$idx]);
                   8004: 	    }
                   8005: 	    $$responses{$id}=join(',',@idresponses);
                   8006: 	}
1.405     www      8007:     }
                   8008:     return ($errormsg,$number);
                   8009: }
                   8010: 
1.419     www      8011: sub interwrite_eval {
                   8012:     my ($questiontitles,$responses)=@_;
                   8013:     my $number=0;
                   8014:     my $errormsg='';
1.420     www      8015:     my $skipline=1;
                   8016:     my $questionnumber=0;
                   8017:     my %idresponses=();
1.419     www      8018:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8019:         my %components=&Apache::loncommon::record_sep($line);
                   8020:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8021:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8022:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8023:         next if $skipline;
                   8024:         if ($entries[0]!=$questionnumber) {
                   8025:            $questionnumber=$entries[0];
                   8026:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8027:            $number++;
1.419     www      8028:         }
1.420     www      8029:         my $id=$entries[4];
                   8030:         $id=~s/^[\#0]+//;
1.421     www      8031:         $id=~s/^v\d*\://i;
                   8032:         $id=~s/[\-\:]//g;
1.420     www      8033:         $idresponses{$id}[$number]=$entries[6];
                   8034:     }
                   8035:     foreach my $id (keys %idresponses) {
                   8036:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8037:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8038:     }
                   8039:     return ($errormsg,$number);
                   8040: }
                   8041: 
1.414     www      8042: sub assign_clicker_grades {
                   8043:     my ($r)=@_;
                   8044:     my ($symb)=&get_symb($r);
                   8045:     if (!$symb) {return '';}
1.416     www      8046: # See which part we are saving to
                   8047:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8048: # FIXME: This should probably look for the first handgradeable part
                   8049:     my $part=$$partlist[0];
                   8050: # Start screen output
1.414     www      8051:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8052: 
1.414     www      8053:     my $heading=&mt('Assigning grades based on clicker file');
                   8054:     $result.=(<<ENDHEADER);
                   8055: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8056: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8057: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8058: ENDHEADER
                   8059: # Get correct result
                   8060: # FIXME: Possibly need delimiter other than ":"
                   8061:     my @correct=();
1.415     www      8062:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8063:     my $number=$env{'form.number'};
                   8064:     if ($gradingmechanism ne 'attendance') {
1.414     www      8065:        foreach my $key (keys(%env)) {
                   8066:           if ($key=~/^form\.correct\:/) {
                   8067:              my @input=split(/\,/,$env{$key});
                   8068:              for (my $i=0;$i<=$#input;$i++) {
                   8069:                  if (($correct[$i]) && ($input[$i]) &&
                   8070:                      ($correct[$i] ne $input[$i])) {
                   8071:                     $result.='<br /><span class="LC_warning">'.
                   8072:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8073:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8074:                  } elsif ($input[$i]) {
                   8075:                     $correct[$i]=$input[$i];
                   8076:                  }
                   8077:              }
                   8078:           }
                   8079:        }
1.415     www      8080:        for (my $i=0;$i<$number;$i++) {
1.414     www      8081:           if (!$correct[$i]) {
                   8082:              $result.='<br /><span class="LC_error">'.
                   8083:                       &mt('No correct result given for question "[_1]"!',
                   8084:                           $env{'form.question:'.$i}).'</span>';
                   8085:           }
                   8086:        }
                   8087:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8088:     }
                   8089: # Start grading
1.415     www      8090:     my $pcorrect=$env{'form.pcorrect'};
                   8091:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8092:     my $storecount=0;
1.415     www      8093:     foreach my $key (keys(%env)) {
1.420     www      8094:        my $user='';
1.415     www      8095:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8096:           $user=$1;
                   8097:        }
                   8098:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8099:           my $id=$1;
                   8100:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8101:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8102:           } elsif ($env{'form.multi'.$id}) {
                   8103:              $user=$env{'form.multi'.$id};
1.420     www      8104:           }
                   8105:        }
                   8106:        if ($user) { 
1.415     www      8107:           my @answer=split(/\,/,$env{$key});
                   8108:           my $sum=0;
                   8109:           for (my $i=0;$i<$number;$i++) {
                   8110:              if ($answer[$i]) {
                   8111:                 if ($gradingmechanism eq 'attendance') {
                   8112:                    $sum+=$pcorrect;
                   8113:                 } else {
                   8114:                    if ($answer[$i] eq $correct[$i]) {
                   8115:                       $sum+=$pcorrect;
                   8116:                    } else {
                   8117:                       $sum+=$pincorrect;
                   8118:                    }
                   8119:                 }
                   8120:              }
                   8121:           }
1.416     www      8122:           my $ave=$sum/(100*$number);
                   8123: # Store
                   8124:           my ($username,$domain)=split(/\:/,$user);
                   8125:           my %grades=();
                   8126:           $grades{"resource.$part.solved"}='correct_by_override';
                   8127:           $grades{"resource.$part.awarded"}=$ave;
                   8128:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8129:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8130:                                                  $env{'request.course.id'},
                   8131:                                                  $domain,$username);
                   8132:           if ($returncode ne 'ok') {
                   8133:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8134:           } else {
                   8135:              $storecount++;
                   8136:           }
1.415     www      8137:        }
                   8138:     }
                   8139: # We are done
1.416     www      8140:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8141:              '</td></tr></table>'."\n".
1.414     www      8142:              '</td></tr></table><br /><br />'."\n";
                   8143:     return $result.&show_grading_menu_form($symb);
                   8144: }
                   8145: 
1.1       albertel 8146: sub handler {
1.41      ng       8147:     my $request=$_[0];
1.434     albertel 8148:     &reset_caches();
1.257     albertel 8149:     if ($env{'browser.mathml'}) {
1.141     www      8150: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8151:     } else {
1.141     www      8152: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8153:     }
                   8154:     $request->send_http_header;
1.44      ng       8155:     return '' if $request->header_only;
1.41      ng       8156:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8157:     my $symb=&get_symb($request,1);
1.160     albertel 8158:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8159:     my $command=$commands[0];
1.447     foxr     8160: 
1.160     albertel 8161:     if ($#commands > 0) {
                   8162: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8163:     }
1.447     foxr     8164: 
                   8165: 
1.353     albertel 8166:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8167:     if ($symb eq '' && $command eq '') {
1.257     albertel 8168: 	if ($env{'user.adv'}) {
                   8169: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8170: 		($env{'form.codethree'})) {
                   8171: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8172: 		    $env{'form.codethree'};
1.41      ng       8173: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8174: 		    &Apache::lonnet::checkin($token);
                   8175: 		if ($tsymb) {
1.137     albertel 8176: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8177: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8178: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8179: 					  ('grade_username' => $tuname,
                   8180: 					   'grade_domain' => $tudom,
                   8181: 					   'grade_courseid' => $tcrsid,
                   8182: 					   'grade_symb' => $tsymb)));
1.41      ng       8183: 		    } else {
1.45      ng       8184: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8185: 		    }
1.41      ng       8186: 		} else {
1.45      ng       8187: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8188: 		}
1.14      www      8189: 	    } else {
1.41      ng       8190: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8191: 	    }
                   8192: 	}
                   8193:     } else {
1.285     albertel 8194: 	&init_perm();
1.104     albertel 8195: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8196: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8197: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8198: 	    &pickStudentPage($request);
1.103     albertel 8199: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8200: 	    &displayPage($request);
1.104     albertel 8201: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8202: 	    &updateGradeByPage($request);
1.104     albertel 8203: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8204: 	    &processGroup($request);
1.104     albertel 8205: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8206: 	    $request->print(&grading_menu($request));
                   8207: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8208: 	    $request->print(&submit_options($request));
1.104     albertel 8209: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8210: 	    $request->print(&viewgrades($request));
1.104     albertel 8211: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8212: 	    $request->print(&processHandGrade($request));
1.106     albertel 8213: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8214: 	    $request->print(&editgrades($request));
1.106     albertel 8215: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8216: 	    $request->print(&verifyreceipt($request));
1.400     www      8217:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8218:             $request->print(&process_clicker($request));
                   8219:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8220:             $request->print(&process_clicker_file($request));
1.414     www      8221:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8222:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8223: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8224: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8225: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8226: 	    $request->print(&csvupload($request));
1.106     albertel 8227: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8228: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8229: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8230: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8231: 		$request->print(&csvuploadoptions($request));
1.41      ng       8232: 	    } else {
1.257     albertel 8233: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8234: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8235: 		} else {
1.257     albertel 8236: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8237: 		}
                   8238: 		$request->print(&csvuploadmap($request));
                   8239: 	    }
1.246     albertel 8240: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8241: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8242: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8243: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8244:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8245:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8246: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8247: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8248: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8249: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8250:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8251:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8252: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8253:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8254:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8255:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8256: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8257:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8258:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8259: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8260:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8261: 	} elsif ($command) {
1.157     albertel 8262: 	    $request->print("Access Denied ($command)");
1.26      albertel 8263: 	}
1.2       albertel 8264:     }
1.353     albertel 8265:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8266:     &reset_caches();
1.44      ng       8267:     return '';
                   8268: }
                   8269: 
1.1       albertel 8270: 1;
                   8271: 
1.13      albertel 8272: __END__;

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