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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.486   ! albertel    4: # $Id: grades.pm,v 1.485 2007/11/08 01:48:18 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.486   ! albertel  748:     
        !           749:     my $header = 
        !           750: 	&Apache::loncommon::start_data_table().
        !           751: 	&Apache::loncommon::start_data_table_header_row().
        !           752: 	'<th>&nbsp;Fullname&nbsp;</th>'."\n".
        !           753: 	'<th>&nbsp;Username&nbsp;</th>'."\n".
        !           754: 	'<th>&nbsp;Domain&nbsp;</th>';
        !           755:     if ($receiptparts) {
        !           756: 	$header.='<th>&nbsp;Problem Part&nbsp;</th>';
        !           757:     }
        !           758:     $header.=
        !           759: 	&Apache::loncommon::end_data_table_header_row();
        !           760: 
1.294     albertel  761:     foreach (sort 
                    762: 	     {
                    763: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    764: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    765: 		 }
                    766: 		 return $a cmp $b;
                    767: 	     } (keys(%$fullname))) {
1.44      ng        768: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  769: 	foreach my $part (@$parts) {
                    770: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
1.486   ! albertel  771: 		$contents.=
        !           772: 		    &Apache::loncommon::start_data_table_row().
        !           773: 		    '<td>&nbsp;'."\n".
1.177     albertel  774: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  775: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  776: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    777: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    778: 		if ($receiptparts) {
                    779: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    780: 		}
1.486   ! albertel  781: 		$contents.= 
        !           782: 		    &Apache::loncommon::end_data_table_row()."\n";
1.177     albertel  783: 		
                    784: 		$matches++;
                    785: 	    }
1.44      ng        786: 	}
                    787:     }
                    788:     if ($matches == 0) {
                    789: 	$string = $title.'No match found for the above receipt.';
                    790:     } else {
1.324     albertel  791: 	$string = &jscriptNform($symb).$title.
1.44      ng        792: 	    'The above receipt matches the following student'.
                    793: 	    ($matches <= 1 ? '.' : 's.')."\n".
1.486   ! albertel  794: 	    $header.
        !           795: 	    $contents.
        !           796: 	    &Apache::loncommon::end_data_table()."\n";
1.44      ng        797:     }
1.324     albertel  798:     return $string.&show_grading_menu_form($symb);
1.44      ng        799: }
                    800: 
                    801: #--- This is called by a number of programs.
                    802: #--- Called from the Grading Menu - View/Grade an individual student
                    803: #--- Also called directly when one clicks on the subm button 
                    804: #    on the problem page.
1.30      ng        805: sub listStudents {
1.41      ng        806:     my ($request) = shift;
1.49      albertel  807: 
1.324     albertel  808:     my ($symb) = &get_symb($request);
1.257     albertel  809:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    810:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    811:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  812:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  813:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    814:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    815:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    816: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  817: 
1.485     albertel  818:     my $result='<h3><span class="LC_info">&nbsp;'.
                    819: 	&mt($viewgrade.' Submissions for a Student or a Group of Students')
                    820: 	.'</span></h3>';
1.118     ng        821: 
1.324     albertel  822:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  823: 
1.485     albertel  824:     my %lt = ( 'multiple' =>
                    825: 	       "Please select a student or group of students before clicking on the Next button.",
                    826: 	       'single'   =>
                    827: 	       "Please select the student before clicking on the Next button.",
                    828: 	       );
                    829:     %lt = &Apache::lonlocal::texthash(%lt);
1.45      ng        830:     $request->print(<<LISTJAVASCRIPT);
                    831: <script type="text/javascript" language="javascript">
1.110     ng        832:     function checkSelect(checkBox) {
                    833: 	var ctr=0;
                    834: 	var sense="";
                    835: 	if (checkBox.length > 1) {
                    836: 	    for (var i=0; i<checkBox.length; i++) {
                    837: 		if (checkBox[i].checked) {
                    838: 		    ctr++;
                    839: 		}
                    840: 	    }
1.485     albertel  841: 	    sense = '$lt{'multiple'}';
1.110     ng        842: 	} else {
                    843: 	    if (checkBox.checked) {
                    844: 		ctr = 1;
                    845: 	    }
1.485     albertel  846: 	    sense = '$lt{'single'}';
1.110     ng        847: 	}
                    848: 	if (ctr == 0) {
1.485     albertel  849: 	    alert(sense);
1.110     ng        850: 	    return false;
                    851: 	}
                    852: 	document.gradesub.submit();
                    853:     }
                    854: 
                    855:     function reLoadList(formname) {
1.112     ng        856: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        857: 	formname.command.value = 'submission';
                    858: 	formname.submit();
                    859:     }
1.45      ng        860: </script>
                    861: LISTJAVASCRIPT
                    862: 
1.118     ng        863:     &commonJSfunctions($request);
1.41      ng        864:     $request->print($result);
1.39      ng        865: 
1.401     albertel  866:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    867:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  868:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
1.485     albertel  869: 	"\n".$table;
                    870: 	
                    871:     $gradeTable .= 
                    872: 	'&nbsp;'.
                    873: 	&mt('<b>View Problem Text: </b>[_1]',
                    874: 	    '<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                    875: 	    '<label><input type="radio" name="vProb" value="yes" /> '.&mt('one student').' </label>'."\n".
                    876: 	    '<label><input type="radio" name="vProb" value="all" /> '.&mt('all students').' </label>').'<br />'."\n";
                    877:     $gradeTable .= 
                    878: 	'&nbsp;'.
                    879: 	&mt('<b>View Answer: </b>[_1]',
                    880: 	    '<label><input type="radio" name="vAns" value="no"  /> '.&mt('no').' </label>'."\n".
                    881: 	    '<label><input type="radio" name="vAns" value="yes" /> '.&mt('one student').' </label>'."\n".
                    882: 	    '<label><input type="radio" name="vAns" value="all" checked="checked" /> '.&mt('all students').' </label>').'<br />'."\n";
                    883: 
                    884:     my $submission_options;
1.257     albertel  885:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.485     albertel  886: 	$submission_options.=
                    887: 	    '<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> '.&mt('essay part only').' </label>'."\n";
1.49      albertel  888:     }
1.442     banghart  889:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    890:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  891:     $env{'form.Status'} = $saveStatus;
1.485     albertel  892:     $submission_options.=
                    893: 	'<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> '.&mt('last submission only').' </label>'."\n".
                    894: 	'<label><input type="radio" name="lastSub" value="last" /> '.&mt('last submission &amp; parts info').' </label>'."\n".
                    895: 	'<label><input type="radio" name="lastSub" value="datesub" /> '.&mt('by dates and submissions').' </label>'."\n".
                    896: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').'</label>';
                    897:     $gradeTable .= 
                    898: 	'&nbsp;'.
                    899: 	&mt('<b>Submissions: </b>[_1]',$submission_options).'<br />'."\n";
                    900: 
                    901:     $gradeTable .= 
                    902:         '&nbsp;'.
                    903: 	&mt('<b>Grading Increments:</b> [_1]',
                    904: 	    '<select name="increment">'.
                    905: 	    '<option value="1">'.&mt('Whole Points').'</option>'.
                    906: 	    '<option value=".5">'.&mt('Half Points').'</option>'.
                    907: 	    '<option value=".25">'.&mt('Quarter Points').'</option>'.
                    908: 	    '<option value=".1">'.&mt('Tenths of a Point').'</option>'.
                    909: 	    '</select>');
                    910:     
                    911:     $gradeTable .= 
1.432     banghart  912:         &build_section_inputs().
1.45      ng        913: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  914: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    915: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    916: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    917: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  918: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        919: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    920: 
1.257     albertel  921:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  922: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        923:     } else {
1.485     albertel  924: 	$gradeTable.=&mt('<b>Student Status:</b> [_1]',
                    925: 			 &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);')).'<br />';
1.124     ng        926:     }
1.112     ng        927: 
1.485     albertel  928:     $gradeTable.=&mt('To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    929: 	'next to the student\'s name(s). Then click on the Next button.').'<br />'."\n".
1.110     ng        930: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  931: 
                    932: # checkall buttons
                    933:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        934:     $gradeTable.='<input type="button" '."\n".
1.45      ng        935: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.485     albertel  936: 	'value="'.&mt('Next-&gt;').'" /> <br />'."\n";
1.249     albertel  937:     $gradeTable.=&check_buttons();
1.485     albertel  938:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />'.&mt('Check For Plagiarism').'</label>';
1.450     banghart  939:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  940:     $gradeTable.= &Apache::loncommon::start_data_table().
                    941: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        942:     my $loop = 0;
                    943:     while ($loop < 2) {
1.485     albertel  944: 	$gradeTable.='<th>'.&mt('No.').'</th><th>'.&mt('Select').'</th>'.
                    945: 	    '<th>'.&nameUserString('header').'&nbsp;'.&mt('Section/Group').'</th>';
1.301     albertel  946: 	if ($env{'form.showgrading'} eq 'yes' 
                    947: 	    && $submitonly ne 'queued'
                    948: 	    && $submitonly ne 'all') {
1.485     albertel  949: 	    foreach my $part (sort(@$partlist)) {
                    950: 		my $display_part=
                    951: 		    &get_display_part((split(/_/,$part))[0],$symb);
                    952: 		$gradeTable.=
                    953: 		    '<th>'.&mt('Part: [_1] Status',$display_part).'</th>';
1.110     ng        954: 	    }
1.301     albertel  955: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  956: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        957: 	}
                    958: 	$loop++;
1.126     ng        959: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        960:     }
1.474     albertel  961:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        962: 
1.45      ng        963:     my $ctr = 0;
1.294     albertel  964:     foreach my $student (sort 
                    965: 			 {
                    966: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    967: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    968: 			     }
                    969: 			     return $a cmp $b;
                    970: 			 }
                    971: 			 (keys(%$fullname))) {
1.41      ng        972: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  973: 
1.110     ng        974: 	my %status = ();
1.301     albertel  975: 
                    976: 	if ($submitonly eq 'queued') {
                    977: 	    my %queue_status = 
                    978: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    979: 							$udom,$uname);
                    980: 	    next if (!defined($queue_status{'gradingqueue'}));
                    981: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    982: 	}
                    983: 
                    984: 	if ($env{'form.showgrading'} eq 'yes' 
                    985: 	    && $submitonly ne 'queued'
                    986: 	    && $submitonly ne 'all') {
1.324     albertel  987: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  988: 	    my $submitted = 0;
1.164     albertel  989: 	    my $graded = 0;
1.248     albertel  990: 	    my $incorrect = 0;
1.110     ng        991: 	    foreach (keys(%status)) {
1.145     albertel  992: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  993: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    994: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    995: 		
1.110     ng        996: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    997: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  998: 		    $submitted = 0;
1.150     albertel  999: 		    my ($part)=split(/\./,$partid);
1.110     ng       1000: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel 1001: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng       1002: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                   1003: 		}
1.41      ng       1004: 	    }
1.248     albertel 1005: 	    
1.156     albertel 1006: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   1007: 				     $submitonly eq 'incorrect' ||
                   1008: 				     $submitonly eq 'graded'));
1.248     albertel 1009: 	    next if (!$graded && ($submitonly eq 'graded'));
                   1010: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       1011: 	}
1.34      ng       1012: 
1.45      ng       1013: 	$ctr++;
1.249     albertel 1014: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart 1015:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel 1016: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel 1017: 	    if ($ctr%2 ==1) {
                   1018: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                   1019: 	    }
1.126     ng       1020: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel 1021:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                   1022:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                   1023: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                   1024: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel 1025: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng       1026: 
1.257     albertel 1027: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng       1028: 		foreach (sort keys(%status)) {
1.485     albertel 1029: 		    next if ($_ =~ /^resource.*?submitted_by$/);
                   1030: 		    $gradeTable.='<td align="center">&nbsp;'.&mt($status{$_}).'&nbsp;</td>'."\n";
1.110     ng       1031: 		}
1.41      ng       1032: 	    }
1.126     ng       1033: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel 1034: 	    if ($ctr%2 ==0) {
                   1035: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1036: 	    }
1.41      ng       1037: 	}
                   1038:     }
1.110     ng       1039:     if ($ctr%2 ==1) {
1.126     ng       1040: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1041: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1042: 		&& $submitonly ne 'queued'
                   1043: 		&& $submitonly ne 'all') {
1.110     ng       1044: 		foreach (@$partlist) {
                   1045: 		    $gradeTable.='<td>&nbsp;</td>';
                   1046: 		}
1.301     albertel 1047: 	    } elsif ($submitonly eq 'queued') {
                   1048: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1049: 	    }
1.474     albertel 1050: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1051:     }
                   1052: 
1.474     albertel 1053:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1054: 	'<input type="button" '.
                   1055: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.485     albertel 1056: 	'value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.45      ng       1057:     if ($ctr == 0) {
1.96      albertel 1058: 	my $num_students=(scalar(keys(%$fullname)));
                   1059: 	if ($num_students eq 0) {
1.485     albertel 1060: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.&mt('There are no students currently enrolled.').'</span>';
1.96      albertel 1061: 	} else {
1.171     albertel 1062: 	    my $submissions='submissions';
                   1063: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1064: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1065: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1066: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.485     albertel 1067: 		&mt('No '.$submissions.' found for this resource for any students. ([_1] students checked for '.$submissions.')',
                   1068: 		    $num_students).
                   1069: 		'</span><br />';
1.96      albertel 1070: 	}
1.46      ng       1071:     } elsif ($ctr == 1) {
1.474     albertel 1072: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1073:     }
1.324     albertel 1074:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1075:     $request->print($gradeTable);
1.44      ng       1076:     return '';
1.10      ng       1077: }
                   1078: 
1.44      ng       1079: #---- Called from the listStudents routine
1.249     albertel 1080: 
                   1081: sub check_script {
                   1082:     my ($form, $type)=@_;
                   1083:     my $chkallscript='<script type="text/javascript">
                   1084:     function checkall() {
                   1085:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1086:             ele = document.forms.'.$form.'.elements[i];
                   1087:             if (ele.name == "'.$type.'") {
                   1088:             document.forms.'.$form.'.elements[i].checked=true;
                   1089:                                        }
                   1090:         }
                   1091:     }
                   1092: 
                   1093:     function checksec() {
                   1094:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1095:             ele = document.forms.'.$form.'.elements[i];
                   1096:            string = document.forms.'.$form.'.chksec.value;
                   1097:            if
                   1098:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1099:               document.forms.'.$form.'.elements[i].checked=true;
                   1100:             }
                   1101:         }
                   1102:     }
                   1103: 
                   1104: 
                   1105:     function uncheckall() {
                   1106:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1107:             ele = document.forms.'.$form.'.elements[i];
                   1108:             if (ele.name == "'.$type.'") {
                   1109:             document.forms.'.$form.'.elements[i].checked=false;
                   1110:                                        }
                   1111:         }
                   1112:     }
                   1113: 
                   1114: </script>'."\n";
                   1115:     return $chkallscript;
                   1116: }
                   1117: 
                   1118: sub check_buttons {
1.485     albertel 1119:     my $buttons.='<input type="button" onclick="checkall()" value="'.&mt('Check All').'" />';
                   1120:     $buttons.='<input type="button" onclick="uncheckall()" value="'.&mt('Uncheck All').'" />&nbsp;';
                   1121:     $buttons.='<input type="button" onclick="checksec()" value="'.&mt('Check Section/Group').'" />';
1.249     albertel 1122:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1123:     return $buttons;
                   1124: }
                   1125: 
1.44      ng       1126: #     Displays the submissions for one student or a group of students
1.34      ng       1127: sub processGroup {
1.41      ng       1128:     my ($request)  = shift;
                   1129:     my $ctr        = 0;
1.155     albertel 1130:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1131:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1132: 
1.396     banghart 1133:     foreach my $student (@stuchecked) {
                   1134: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1135: 	$env{'form.student'}        = $uname;
                   1136: 	$env{'form.userdom'}        = $udom;
                   1137: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1138: 	&submission($request,$ctr,$total);
                   1139: 	$ctr++;
                   1140:     }
                   1141:     return '';
1.35      ng       1142: }
1.34      ng       1143: 
1.44      ng       1144: #------------------------------------------------------------------------------------
                   1145: #
                   1146: #-------------------------- Next few routines handles grading by student, essentially
                   1147: #                           handles essay response type problem/part
                   1148: #
                   1149: #--- Javascript to handle the submission page functionality ---
                   1150: sub sub_page_js {
                   1151:     my $request = shift;
                   1152:     $request->print(<<SUBJAVASCRIPT);
                   1153: <script type="text/javascript" language="javascript">
1.71      ng       1154:     function updateRadio(formname,id,weight) {
1.125     ng       1155: 	var gradeBox = formname["GD_BOX"+id];
                   1156: 	var radioButton = formname["RADVAL"+id];
                   1157: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1158: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1159: 	gradeBox.value = pts;
                   1160: 	var resetbox = false;
                   1161: 	if (isNaN(pts) || pts < 0) {
                   1162: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1163: 	    for (var i=0; i<radioButton.length; i++) {
                   1164: 		if (radioButton[i].checked) {
                   1165: 		    gradeBox.value = i;
                   1166: 		    resetbox = true;
                   1167: 		}
                   1168: 	    }
                   1169: 	    if (!resetbox) {
                   1170: 		formtextbox.value = "";
                   1171: 	    }
                   1172: 	    return;
1.44      ng       1173: 	}
1.71      ng       1174: 
                   1175: 	if (pts > weight) {
                   1176: 	    var resp = confirm("You entered a value ("+pts+
                   1177: 			       ") greater than the weight for the part. Accept?");
                   1178: 	    if (resp == false) {
1.125     ng       1179: 		gradeBox.value = oldpts;
1.71      ng       1180: 		return;
                   1181: 	    }
1.44      ng       1182: 	}
1.13      albertel 1183: 
1.71      ng       1184: 	for (var i=0; i<radioButton.length; i++) {
                   1185: 	    radioButton[i].checked=false;
                   1186: 	    if (pts == i && pts != "") {
                   1187: 		radioButton[i].checked=true;
                   1188: 	    }
                   1189: 	}
                   1190: 	updateSelect(formname,id);
1.125     ng       1191: 	formname["stores"+id].value = "0";
1.41      ng       1192:     }
1.5       albertel 1193: 
1.72      ng       1194:     function writeBox(formname,id,pts) {
1.125     ng       1195: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1196: 	if (checkSolved(formname,id) == 'update') {
                   1197: 	    gradeBox.value = pts;
                   1198: 	} else {
1.125     ng       1199: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1200: 	    gradeBox.value = oldpts;
1.125     ng       1201: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1202: 	    for (var i=0; i<radioButton.length; i++) {
                   1203: 		radioButton[i].checked=false;
1.72      ng       1204: 		if (i == oldpts) {
1.71      ng       1205: 		    radioButton[i].checked=true;
                   1206: 		}
                   1207: 	    }
1.41      ng       1208: 	}
1.125     ng       1209: 	formname["stores"+id].value = "0";
1.71      ng       1210: 	updateSelect(formname,id);
                   1211: 	return;
1.41      ng       1212:     }
1.44      ng       1213: 
1.71      ng       1214:     function clearRadBox(formname,id) {
                   1215: 	if (checkSolved(formname,id) == 'noupdate') {
                   1216: 	    updateSelect(formname,id);
                   1217: 	    return;
                   1218: 	}
1.125     ng       1219: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1220: 	for (var i=0; i<gradeSelect.length; i++) {
                   1221: 	    if (gradeSelect[i].selected) {
                   1222: 		var selectx=i;
                   1223: 	    }
                   1224: 	}
1.125     ng       1225: 	var stores = formname["stores"+id];
1.71      ng       1226: 	if (selectx == stores.value) { return };
1.125     ng       1227: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1228: 	gradeBox.value = "";
1.125     ng       1229: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1230: 	for (var i=0; i<radioButton.length; i++) {
                   1231: 	    radioButton[i].checked=false;
                   1232: 	}
                   1233: 	stores.value = selectx;
                   1234:     }
1.5       albertel 1235: 
1.71      ng       1236:     function checkSolved(formname,id) {
1.125     ng       1237: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1238: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1239: 	    if (!reply) {return "noupdate";}
1.120     ng       1240: 	    formname.overRideScore.value = 'yes';
1.41      ng       1241: 	}
1.71      ng       1242: 	return "update";
1.13      albertel 1243:     }
1.71      ng       1244: 
                   1245:     function updateSelect(formname,id) {
1.125     ng       1246: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1247: 	return;
1.41      ng       1248:     }
1.33      ng       1249: 
1.121     ng       1250: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1251:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1252: 	formname.gradeOpt.value = val;
1.71      ng       1253: 	if (val == "Save & Next") {
                   1254: 	    for (i=0;i<=total;i++) {
                   1255: 		for (j=0;j<parttot;j++) {
1.125     ng       1256: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1257: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1258: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1259: 			if (points == "") {
1.125     ng       1260: 			    var name = formname["name"+i].value;
1.129     ng       1261: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1262: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1263: 					       ", part "+partid+". Continue?");
1.71      ng       1264: 			    if (resp == false) {
1.125     ng       1265: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1266: 				return false;
                   1267: 			    }
                   1268: 			}
                   1269: 		    }
                   1270: 		    
                   1271: 		}
                   1272: 	    }
                   1273: 	    
                   1274: 	}
1.121     ng       1275: 	if (val == "Grade Student") {
                   1276: 	    formname.showgrading.value = "yes";
                   1277: 	    if (formname.Status.value == "") {
                   1278: 		formname.Status.value = "Active";
                   1279: 	    }
                   1280: 	    formname.studentNo.value = total;
                   1281: 	}
1.120     ng       1282: 	formname.submit();
                   1283:     }
                   1284: 
1.71      ng       1285: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1286:     function checkSubmitPage(formname,total) {
                   1287: 	noscore = new Array(100);
                   1288: 	var ptr = 0;
                   1289: 	for (i=1;i<total;i++) {
1.125     ng       1290: 	    var partid = formname["q_"+i].value;
1.127     ng       1291: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1292: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1293: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1294: 		if (points == "" && status != "correct_by_student") {
                   1295: 		    noscore[ptr] = i;
                   1296: 		    ptr++;
                   1297: 		}
                   1298: 	    }
                   1299: 	}
                   1300: 	if (ptr != 0) {
                   1301: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1302: 	    var prolist = "";
                   1303: 	    if (ptr == 1) {
                   1304: 		prolist = noscore[0];
                   1305: 	    } else {
                   1306: 		var i = 0;
                   1307: 		while (i < ptr-1) {
                   1308: 		    prolist += noscore[i]+", ";
                   1309: 		    i++;
                   1310: 		}
                   1311: 		prolist += "and "+noscore[i];
                   1312: 	    }
                   1313: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1314: 	    if (resp == false) {
                   1315: 		return false;
                   1316: 	    }
                   1317: 	}
1.45      ng       1318: 
1.71      ng       1319: 	formname.submit();
                   1320:     }
                   1321: </script>
                   1322: SUBJAVASCRIPT
                   1323: }
1.45      ng       1324: 
1.71      ng       1325: #--- javascript for essay type problem --
                   1326: sub sub_page_kw_js {
                   1327:     my $request = shift;
1.80      ng       1328:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1329:     &commonJSfunctions($request);
1.350     albertel 1330: 
1.351     albertel 1331:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1332:     <script text="text/javascript">
                   1333:     function checkInput() {
                   1334:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1335:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1336:       var usrctr = document.msgcenter.usrctr.value;
                   1337:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1338:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1339: 
                   1340:       var msgchk = "";
                   1341:       if (document.msgcenter.subchk.checked) {
                   1342:          msgchk = "msgsub,";
                   1343:       }
                   1344:       var includemsg = 0;
                   1345:       for (var i=1; i<=nmsg; i++) {
                   1346:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1347:           var frmmsg = document.msgcenter["msg"+i];
                   1348:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1349:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1350:           showflg.value = "1";
                   1351:           var chkbox = document.msgcenter["msgn"+i];
                   1352:           if (chkbox.checked) {
                   1353:              msgchk += "savemsg"+i+",";
                   1354:              includemsg = 1;
                   1355:           }
                   1356:       }
                   1357:       if (document.msgcenter.newmsgchk.checked) {
                   1358:          msgchk += "newmsg"+usrctr;
                   1359:          includemsg = 1;
                   1360:       }
                   1361:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1362:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1363:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1364:       includemsg.value = msgchk;
                   1365: 
                   1366:       self.close()
                   1367: 
                   1368:     }
                   1369:     </script>
                   1370: INNERJS
                   1371: 
1.351     albertel 1372:     my $inner_js_highlight_central=<<INNERJS;
                   1373:  <script type="text/javascript">
                   1374:     function updateChoice(flag) {
                   1375:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1376:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1377:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1378:       opener.document.SCORE.refresh.value = "on";
                   1379:       if (opener.document.SCORE.keywords.value!=""){
                   1380:          opener.document.SCORE.submit();
                   1381:       }
                   1382:       self.close()
                   1383:     }
                   1384: </script>
                   1385: INNERJS
                   1386: 
                   1387:     my $start_page_msg_central = 
                   1388:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1389: 				       {'js_ready'  => 1,
                   1390: 					'only_body' => 1,
                   1391: 					'bgcolor'   =>'#FFFFFF',});
                   1392:     my $end_page_msg_central = 
                   1393: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1394: 
                   1395: 
                   1396:     my $start_page_highlight_central = 
                   1397:         &Apache::loncommon::start_page('Highlight Central',
                   1398: 				       $inner_js_highlight_central,
1.350     albertel 1399: 				       {'js_ready'  => 1,
                   1400: 					'only_body' => 1,
                   1401: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1402:     my $end_page_highlight_central = 
1.350     albertel 1403: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1404: 
1.219     www      1405:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1406:     $docopen=~s/^document\.//;
1.71      ng       1407:     $request->print(<<SUBJAVASCRIPT);
                   1408: <script type="text/javascript" language="javascript">
1.45      ng       1409: 
1.44      ng       1410: //===================== Show list of keywords ====================
1.122     ng       1411:   function keywords(formname) {
                   1412:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1413:     if (nret==null) return;
1.122     ng       1414:     formname.keywords.value = nret;
1.44      ng       1415: 
1.122     ng       1416:     if (formname.keywords.value != "") {
1.128     ng       1417: 	formname.refresh.value = "on";
1.122     ng       1418: 	formname.submit();
1.44      ng       1419:     }
                   1420:     return;
                   1421:   }
                   1422: 
                   1423: //===================== Script to view submitted by ==================
                   1424:   function viewSubmitter(submitter) {
                   1425:     document.SCORE.refresh.value = "on";
                   1426:     document.SCORE.NCT.value = "1";
                   1427:     document.SCORE.unamedom0.value = submitter;
                   1428:     document.SCORE.submit();
                   1429:     return;
                   1430:   }
                   1431: 
                   1432: //===================== Script to add keyword(s) ==================
                   1433:   function getSel() {
                   1434:     if (document.getSelection) txt = document.getSelection();
                   1435:     else if (document.selection) txt = document.selection.createRange().text;
                   1436:     else return;
                   1437:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1438:     if (cleantxt=="") {
1.46      ng       1439: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1440: 	return;
                   1441:     }
                   1442:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1443:     if (nret==null) return;
1.127     ng       1444:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1445:     if (document.SCORE.keywords.value != "") {
1.127     ng       1446: 	document.SCORE.refresh.value = "on";
1.44      ng       1447: 	document.SCORE.submit();
                   1448:     }
                   1449:     return;
                   1450:   }
                   1451: 
                   1452: //====================== Script for composing message ==============
1.80      ng       1453:    // preload images
                   1454:    img1 = new Image();
                   1455:    img1.src = "$iconpath/mailbkgrd.gif";
                   1456:    img2 = new Image();
                   1457:    img2.src = "$iconpath/mailto.gif";
                   1458: 
1.44      ng       1459:   function msgCenter(msgform,usrctr,fullname) {
                   1460:     var Nmsg  = msgform.savemsgN.value;
                   1461:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1462:     var subject = msgform.msgsub.value;
1.127     ng       1463:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1464:     re = /msgsub/;
                   1465:     var shwsel = "";
                   1466:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1467:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1468:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1469:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1470: 	var testmsg = "savemsg"+i+",";
                   1471: 	re = new RegExp(testmsg,"g");
1.44      ng       1472: 	shwsel = "";
                   1473: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1474: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1475: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1476: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1477: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1478:     }
1.125     ng       1479:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1480:     shwsel = "";
                   1481:     re = /newmsg/;
                   1482:     if (re.test(msgchk)) { shwsel = "checked" }
                   1483:     newMsg(newmsg,shwsel);
                   1484:     msgTail(); 
                   1485:     return;
                   1486:   }
                   1487: 
1.123     ng       1488:   function checkEntities(strx) {
                   1489:     if (strx.length == 0) return strx;
                   1490:     var orgStr = ["&", "<", ">", '"']; 
                   1491:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1492:     var counter = 0;
                   1493:     while (counter < 4) {
                   1494: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1495: 	counter++;
                   1496:     }
                   1497:     return strx;
                   1498:   }
                   1499: 
                   1500:   function strReplace(strx, orgStr, newStr) {
                   1501:     return strx.split(orgStr).join(newStr);
                   1502:   }
                   1503: 
1.44      ng       1504:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1505:     var height = 70*Nmsg+250;
1.44      ng       1506:     var scrollbar = "no";
                   1507:     if (height > 600) {
                   1508: 	height = 600;
                   1509: 	scrollbar = "yes";
                   1510:     }
1.118     ng       1511:     var xpos = (screen.width-600)/2;
                   1512:     xpos = (xpos < 0) ? '0' : xpos;
                   1513:     var ypos = (screen.height-height)/2-30;
                   1514:     ypos = (ypos < 0) ? '0' : ypos;
                   1515: 
1.206     albertel 1516:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1517:     pWin.focus();
                   1518:     pDoc = pWin.document;
1.219     www      1519:     pDoc.$docopen;
1.351     albertel 1520:     pDoc.write('$start_page_msg_central');
1.76      ng       1521: 
                   1522:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1523:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1524:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1525: 
                   1526:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1527:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1528:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1529: }
                   1530:     function displaySubject(msg,shwsel) {
1.76      ng       1531:     pDoc = pWin.document;
                   1532:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1533:     pDoc.write("<td>Subject<\\/td>");
                   1534:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1535:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1536: }
                   1537: 
1.72      ng       1538:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1539:     pDoc = pWin.document;
                   1540:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1541:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1542:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1543:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1544: }
                   1545: 
                   1546:   function newMsg(newmsg,shwsel) {
1.76      ng       1547:     pDoc = pWin.document;
                   1548:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1549:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1550:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1551:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1552: }
                   1553: 
                   1554:   function msgTail() {
1.76      ng       1555:     pDoc = pWin.document;
1.465     albertel 1556:     pDoc.write("<\\/table>");
                   1557:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1558:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1559:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1560:     pDoc.write("<\\/form>");
1.351     albertel 1561:     pDoc.write('$end_page_msg_central');
1.128     ng       1562:     pDoc.close();
1.44      ng       1563: }
                   1564: 
                   1565: //====================== Script for keyword highlight options ==============
                   1566:   function kwhighlight() {
                   1567:     var kwclr    = document.SCORE.kwclr.value;
                   1568:     var kwsize   = document.SCORE.kwsize.value;
                   1569:     var kwstyle  = document.SCORE.kwstyle.value;
                   1570:     var redsel = "";
                   1571:     var grnsel = "";
                   1572:     var blusel = "";
                   1573:     if (kwclr=="red")   {var redsel="checked"};
                   1574:     if (kwclr=="green") {var grnsel="checked"};
                   1575:     if (kwclr=="blue")  {var blusel="checked"};
                   1576:     var sznsel = "";
                   1577:     var sz1sel = "";
                   1578:     var sz2sel = "";
                   1579:     if (kwsize=="0")  {var sznsel="checked"};
                   1580:     if (kwsize=="+1") {var sz1sel="checked"};
                   1581:     if (kwsize=="+2") {var sz2sel="checked"};
                   1582:     var synsel = "";
                   1583:     var syisel = "";
                   1584:     var sybsel = "";
                   1585:     if (kwstyle=="")    {var synsel="checked"};
                   1586:     if (kwstyle=="<i>") {var syisel="checked"};
                   1587:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1588:     highlightCentral();
                   1589:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1590:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1591:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1592:     highlightend();
                   1593:     return;
                   1594:   }
                   1595: 
                   1596:   function highlightCentral() {
1.76      ng       1597: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1598:     var xpos = (screen.width-400)/2;
                   1599:     xpos = (xpos < 0) ? '0' : xpos;
                   1600:     var ypos = (screen.height-330)/2-30;
                   1601:     ypos = (ypos < 0) ? '0' : ypos;
                   1602: 
1.206     albertel 1603:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1604:     hwdWin.focus();
                   1605:     var hDoc = hwdWin.document;
1.219     www      1606:     hDoc.$docopen;
1.351     albertel 1607:     hDoc.write('$start_page_highlight_central');
1.76      ng       1608:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1609:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1610: 
                   1611:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1612:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1613:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1614:   }
                   1615: 
                   1616:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1617:     var hDoc = hwdWin.document;
                   1618:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1619:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1620:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1621:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1622:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1623:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1624:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1625:     hDoc.write("<\\/tr>");
1.44      ng       1626:   }
                   1627: 
                   1628:   function highlightend() { 
1.76      ng       1629:     var hDoc = hwdWin.document;
1.465     albertel 1630:     hDoc.write("<\\/table>");
                   1631:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1632:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1633:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1634:     hDoc.write("<\\/form>");
1.351     albertel 1635:     hDoc.write('$end_page_highlight_central');
1.128     ng       1636:     hDoc.close();
1.44      ng       1637:   }
                   1638: 
                   1639: </script>
                   1640: SUBJAVASCRIPT
                   1641: }
                   1642: 
1.349     albertel 1643: sub get_increment {
1.348     bowersj2 1644:     my $increment = $env{'form.increment'};
                   1645:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1646:         $increment != .1) {
                   1647:         $increment = 1;
                   1648:     }
                   1649:     return $increment;
                   1650: }
                   1651: 
1.71      ng       1652: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1653: sub gradeBox {
1.322     albertel 1654:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1655:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 1656: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       1657:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1658:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1659:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1660:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1661:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1662: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1663:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1664:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1665:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1666: 				       [$partid]);
                   1667:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1668:     if ($last_resets{$partid}) {
                   1669:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1670:     }
1.485     albertel 1671:     $result.='<table border="0"><tr>';
1.71      ng       1672:     my $ctr = 0;
1.348     bowersj2 1673:     my $thisweight = 0;
1.349     albertel 1674:     my $increment = &get_increment();
1.485     albertel 1675: 
                   1676:     my $radio.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1677:     while ($thisweight<=$wgt) {
1.485     albertel 1678: 	$radio.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1679: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1680: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1681: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.485     albertel 1682: 	$radio.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1683:         $thisweight += $increment;
1.71      ng       1684: 	$ctr++;
                   1685:     }
1.485     albertel 1686:     $radio.='</tr></table>';
                   1687: 
                   1688:     my $line.='<input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
1.71      ng       1689: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1690: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1691: 	$wgt.')" /></td>'."\n";
1.485     albertel 1692:     $line.='<td>/'.$wgt.' '.$wgtmsg.
1.71      ng       1693: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1694: 	' </td><td>'."\n";
1.485     albertel 1695:     $line.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
1.71      ng       1696: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1697:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.485     albertel 1698: 	$line.='<option></option>'.
                   1699: 	    '<option value="excused" selected="selected">'.&mt('excused').'</option>';
1.71      ng       1700:     } else {
1.485     albertel 1701: 	$line.='<option selected="selected"></option>'.
                   1702: 	    '<option value="excused" >'.&mt('excused').'</option>';
1.71      ng       1703:     }
1.485     albertel 1704:     $line.='<option value="reset status">'.&mt('reset status').'</option></select>'."\n";
                   1705: 
                   1706: 
                   1707:     $result .= 
                   1708: 	&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);
                   1709: 
                   1710:     
                   1711:     $result.='</tr></table>'."\n";
1.71      ng       1712:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1713: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1714: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1715: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1716:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1717:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1718:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1719:         $aggtries.'" />'."\n";
1.323     banghart 1720:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1721:     return $result;
                   1722: }
1.322     albertel 1723: 
                   1724: sub handback_box {
1.323     banghart 1725:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1726:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1727:     my (@respids);
1.375     albertel 1728:      my @part_response_id = &flatten_responseType($responseType);
                   1729:     foreach my $part_response_id (@part_response_id) {
                   1730:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1731:         if ($part eq $partid) {
1.375     albertel 1732:             push(@respids,$resp);
1.323     banghart 1733:         }
                   1734:     }
1.318     banghart 1735:     my $result;
1.323     banghart 1736:     foreach my $respid (@respids) {
1.322     albertel 1737: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1738: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1739: 	next if (!@$files);
                   1740: 	my $file_counter = 1;
1.313     banghart 1741: 	foreach my $file (@$files) {
1.368     banghart 1742: 	    if ($file =~ /\/portfolio\//) {
                   1743:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1744:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1745:     	        $file_disp = "$name.$ext";
                   1746:     	        $file = $file_path.$file_disp;
                   1747:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1748:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1749:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1750:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.485     albertel 1751:     	        $result.='('.&mt('File will be uploaded when you click on Save &amp; Next below.').')<br />';
1.368     banghart 1752:     	        $file_counter++;
                   1753: 	    }
1.322     albertel 1754: 	}
1.313     banghart 1755:     }
1.318     banghart 1756:     return $result;    
1.71      ng       1757: }
1.44      ng       1758: 
1.58      albertel 1759: sub show_problem {
1.382     albertel 1760:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1761:     my $rendered;
1.382     albertel 1762:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1763:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1764:     if ($mode eq 'both' or $mode eq 'text') {
                   1765: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1766: 						       $env{'request.course.id'},
                   1767: 						       undef,\%form);
1.144     albertel 1768:     }
1.58      albertel 1769:     if ($removeform) {
                   1770: 	$rendered=~s|<form(.*?)>||g;
                   1771: 	$rendered=~s|</form>||g;
1.374     albertel 1772: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1773:     }
1.144     albertel 1774:     my $companswer;
                   1775:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1776: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1777: 	$companswer=
                   1778: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1779: 						    $env{'request.course.id'},
                   1780: 						    %form);
1.144     albertel 1781:     }
1.58      albertel 1782:     if ($removeform) {
                   1783: 	$companswer=~s|<form(.*?)>||g;
                   1784: 	$companswer=~s|</form>||g;
1.144     albertel 1785: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1786:     }
1.468     albertel 1787:     $rendered=
                   1788: 	'<div class="LC_grade_show_problem_header">'.
                   1789: 	&mt('View of the problem').
                   1790: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1791: 	$rendered.
                   1792: 	'</div>';
                   1793:     $companswer=
                   1794: 	'<div class="LC_grade_show_problem_header">'.
                   1795: 	&mt('Correct answer').
                   1796: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1797: 	$companswer.
                   1798: 	'</div>';
                   1799:     my $result;
1.144     albertel 1800:     if ($mode eq 'both') {
1.468     albertel 1801: 	$result=$rendered.$companswer;
1.144     albertel 1802:     } elsif ($mode eq 'text') {
1.468     albertel 1803: 	$result=$rendered;
1.144     albertel 1804:     } elsif ($mode eq 'answer') {
1.468     albertel 1805: 	$result=$companswer;
1.144     albertel 1806:     }
1.468     albertel 1807:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1808:     return $result;
1.58      albertel 1809: }
1.397     albertel 1810: 
1.396     banghart 1811: sub files_exist {
                   1812:     my ($r, $symb) = @_;
                   1813:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1814: 
1.396     banghart 1815:     foreach my $student (@students) {
                   1816:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1817:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1818: 					      $udom,$uname);
1.396     banghart 1819:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1820:         foreach my $submission (@$string) {
                   1821:             my ($partid,$respid) =
                   1822: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1823:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1824: 					   \%record);
                   1825:             return 1 if (@$files);
1.396     banghart 1826:         }
                   1827:     }
1.397     albertel 1828:     return 0;
1.396     banghart 1829: }
1.397     albertel 1830: 
1.394     banghart 1831: sub download_all_link {
                   1832:     my ($r,$symb) = @_;
1.395     albertel 1833:     my $all_students = 
                   1834: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1835: 
                   1836:     my $parts =
                   1837: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1838: 
1.394     banghart 1839:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1840:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1841:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1842:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1843:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1844: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1845:     return
                   1846: }
1.395     albertel 1847: 
1.432     banghart 1848: sub build_section_inputs {
                   1849:     my $section_inputs;
                   1850:     if ($env{'form.section'} eq '') {
                   1851:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1852:     } else {
                   1853:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1854:         foreach my $section (@sections) {
1.432     banghart 1855:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1856:         }
                   1857:     }
                   1858:     return $section_inputs;
                   1859: }
                   1860: 
1.44      ng       1861: # --------------------------- show submissions of a student, option to grade 
                   1862: sub submission {
                   1863:     my ($request,$counter,$total) = @_;
1.257     albertel 1864:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1865:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1866:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1867:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1868:     my $symb = &get_symb($request); 
                   1869:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1870: 
                   1871:     if (!&canview($usec)) {
1.398     albertel 1872: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1873: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1874: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1875: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1876: 	return;
                   1877:     }
                   1878: 
1.257     albertel 1879:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1880:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1881:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1882:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1883:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1884: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1885: 	'/check.gif" height="16" border="0" />';
1.41      ng       1886: 
1.426     albertel 1887:     my %old_essays;
1.41      ng       1888:     # header info
                   1889:     if ($counter == 0) {
                   1890: 	&sub_page_js($request);
1.257     albertel 1891: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1892: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1893: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1894: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1895: 	    &download_all_link($request, $symb);
                   1896: 	}
1.485     albertel 1897: 	$request->print('<h3>&nbsp;<span class="LC_info">'.&mt('Submission Record').'</span></h3>'."\n".
                   1898: 			'<h4>&nbsp;'.&mt('<b>Resource: </b> [_1]',$env{'form.probTitle'}).'</h4>'."\n");
1.118     ng       1899: 
1.44      ng       1900: 	# option to display problem, only once else it cause problems 
                   1901:         # with the form later since the problem has a form.
1.257     albertel 1902: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1903: 	    my $mode;
1.257     albertel 1904: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1905: 		$mode='both';
1.257     albertel 1906: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1907: 		$mode='text';
1.257     albertel 1908: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1909: 		$mode='answer';
                   1910: 	    }
1.329     albertel 1911: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1912: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1913: 	}
1.441     www      1914: 
1.44      ng       1915: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1916:         # if this subroutine has been called once.
1.41      ng       1917: 	my %keyhash = ();
1.257     albertel 1918: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1919: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1920: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1921: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1922: 
1.257     albertel 1923: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1924: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1925: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1926: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1927: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1928: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1929: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1930: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1931: 	}
1.257     albertel 1932: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1933: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1934: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1935: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1936: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1937: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1938: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1939: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1940: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1941: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1942: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1943: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1944: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1945: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1946: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1947: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1948: 			&build_section_inputs().
1.326     albertel 1949: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1950: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1951: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1952: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1953: 	if ($env{'form.handgrade'} eq 'yes') {
                   1954: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1955: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1956: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1957: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1958: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1959: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1960: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1961: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1962: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1963: 	    }
1.123     ng       1964: 	}
1.41      ng       1965: 	
                   1966: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1967: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1968: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1969: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1970: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1971: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1972: 		'" />'."\n".
                   1973: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1974: 	    $cts++;
                   1975: 	}
                   1976: 	$request->print($prnmsg);
1.32      ng       1977: 
1.257     albertel 1978: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1979: #
                   1980: # Print out the keyword options line
                   1981: #
1.41      ng       1982: 	    $request->print(<<KEYWORDS);
1.38      ng       1983: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1984: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1985: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1986:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1987: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1988: KEYWORDS
1.88      www      1989: #
                   1990: # Load the other essays for similarity check
                   1991: #
1.324     albertel 1992:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1993: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1994: 	    $apath=&escape($apath);
1.88      www      1995: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1996: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1997:         }
                   1998:     }
1.44      ng       1999: 
1.441     www      2000: # This is where output for one specific student would start
1.468     albertel 2001:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      2002:     $request->print("\n\n".
1.468     albertel 2003:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   2004: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   2005: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      2006: 
1.257     albertel 2007:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 2008: 	my $mode;
1.257     albertel 2009: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 2010: 	    $mode='both';
1.257     albertel 2011: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 2012: 	    $mode='text';
1.257     albertel 2013: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 2014: 	    $mode='answer';
                   2015: 	}
1.329     albertel 2016: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 2017: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 2018:     }
1.144     albertel 2019: 
1.257     albertel 2020:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2021:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       2022: 
1.44      ng       2023:     # Display student info
1.41      ng       2024:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 2025:     my $result='<div class="LC_grade_submissions">';
                   2026:     
                   2027:     $result.='<div class="LC_grade_submissions_header">';
                   2028:     $result.= &mt('Submissions');
1.45      ng       2029:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 2030: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 2031:     if ($env{'form.handgrade'} eq 'no') {
                   2032: 	$result.='<span class="LC_grade_check_note">'.
                   2033: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   2034: 
                   2035:     }
                   2036: 
                   2037: 
1.41      ng       2038: 
1.118     ng       2039:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2040:     my $fullname;
                   2041:     my $col_fullnames = [];
1.257     albertel 2042:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2043: 	(my $sub_result,$fullname,$col_fullnames)=
                   2044: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2045: 				 $counter);
                   2046: 	$result.=$sub_result;
1.41      ng       2047:     }
1.44      ng       2048:     $request->print($result."\n");
1.468     albertel 2049:     $request->print('</div>'."\n");
1.44      ng       2050:     # print student answer/submission
                   2051:     # Options are (1) Handgaded submission only
                   2052:     #             (2) Last submission, includes submission that is not handgraded 
                   2053:     #                  (for multi-response type part)
                   2054:     #             (3) Last submission plus the parts info
                   2055:     #             (4) The whole record for this student
1.257     albertel 2056:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2057: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2058: 	
                   2059: 	my $lastsubonly;
                   2060: 
1.151     albertel 2061: 	if ($$timestamp eq '') {
1.468     albertel 2062: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2063: 	} else {
1.468     albertel 2064: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2065: 
1.151     albertel 2066: 	    my %seenparts;
1.375     albertel 2067: 	    my @part_response_id = &flatten_responseType($responseType);
                   2068: 	    foreach my $part (@part_response_id) {
1.393     albertel 2069: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2070: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2071: 
1.375     albertel 2072: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2073: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2074: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2075: 		    if (exists($seenparts{$partid})) { next; }
                   2076: 		    $seenparts{$partid}=1;
1.207     albertel 2077: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2078: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2079: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2080: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2081: 			'\');" target="_self">'.
1.257     albertel 2082: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2083: 		    $request->print($submitby);
                   2084: 		    next;
                   2085: 		}
                   2086: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2087: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2088: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2089: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2090: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2091: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2092: 		    next;
                   2093: 		}
1.468     albertel 2094: 		foreach my $submission (@$string) {
                   2095: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2096: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2097: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2098: 		    # Similarity check
                   2099: 		    my $similar='';
1.257     albertel 2100: 		    if($env{'form.checkPlag'}){
1.151     albertel 2101: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2102: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2103: 			if ($osim) {
                   2104: 			    $osim=int($osim*100.0);
1.426     albertel 2105: 			    my %old_course_desc = 
                   2106: 				&Apache::lonnet::coursedescription($ocrsid,
                   2107: 								   {'one_time' => 1});
                   2108: 
                   2109: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2110: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2111: 				    $osim,
                   2112: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2113: 				    $oname,$odom,
1.426     albertel 2114: 				    $old_course_desc{'description'},
1.427     albertel 2115: 				    $old_course_desc{'num'},
1.426     albertel 2116: 				    $old_course_desc{'domain'}).
1.398     albertel 2117: 				'</span></h3><blockquote><i>'.
1.151     albertel 2118: 				&keywords_highlight($oessay).
                   2119: 				'</i></blockquote><hr />';
                   2120: 			}
1.150     albertel 2121: 		    }
1.151     albertel 2122: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2123: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2124: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2125: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2126: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2127: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2128: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2129: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2130: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2131: 			if (@$files) {
1.468     albertel 2132: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2133: 			    my $file_counter = 0;
1.313     banghart 2134: 			    foreach my $file (@$files) {
1.468     albertel 2135: 			        $file_counter++;
1.232     albertel 2136: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2137: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2138: 			    }
1.236     albertel 2139: 			    $lastsubonly.='<br />';
1.41      ng       2140: 			}
1.468     albertel 2141: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2142: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2143: 					 $respid,\%record,$order);
                   2144: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2145: 			$lastsubonly.='</div>';
1.41      ng       2146: 		    }
                   2147: 		}
                   2148: 	    }
1.468     albertel 2149: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2150: 	}
                   2151: 	$request->print($lastsubonly);
1.468     albertel 2152:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2153: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2154: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2155:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2156: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2157: 								 $env{'request.course.id'},
1.44      ng       2158: 								 $last,'.submission',
                   2159: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2160:     }
1.120     ng       2161: 
1.121     ng       2162:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2163: 	.$udom.'" />'."\n");
1.44      ng       2164:     # return if view submission with no grading option
1.257     albertel 2165:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2166: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2167: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2168: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2169: 	$toGrade.='</div>'."\n";
1.257     albertel 2170: 	if (($env{'form.command'} eq 'submission') || 
                   2171: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2172: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2173: 	}
1.180     albertel 2174: 	$request->print($toGrade);
1.41      ng       2175: 	return;
1.180     albertel 2176:     } else {
1.468     albertel 2177: 	$request->print('</div>'."\n");
1.41      ng       2178:     }
1.33      ng       2179: 
1.121     ng       2180:     # essay grading message center
1.257     albertel 2181:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2182: 	my $result='<div class="LC_grade_message_center">';
                   2183:     
                   2184: 	$result.='<div class="LC_grade_message_center_header">'.
                   2185: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2186: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2187: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2188: 	if (scalar(@$col_fullnames) > 0) {
                   2189: 	    my $lastone = pop(@$col_fullnames);
                   2190: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2191: 	}
                   2192: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2193: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2194: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2195: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2196: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2197: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2198: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2199: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2200: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2201: 	    '<br />&nbsp;('.
1.468     albertel 2202: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2203: 	$result.='</div></div>';
1.121     ng       2204: 	$request->print($result);
1.118     ng       2205:     }
1.41      ng       2206: 
                   2207:     my %seen = ();
                   2208:     my @partlist;
1.129     ng       2209:     my @gradePartRespid;
1.375     albertel 2210:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2211:     $request->print('<div class="LC_grade_assign">'.
                   2212: 		    
                   2213: 		    '<div class="LC_grade_assign_header">'.
                   2214: 		    &mt('Assign Grades').'</div>'.
                   2215: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2216:     foreach my $part_response_id (@part_response_id) {
                   2217:     	my ($partid,$respid) = @{ $part_response_id };
                   2218: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2219: 	next if ($seen{$partid} > 0);
1.41      ng       2220: 	$seen{$partid}++;
1.393     albertel 2221: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2222: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2223: 	push @partlist,$partid;
1.129     ng       2224: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2225: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2226:     }
1.468     albertel 2227:     $request->print('</div></div>');
                   2228: 
                   2229:     $request->print('<div class="LC_grade_info_links">');
                   2230:     if ($perm{'vgr'}) {
                   2231: 	$request->print(
                   2232: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2233: 						   $uname,$udom,'check'));
                   2234:     }
                   2235:     if ($perm{'opa'}) {
                   2236: 	$request->print(
                   2237: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2238: 					 $uname,$udom,$symb,'check'));
                   2239:     }
                   2240:     $request->print('</div>');
                   2241: 
1.45      ng       2242:     $result='<input type="hidden" name="partlist'.$counter.
                   2243: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2244:     $result.='<input type="hidden" name="gradePartRespid'.
                   2245: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2246:     my $ctr = 0;
                   2247:     while ($ctr < scalar(@partlist)) {
                   2248: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2249: 	    $partlist[$ctr].'" />'."\n";
                   2250: 	$ctr++;
                   2251:     }
1.468     albertel 2252:     $request->print($result.''."\n");
1.41      ng       2253: 
1.441     www      2254: # Done with printing info for one student
                   2255: 
1.468     albertel 2256:     $request->print('</div>');#LC_grade_show_user_body
                   2257:     $request->print('</div>');#LC_grade_show_user
1.441     www      2258: 
                   2259: 
1.41      ng       2260:     # print end of form
                   2261:     if ($counter == $total) {
1.297     www      2262: 	my $endform='<table border="0"><tr><td>'."\n";
1.485     albertel 2263: 	$endform.='<input type="button" value="'.&mt('Save &amp; Next').'" '.
1.119     ng       2264: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2265: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2266: 	my $ntstu ='<select name="NTSTU">'.
                   2267: 	    '<option>1</option><option>2</option>'.
                   2268: 	    '<option>3</option><option>5</option>'.
                   2269: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2270: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2271: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.485     albertel 2272: 	$endform.=&mt('[_1]student(s)',$ntstu);
                   2273: 	$endform.='&nbsp;&nbsp;<input type="button" value="'.&mt('Previous').'" '.
1.417     albertel 2274: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.485     albertel 2275: 	    '<input type="button" value="'.&mt('Next').'" '.
1.417     albertel 2276: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.485     albertel 2277: 	$endform.=&mt('(Next and Previous (student) do not save the scores.)')."\n" ;
1.349     albertel 2278:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2279:             "' name='increment' />";
1.485     albertel 2280: 	$endform.='</td></tr></table></form>';
1.324     albertel 2281: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2282: 	$request->print($endform);
                   2283:     }
                   2284:     return '';
1.38      ng       2285: }
                   2286: 
1.464     albertel 2287: sub check_collaborators {
                   2288:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2289:     my ($result,@col_fullnames);
                   2290:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2291:     foreach my $part (keys(%$handgrade)) {
                   2292: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2293: 					'.maxcollaborators',
                   2294: 					$symb,$udom,$uname);
                   2295: 	next if ($ncol <= 0);
                   2296: 	$part =~ s/\_/\./g;
                   2297: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2298: 	my (@good_collaborators, @bad_collaborators);
                   2299: 	foreach my $possible_collaborator
                   2300: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2301: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2302: 	    next if ($possible_collaborator eq '');
                   2303: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2304: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2305: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2306: 	    # Doing this grep allows 'fuzzy' specification
                   2307: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2308: 			       keys(%$classlist));
                   2309: 	    if (! scalar(@matches)) {
                   2310: 		push(@bad_collaborators, $possible_collaborator);
                   2311: 	    } else {
                   2312: 		push(@good_collaborators, @matches);
                   2313: 	    }
                   2314: 	}
                   2315: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2316: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2317: 	    foreach my $name (@good_collaborators) {
                   2318: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2319: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2320: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2321: 	    }
                   2322: 	    $result.='<br />'."\n";
1.466     albertel 2323: 	    my ($part)=split(/\./,$part);
1.464     albertel 2324: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2325: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2326: 		"\n";
                   2327: 	}
                   2328: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2329: 	    $result.='<div class="LC_warning">';
1.464     albertel 2330: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2331: 	    $result .= '</div>';
                   2332: 	}         
                   2333: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2334: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2335: 	    $result .= &mt('This student has submitted too many '.
                   2336: 		'collaborators.  Maximum is [_1].',$ncol);
                   2337: 	    $result .= '</div>';
                   2338: 	}
                   2339:     }
                   2340:     return ($result,$fullname,\@col_fullnames);
                   2341: }
                   2342: 
1.44      ng       2343: #--- Retrieve the last submission for all the parts
1.38      ng       2344: sub get_last_submission {
1.119     ng       2345:     my ($returnhash)=@_;
1.46      ng       2346:     my (@string,$timestamp);
1.119     ng       2347:     if ($$returnhash{'version'}) {
1.46      ng       2348: 	my %lasthash=();
                   2349: 	my ($version);
1.119     ng       2350: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2351: 	    foreach my $key (sort(split(/\:/,
                   2352: 					$$returnhash{$version.':keys'}))) {
                   2353: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2354: 		$timestamp = 
                   2355: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2356: 	    }
                   2357: 	}
1.397     albertel 2358: 	foreach my $key (keys(%lasthash)) {
                   2359: 	    next if ($key !~ /\.submission$/);
                   2360: 
                   2361: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2362: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2363: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2364: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2365: 	}
                   2366:     }
1.397     albertel 2367:     if (!@string) {
                   2368: 	$string[0] =
1.398     albertel 2369: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2370:     }
                   2371:     return (\@string,\$timestamp);
1.38      ng       2372: }
1.35      ng       2373: 
1.44      ng       2374: #--- High light keywords, with style choosen by user.
1.38      ng       2375: sub keywords_highlight {
1.44      ng       2376:     my $string    = shift;
1.257     albertel 2377:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2378:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2379:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2380:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2381:     foreach my $keyword (@keylist) {
                   2382: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2383:     }
                   2384:     return $string;
1.38      ng       2385: }
1.36      ng       2386: 
1.44      ng       2387: #--- Called from submission routine
1.38      ng       2388: sub processHandGrade {
1.41      ng       2389:     my ($request) = shift;
1.324     albertel 2390:     my $symb   = &get_symb($request);
                   2391:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2392:     my $button = $env{'form.gradeOpt'};
                   2393:     my $ngrade = $env{'form.NCT'};
                   2394:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2395:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2396:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2397: 
1.44      ng       2398:     if ($button eq 'Save & Next') {
                   2399: 	my $ctr = 0;
                   2400: 	while ($ctr < $ngrade) {
1.257     albertel 2401: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2402: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2403: 	    if ($errorflag eq 'no_score') {
                   2404: 		$ctr++;
                   2405: 		next;
                   2406: 	    }
1.104     albertel 2407: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2408: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2409: 		$ctr++;
                   2410: 		next;
                   2411: 	    }
1.257     albertel 2412: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2413: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2414: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2415:             my ($feedurl,$showsymb) =
                   2416: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2417: 	    my $messagetail;
1.62      albertel 2418: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2419: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2420: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2421: 		$subject.=' ['.$restitle.']';
1.44      ng       2422: 		my (@msgnum) = split(/,/,$includemsg);
                   2423: 		foreach (@msgnum) {
1.257     albertel 2424: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2425: 		}
1.80      ng       2426: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2427: 		if ($env{'form.withgrades'.$ctr}) {
                   2428: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2429: 		    $messagetail = " for <a href=\"".
1.418     albertel 2430: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2431: 		}
                   2432: 		$msgstatus = 
                   2433:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2434: 						     $message.$messagetail,
1.418     albertel 2435:                                                      undef,$feedurl,undef,
1.386     raeburn  2436:                                                      undef,undef,$showsymb,
                   2437:                                                      $restitle);
                   2438: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2439: 				$msgstatus);
1.44      ng       2440: 	    }
1.257     albertel 2441: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2442: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2443: 		foreach my $collabstr (@collabstrs) {
                   2444: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2445: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2446: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2447: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2448: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2449: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2450: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2451: 			    next;
1.418     albertel 2452: 			} elsif ($message ne '') {
                   2453: 			    my ($baseurl,$showsymb) = 
                   2454: 				&get_feedurl_and_symb($symb,$collaborator,
                   2455: 						      $udom);
                   2456: 			    if ($env{'form.withgrades'.$ctr}) {
                   2457: 				$messagetail = " for <a href=\"".
1.386     raeburn  2458:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2459: 			    }
1.418     albertel 2460: 			    $msgstatus = 
                   2461: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2462: 			}
1.44      ng       2463: 		    }
                   2464: 		}
                   2465: 	    }
                   2466: 	    $ctr++;
                   2467: 	}
                   2468:     }
                   2469: 
1.257     albertel 2470:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2471: 	# Keywords sorted in alphabatical order
1.257     albertel 2472: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2473: 	my %keyhash = ();
1.257     albertel 2474: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2475: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2476: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2477: 	$env{'form.keywords'} = join(' ',@keywords);
                   2478: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2479: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2480: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2481: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2482: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2483: 
                   2484: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2485: 	# New messages are saved in env for the next student.
1.119     ng       2486: 	# All messages are saved in nohist_handgrade.db
                   2487: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2488: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2489: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2490: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2491: 		$idx++;
                   2492: 	    }
                   2493: 	    $ctr++;
1.41      ng       2494: 	}
1.119     ng       2495: 	$ctr = 0;
                   2496: 	while ($ctr < $ngrade) {
1.257     albertel 2497: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2498: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2499: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2500: 		$idx++;
                   2501: 	    }
                   2502: 	    $ctr++;
1.41      ng       2503: 	}
1.257     albertel 2504: 	$env{'form.savemsgN'} = --$idx;
                   2505: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2506: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2507: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2508:     }
1.44      ng       2509:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2510:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2511:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2512: 	my ($ctr,$total) = (0,0);
                   2513: 	while ($ctr < $ngrade) {
1.257     albertel 2514: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2515: 	    $ctr++;
                   2516: 	}
1.257     albertel 2517: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2518: 	$ctr = 0;
                   2519: 	while ($ctr < $total) {
1.257     albertel 2520: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2521: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2522: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2523: 	    &submission($request,$ctr,$total-1);
1.41      ng       2524: 	    $ctr++;
                   2525: 	}
                   2526: 	return '';
                   2527:     }
1.36      ng       2528: 
1.121     ng       2529: # Go directly to grade student - from submission or link from chart page
1.120     ng       2530:     if ($button eq 'Grade Student') {
1.324     albertel 2531: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2532: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2533: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2534: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2535: 	&submission($request,0,0);
                   2536: 	return '';
                   2537:     }
                   2538: 
1.44      ng       2539:     # Get the next/previous one or group of students
1.257     albertel 2540:     my $firststu = $env{'form.unamedom0'};
                   2541:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2542:     my $ctr = 2;
1.41      ng       2543:     while ($laststu eq '') {
1.257     albertel 2544: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2545: 	$ctr++;
                   2546: 	$laststu = $firststu if ($ctr > $ngrade);
                   2547:     }
1.44      ng       2548: 
1.41      ng       2549:     my (@parsedlist,@nextlist);
                   2550:     my ($nextflg) = 0;
1.294     albertel 2551:     foreach (sort 
                   2552: 	     {
                   2553: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2554: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2555: 		 }
                   2556: 		 return $a cmp $b;
                   2557: 	     } (keys(%$fullname))) {
1.41      ng       2558: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2559: 	    push @parsedlist,$_;
                   2560: 	}
                   2561: 	$nextflg = 1 if ($_ eq $laststu);
                   2562: 	if ($button eq 'Previous') {
                   2563: 	    last if ($_ eq $firststu);
                   2564: 	    push @parsedlist,$_;
                   2565: 	}
                   2566:     }
                   2567:     $ctr = 0;
                   2568:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2569:     my ($partlist) = &response_type($symb);
1.41      ng       2570:     foreach my $student (@parsedlist) {
1.257     albertel 2571: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2572: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2573: 	
                   2574: 	if ($submitonly eq 'queued') {
                   2575: 	    my %queue_status = 
                   2576: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2577: 							$udom,$uname);
                   2578: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2579: 	}
                   2580: 
1.156     albertel 2581: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2582: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2583: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2584: 	    my $submitted = 0;
1.248     albertel 2585: 	    my $ungraded = 0;
                   2586: 	    my $incorrect = 0;
1.145     albertel 2587: 	    foreach (keys(%status)) {
                   2588: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2589: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2590: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2591: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2592: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2593: 		    $submitted = 0;
                   2594: 		}
1.41      ng       2595: 	    }
1.156     albertel 2596: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2597: 				     $submitonly eq 'incorrect' ||
                   2598: 				     $submitonly eq 'graded'));
1.248     albertel 2599: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2600: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2601: 	}
                   2602: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2603: 	last if ($ctr == $ntstu);
1.41      ng       2604: 	$ctr++;
                   2605:     }
1.36      ng       2606: 
1.41      ng       2607:     $ctr = 0;
                   2608:     my $total = scalar(@nextlist)-1;
1.39      ng       2609: 
1.41      ng       2610:     foreach (sort @nextlist) {
                   2611: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2612: 	$env{'form.student'}  = $uname;
                   2613: 	$env{'form.userdom'}  = $udom;
                   2614: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2615: 	&submission($request,$ctr,$total);
                   2616: 	$ctr++;
                   2617:     }
                   2618:     if ($total < 0) {
1.485     albertel 2619: 	my $the_end = '<h3><span class="LC_info">'.&mt('LON-CAPA User Message').'</span></h3><br />'."\n";
                   2620: 	$the_end.=&mt('<b>Message: </b> No more students for this section or class.').'<br /><br />'."\n";
                   2621: 	$the_end.=&mt('Click on the button below to return to the grading menu.').'<br /><br />'."\n";
1.324     albertel 2622: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2623: 	$request->print($the_end);
                   2624:     }
                   2625:     return '';
1.38      ng       2626: }
1.36      ng       2627: 
1.44      ng       2628: #---- Save the score and award for each student, if changed
1.38      ng       2629: sub saveHandGrade {
1.324     albertel 2630:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2631:     my @version_parts;
1.104     albertel 2632:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2633: 					   $env{'request.course.id'});
1.104     albertel 2634:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2635:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2636:     my @parts_graded;
1.77      ng       2637:     my %newrecord  = ();
                   2638:     my ($pts,$wgt) = ('','');
1.269     raeburn  2639:     my %aggregate = ();
                   2640:     my $aggregateflag = 0;
1.301     albertel 2641:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2642:     foreach my $new_part (@parts) {
1.337     banghart 2643: 	#collaborator ($submi may vary for different parts
1.259     banghart 2644: 	if ($submitter && $new_part ne $part) { next; }
                   2645: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2646: 	if ($dropMenu eq 'excused') {
1.259     banghart 2647: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2648: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2649: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2650: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2651: 		}
1.364     banghart 2652: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2653: 	    }
1.125     ng       2654: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2655: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2656: 	    foreach my $key (keys (%record)) {
1.259     banghart 2657: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2658: 	    }
1.259     banghart 2659: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2660: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2661:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2662: 
                   2663:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2664: 					       [$new_part]);
                   2665:             my $aggtries =$totaltries;
1.269     raeburn  2666:             if ($last_resets{$new_part}) {
1.270     albertel 2667:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2668: 					   $new_part);
1.269     raeburn  2669:             }
1.270     albertel 2670: 
                   2671:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2672:             if ($aggtries > 0) {
1.327     albertel 2673:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2674:                 $aggregateflag = 1;
                   2675:             }
1.125     ng       2676: 	} elsif ($dropMenu eq '') {
1.259     banghart 2677: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2678: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2679: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2680: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2681: 		next;
                   2682: 	    }
1.259     banghart 2683: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2684: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2685: 	    my $partial= $pts/$wgt;
1.259     banghart 2686: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2687: 		#do not update score for part if not changed.
1.346     banghart 2688:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2689: 		next;
1.251     banghart 2690: 	    } else {
1.259     banghart 2691: 	        push @parts_graded, $new_part;
1.153     albertel 2692: 	    }
1.259     banghart 2693: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2694: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2695: 	    }
1.259     banghart 2696: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2697: 	    if ($partial == 0) {
1.153     albertel 2698: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2699: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2700: 		}
1.41      ng       2701: 	    } else {
1.153     albertel 2702: 		if ($record{$reckey} ne 'correct_by_override') {
                   2703: 		    $newrecord{$reckey} = 'correct_by_override';
                   2704: 		}
                   2705: 	    }	    
                   2706: 	    if ($submitter && 
1.259     banghart 2707: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2708: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2709: 	    }
1.259     banghart 2710: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2711: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2712: 	}
1.259     banghart 2713: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2714: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2715: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2716: 	        $dropMenu eq 'reset status')
                   2717: 	   {
1.342     banghart 2718: 	    push (@version_parts,$new_part);
1.259     banghart 2719: 	}
1.41      ng       2720:     }
1.301     albertel 2721:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2722:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2723: 
1.344     albertel 2724:     if (%newrecord) {
                   2725:         if (@version_parts) {
1.364     banghart 2726:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2727:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2728: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2729: 	    foreach my $new_part (@version_parts) {
                   2730: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2731: 				$new_part,\%newrecord);
                   2732: 	    }
1.259     banghart 2733:         }
1.44      ng       2734: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2735: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2736: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2737: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2738:     }
1.269     raeburn  2739:     if ($aggregateflag) {
                   2740:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2741: 			      $cdom,$cnum);
1.269     raeburn  2742:     }
1.301     albertel 2743:     return ('',$pts,$wgt);
1.36      ng       2744: }
1.322     albertel 2745: 
1.380     albertel 2746: sub check_and_remove_from_queue {
                   2747:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2748:     my @ungraded_parts;
                   2749:     foreach my $part (@{$parts}) {
                   2750: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2751: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2752: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2753: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2754: 		) {
                   2755: 	    push(@ungraded_parts, $part);
                   2756: 	}
                   2757:     }
                   2758:     if ( !@ungraded_parts ) {
                   2759: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2760: 					       $cnum,$domain,$stuname);
                   2761:     }
                   2762: }
                   2763: 
1.337     banghart 2764: sub handback_files {
                   2765:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2766:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2767:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2768: 
                   2769:     my @part_response_id = &flatten_responseType($responseType);
                   2770:     foreach my $part_response_id (@part_response_id) {
                   2771:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2772: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2773:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2774:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2775:                 my $file_counter = 1;
1.367     albertel 2776: 		my $file_msg;
1.337     banghart 2777:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2778:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2779:                     my ($directory,$answer_file) = 
                   2780:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2781:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2782: 		        &file_name_version_ext($answer_file);
1.355     banghart 2783: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2784: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2785: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2786:                     # fix file name
                   2787:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2788:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2789:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2790:             	                                $save_file_name);
1.337     banghart 2791:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2792:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2793:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2794:                     } else {
1.360     banghart 2795:                         # mark the file as read only
                   2796:                         my @files = ($save_file_name);
1.372     albertel 2797:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2798:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2799: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2800: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2801: 			}
                   2802:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2803: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2804: 
1.337     banghart 2805:                     }
                   2806:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2807:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2808:                     $file_counter++;
                   2809:                 }
1.367     albertel 2810: 		my $subject = "File Handed Back by Instructor ";
                   2811: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2812: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2813: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2814: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2815: 		my ($feedurl,$showsymb) = 
                   2816: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2817:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2818: 		my $msgstatus = 
                   2819:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2820: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2821:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2822:             }
                   2823:         }
1.338     banghart 2824:     return;
1.337     banghart 2825: }
                   2826: 
1.418     albertel 2827: sub get_feedurl_and_symb {
                   2828:     my ($symb,$uname,$udom) = @_;
                   2829:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2830:     $url = &Apache::lonnet::clutter($url);
                   2831:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2832: 					$symb,$udom,$uname);
                   2833:     if ($encrypturl =~ /^yes$/i) {
                   2834: 	&Apache::lonenc::encrypted(\$url,1);
                   2835: 	&Apache::lonenc::encrypted(\$symb,1);
                   2836:     }
                   2837:     return ($url,$symb);
                   2838: }
                   2839: 
1.313     banghart 2840: sub get_submitted_files {
                   2841:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2842:     my @files;
                   2843:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2844:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2845:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2846:     	    push(@files,$file_url.$file);
                   2847:         }
                   2848:     }
                   2849:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2850:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2851:     }
                   2852:     return (\@files);
                   2853: }
1.322     albertel 2854: 
1.269     raeburn  2855: # ----------- Provides number of tries since last reset.
                   2856: sub get_num_tries {
                   2857:     my ($record,$last_reset,$part) = @_;
                   2858:     my $timestamp = '';
                   2859:     my $num_tries = 0;
                   2860:     if ($$record{'version'}) {
                   2861:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2862:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2863:                 $timestamp = $$record{$version.':timestamp'};
                   2864:                 if ($timestamp > $last_reset) {
                   2865:                     $num_tries ++;
                   2866:                 } else {
                   2867:                     last;
                   2868:                 }
                   2869:             }
                   2870:         }
                   2871:     }
                   2872:     return $num_tries;
                   2873: }
                   2874: 
                   2875: # ----------- Determine decrements required in aggregate totals 
                   2876: sub decrement_aggs {
                   2877:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2878:     my %decrement = (
                   2879:                         attempts => 0,
                   2880:                         users => 0,
                   2881:                         correct => 0
                   2882:                     );
                   2883:     $decrement{'attempts'} = $aggtries;
                   2884:     if ($solvedstatus =~ /^correct/) {
                   2885:         $decrement{'correct'} = 1;
                   2886:     }
                   2887:     if ($aggtries == $totaltries) {
                   2888:         $decrement{'users'} = 1;
                   2889:     }
                   2890:     foreach my $type (keys (%decrement)) {
                   2891:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2892:     }
                   2893:     return;
                   2894: }
                   2895: 
                   2896: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2897: sub get_last_resets {
1.270     albertel 2898:     my ($symb,$courseid,$partids) =@_;
                   2899:     my %last_resets;
1.269     raeburn  2900:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2901:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2902:     my @keys;
                   2903:     foreach my $part (@{$partids}) {
                   2904: 	push(@keys,"$symb\0$part\0resettime");
                   2905:     }
                   2906:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2907: 				     $cdom,$cname);
                   2908:     foreach my $part (@{$partids}) {
                   2909: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2910:     }
1.270     albertel 2911:     return %last_resets;
1.269     raeburn  2912: }
                   2913: 
1.251     banghart 2914: # ----------- Handles creating versions for portfolio files as answers
                   2915: sub version_portfiles {
1.343     banghart 2916:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2917:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2918:     my @returned_keys;
1.255     banghart 2919:     my $parts = join('|', @$parts_graded);
1.359     www      2920:     my $portfolio_root = &propath($domain,$stu_name).
                   2921: 	'/userfiles/portfolio';
1.277     albertel 2922:     foreach my $key (keys(%$record)) {
1.259     banghart 2923:         my $new_portfiles;
1.263     banghart 2924:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2925:             my @versioned_portfiles;
1.367     albertel 2926:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2927:             foreach my $file (@portfiles) {
1.306     banghart 2928:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2929:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2930: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2931: 		    &file_name_version_ext($answer_file);
1.306     banghart 2932:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2933:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2934:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2935:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2936:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2937:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2938:                         [$directory.$new_answer],
1.306     banghart 2939:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2940:                 }
1.252     banghart 2941:             }
1.343     banghart 2942:             $$record{$key} = join(',',@versioned_portfiles);
                   2943:             push(@returned_keys,$key);
1.251     banghart 2944:         }
                   2945:     } 
1.343     banghart 2946:     return (@returned_keys);   
1.305     banghart 2947: }
                   2948: 
1.307     banghart 2949: sub get_next_version {
1.341     banghart 2950:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2951:     my $version;
                   2952:     foreach my $row (@$dir_list) {
                   2953:         my ($file) = split(/\&/,$row,2);
                   2954:         my ($file_name,$file_version,$file_ext) =
                   2955: 	    &file_name_version_ext($file);
                   2956:         if (($file_name eq $answer_name) && 
                   2957: 	    ($file_ext eq $answer_ext)) {
                   2958:                 # gets here if filename and extension match, regardless of version
                   2959:                 if ($file_version ne '') {
                   2960:                 # a versioned file is found  so save it for later
                   2961:                 if ($file_version > $version) {
                   2962: 		    $version = $file_version;
                   2963: 	        }
                   2964:             }
                   2965:         }
                   2966:     } 
                   2967:     $version ++;
                   2968:     return($version);
                   2969: }
                   2970: 
1.305     banghart 2971: sub version_selected_portfile {
1.306     banghart 2972:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2973:     my ($answer_name,$answer_ver,$answer_ext) =
                   2974:         &file_name_version_ext($file_name);
                   2975:     my $new_answer;
                   2976:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2977:     if($env{'form.copy'} eq '-1') {
                   2978:         $new_answer = 'problem getting file';
                   2979:     } else {
                   2980:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2981:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2982:                             $stu_name,$domain,'copy',
                   2983: 		        '/portfolio'.$directory.$new_answer);
                   2984:     }    
                   2985:     return ($new_answer);
1.251     banghart 2986: }
                   2987: 
1.304     albertel 2988: sub file_name_version_ext {
                   2989:     my ($file)=@_;
                   2990:     my @file_parts = split(/\./, $file);
                   2991:     my ($name,$version,$ext);
                   2992:     if (@file_parts > 1) {
                   2993: 	$ext=pop(@file_parts);
                   2994: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2995: 	    $version=pop(@file_parts);
                   2996: 	}
                   2997: 	$name=join('.',@file_parts);
                   2998:     } else {
                   2999: 	$name=join('.',@file_parts);
                   3000:     }
                   3001:     return($name,$version,$ext);
                   3002: }
                   3003: 
1.44      ng       3004: #--------------------------------------------------------------------------------------
                   3005: #
                   3006: #-------------------------- Next few routines handles grading by section or whole class
                   3007: #
                   3008: #--- Javascript to handle grading by section or whole class
1.42      ng       3009: sub viewgrades_js {
                   3010:     my ($request) = shift;
                   3011: 
1.41      ng       3012:     $request->print(<<VIEWJAVASCRIPT);
                   3013: <script type="text/javascript" language="javascript">
1.45      ng       3014:    function writePoint(partid,weight,point) {
1.125     ng       3015: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   3016: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       3017: 	if (point == "textval") {
1.125     ng       3018: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  3019: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   3020: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       3021: 		var resetbox = false;
                   3022: 		for (var i=0; i<radioButton.length; i++) {
                   3023: 		    if (radioButton[i].checked) {
                   3024: 			textbox.value = i;
                   3025: 			resetbox = true;
                   3026: 		    }
                   3027: 		}
                   3028: 		if (!resetbox) {
                   3029: 		    textbox.value = "";
                   3030: 		}
                   3031: 		return;
                   3032: 	    }
1.109     matthew  3033: 	    if (parseFloat(point) > parseFloat(weight)) {
                   3034: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3035: 				   ") greater than the weight for the part. Accept?");
                   3036: 		if (resp == false) {
                   3037: 		    textbox.value = "";
                   3038: 		    return;
                   3039: 		}
                   3040: 	    }
1.42      ng       3041: 	    for (var i=0; i<radioButton.length; i++) {
                   3042: 		radioButton[i].checked=false;
1.109     matthew  3043: 		if (parseFloat(point) == i) {
1.42      ng       3044: 		    radioButton[i].checked=true;
                   3045: 		}
                   3046: 	    }
1.41      ng       3047: 
1.42      ng       3048: 	} else {
1.125     ng       3049: 	    textbox.value = parseFloat(point);
1.42      ng       3050: 	}
1.41      ng       3051: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3052: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3053: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3054: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3055: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3056: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3057: 	    if (saveval != "correct") {
                   3058: 		scorename.value = point;
1.43      ng       3059: 		if (selname[0].selected != true) {
                   3060: 		    selname[0].selected = true;
                   3061: 		}
1.42      ng       3062: 	    }
                   3063: 	}
1.125     ng       3064: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3065:     }
                   3066: 
                   3067:     function writeRadText(partid,weight) {
1.125     ng       3068: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3069: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3070:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3071: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3072: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3073: 	    for (var i=0; i<radioButton.length; i++) {
                   3074: 		radioButton[i].checked=false;
                   3075: 
                   3076: 	    }
                   3077: 	    textbox.value = "";
                   3078: 
                   3079: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3080: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3081: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3082: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3083: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3084: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3085: 		if ((saveval != "correct") || override) {
1.42      ng       3086: 		    scorename.value = "";
1.125     ng       3087: 		    if (selval[1].selected) {
                   3088: 			selname[1].selected = true;
                   3089: 		    } else {
                   3090: 			selname[2].selected = true;
                   3091: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3092: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3093: 		    }
1.42      ng       3094: 		}
                   3095: 	    }
1.43      ng       3096: 	} else {
                   3097: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3098: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3099: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3100: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3101: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3102: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3103: 		if ((saveval != "correct") || override) {
1.125     ng       3104: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3105: 		    selname[0].selected = true;
                   3106: 		}
                   3107: 	    }
                   3108: 	}	    
1.42      ng       3109:     }
                   3110: 
                   3111:     function changeSelect(partid,user) {
1.125     ng       3112: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3113: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3114: 	var point  = textbox.value;
1.125     ng       3115: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3116: 
1.109     matthew  3117: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3118: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3119: 	    textbox.value = "";
                   3120: 	    return;
                   3121: 	}
1.109     matthew  3122: 	if (parseFloat(point) > parseFloat(weight)) {
                   3123: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3124: 			       ") greater than the weight of the part. Accept?");
                   3125: 	    if (resp == false) {
                   3126: 		textbox.value = "";
                   3127: 		return;
                   3128: 	    }
                   3129: 	}
1.42      ng       3130: 	selval[0].selected = true;
                   3131:     }
                   3132: 
                   3133:     function changeOneScore(partid,user) {
1.125     ng       3134: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3135: 	if (selval[1].selected || selval[2].selected) {
                   3136: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3137: 	    if (selval[2].selected) {
                   3138: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3139: 	    }
1.269     raeburn  3140:         }
1.42      ng       3141:     }
                   3142: 
                   3143:     function resetEntry(numpart) {
                   3144: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3145: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3146: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3147: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3148: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3149: 	    for (var i=0; i<radioButton.length; i++) {
                   3150: 		radioButton[i].checked=false;
                   3151: 
                   3152: 	    }
                   3153: 	    textbox.value = "";
                   3154: 	    selval[0].selected = true;
                   3155: 
                   3156: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3157: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3158: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3159: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3160: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3161: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3162: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3163: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3164: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3165: 		if (saveselval == "excused") {
1.43      ng       3166: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3167: 		} else {
1.43      ng       3168: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3169: 		}
                   3170: 	    }
1.41      ng       3171: 	}
1.42      ng       3172:     }
                   3173: 
1.41      ng       3174: </script>
                   3175: VIEWJAVASCRIPT
1.42      ng       3176: }
                   3177: 
1.44      ng       3178: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3179: sub viewgrades {
                   3180:     my ($request) = shift;
                   3181:     &viewgrades_js($request);
1.41      ng       3182: 
1.324     albertel 3183:     my ($symb) = &get_symb($request);
1.168     albertel 3184:     #need to make sure we have the correct data for later EXT calls, 
                   3185:     #thus invalidate the cache
                   3186:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3187:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3188:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3189:     &Apache::lonnet::clear_EXT_cache_status();
                   3190: 
1.398     albertel 3191:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
1.485     albertel 3192:     $result.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.41      ng       3193: 
                   3194:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3195:     $result.=&jscriptNform($symb);
1.41      ng       3196: 
1.44      ng       3197:     #beginning of class grading form
1.442     banghart 3198:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3199:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3200: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3201: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3202: 	&build_section_inputs().
1.257     albertel 3203: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3204: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3205: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3206: 
1.126     ng       3207:     my $sectionClass;
1.430     banghart 3208:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3209:     if ($env{'form.section'} eq 'all') {
1.485     albertel 3210: 	$sectionClass='Class';
1.257     albertel 3211:     } elsif ($env{'form.section'} eq 'none') {
1.485     albertel 3212: 	$sectionClass='Students in no Section';
1.52      albertel 3213:     } else {
1.485     albertel 3214: 	$sectionClass='Students in Section(s) [_1]';
1.52      albertel 3215:     }
1.485     albertel 3216:     $result.=
                   3217: 	'<h3>'.
                   3218: 	&mt("Assign Common Grade To $sectionClass",$section_display).'</h3>';
1.474     albertel 3219:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3220:     #radio buttons/text box for assigning points for a section or class.
                   3221:     #handles different parts of a problem
1.375     albertel 3222:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3223:     my %weight = ();
                   3224:     my $ctsparts = 0;
1.45      ng       3225:     my %seen = ();
1.375     albertel 3226:     my @part_response_id = &flatten_responseType($responseType);
                   3227:     foreach my $part_response_id (@part_response_id) {
                   3228:     	my ($partid,$respid) = @{ $part_response_id };
                   3229: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3230: 	next if $seen{$partid};
                   3231: 	$seen{$partid}++;
1.375     albertel 3232: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3233: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3234: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3235: 
1.324     albertel 3236: 	my $display_part=&get_display_part($partid,$symb);
1.485     albertel 3237: 	my $radio.='<table border="0"><tr>';  
1.41      ng       3238: 	my $ctr = 0;
1.42      ng       3239: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.485     albertel 3240: 	    $radio.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3241: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3242: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3243: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3244: 	    $ctr++;
                   3245: 	}
1.485     albertel 3246: 	$radio.='</tr></table>';
                   3247: 	my $line = '<input type="text" name="TEXTVAL_'.
1.54      albertel 3248: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3249: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3250: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.485     albertel 3251: 	$line.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3252: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3253: 		$weight{$partid}.')"> '.
1.401     albertel 3254: 	    '<option selected="selected"> </option>'.
1.485     albertel 3255: 	    '<option value="excused">'.&mt('excused').'</option>'.
                   3256: 	    '<option value="reset status">'.&mt('reset status').'</option>'.
                   3257: 	    '</select></td>'.
                   3258:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" />'.&mt('Override "Correct"').'</label>';
                   3259: 	$line.='<input type="hidden" name="partid_'.
                   3260: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3261: 	$line.='<input type="hidden" name="weight_'.
                   3262: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
                   3263: 
                   3264: 	$result.=
                   3265: 	    &Apache::loncommon::start_data_table_row()."\n".
                   3266: 	    &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).
                   3267: 	    &Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3268: 	$ctsparts++;
1.41      ng       3269:     }
1.474     albertel 3270:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3271: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.485     albertel 3272:     $result.='<input type="button" value="'.&mt('Revert to Default').'" '.
1.474     albertel 3273: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3274: 
1.44      ng       3275:     #table listing all the students in a section/class
                   3276:     #header of table
1.485     albertel 3277:     $result.= '<h3>'.&mt('Assign Grade to Specific Students in '.$sectionClass,
                   3278: 			 $section_display).'</h3>';
1.474     albertel 3279:     $result.= &Apache::loncommon::start_data_table().
                   3280: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 3281: 	'<th>'.&mt('No.').'</th>'.
1.474     albertel 3282: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3283:     my (@parts) = sort(&getpartlist($symb));
                   3284:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3285:     my @partids = ();
1.41      ng       3286:     foreach my $part (@parts) {
                   3287: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3288: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3289: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3290: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3291:         push(@partids, $partid);
1.324     albertel 3292: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3293: 	if ($display =~ /^Partial Credit Factor/) {
1.485     albertel 3294: 	    $result.='<th>'.
                   3295: 		&mt('Score Part: [_1]<br /> (weight = [_2])',
                   3296: 		    $display_part,$weight{$partid}).'</th>'."\n";
1.41      ng       3297: 	    next;
1.485     albertel 3298: 	    
1.207     albertel 3299: 	} else {
1.485     albertel 3300: 	    if ($display =~ /Problem Status/) {
                   3301: 		my $grade_status_mt = &mt('Grade Status');
                   3302: 		$display =~ s{Problem Status}{$grade_status_mt<br />};
                   3303: 	    }
                   3304: 	    my $part_mt = &mt('Part:');
                   3305: 	    $display =~s{\[Part: \Q$partid\E\]}{$part_mt $display_part};
1.41      ng       3306: 	}
1.485     albertel 3307: 
1.474     albertel 3308: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3309:     }
1.474     albertel 3310:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3311: 
1.270     albertel 3312:     my %last_resets = 
                   3313: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3314: 
1.41      ng       3315:     #get info for each student
1.44      ng       3316:     #list all the students - with points and grade status
1.257     albertel 3317:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3318:     my $ctr = 0;
1.294     albertel 3319:     foreach (sort 
                   3320: 	     {
                   3321: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3322: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3323: 		 }
                   3324: 		 return $a cmp $b;
                   3325: 	     } (keys(%$fullname))) {
1.126     ng       3326: 	$ctr++;
1.324     albertel 3327: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3328: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3329:     }
1.474     albertel 3330:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3331:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.485     albertel 3332:     $result.='<input type="button" value="'.&mt('Save').'" '.
1.417     albertel 3333: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3334:     if (scalar(%$fullname) eq 0) {
                   3335: 	my $colspan=3+scalar(@parts);
1.433     banghart 3336: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3337:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3338: 	$result='<span class="LC_warning">'.
1.485     albertel 3339: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade.',
1.442     banghart 3340: 	        $section_display, $stu_status).
1.433     banghart 3341: 	    '</span>';
1.96      albertel 3342:     }
1.324     albertel 3343:     $result.=&show_grading_menu_form($symb);
1.41      ng       3344:     return $result;
                   3345: }
                   3346: 
1.44      ng       3347: #--- call by previous routine to display each student
1.41      ng       3348: sub viewstudentgrade {
1.324     albertel 3349:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3350:     my ($uname,$udom) = split(/:/,$student);
                   3351:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3352:     my %aggregates = (); 
1.474     albertel 3353:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3354: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3355: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3356: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3357: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3358: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3359:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3360:     foreach my $apart (@$parts) {
                   3361: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3362: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3363:         $result.='<td align="center">';
1.269     raeburn  3364:         my ($aggtries,$totaltries);
                   3365:         unless (exists($aggregates{$part})) {
1.270     albertel 3366: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3367: 
                   3368: 	    $aggtries = $totaltries;
1.269     raeburn  3369:             if ($$last_resets{$part}) {  
1.270     albertel 3370:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3371: 					   $part);
                   3372:             }
1.269     raeburn  3373:             $result.='<input type="hidden" name="'.
                   3374:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3375:             $result.='<input type="hidden" name="'.
                   3376:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3377:             $aggregates{$part} = 1;
                   3378:         }
1.41      ng       3379: 	if ($type eq 'awarded') {
1.320     albertel 3380: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3381: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3382: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3383: 	    $result.='<input type="text" name="'.
1.89      albertel 3384: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3385: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3386: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3387: 	} elsif ($type eq 'solved') {
                   3388: 	    my ($status,$foo)=split(/_/,$score,2);
                   3389: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3390: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3391: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3392: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3393: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3394: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.485     albertel 3395: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected" value="excused">'.&mt('excused').'</option>' 
                   3396: 		: '<option selected="selected"> </option><option value="excused">'.&mt('excused').'</option>')."\n";
                   3397: 	    $result.='<option value="reset status">'.&mt('reset status').'</option>';
1.126     ng       3398: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3399: 	} else {
                   3400: 	    $result.='<input type="hidden" name="'.
                   3401: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3402: 		    "\n";
1.233     albertel 3403: 	    $result.='<input type="text" name="'.
1.122     ng       3404: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3405: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3406: 	}
                   3407:     }
1.474     albertel 3408:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3409:     return $result;
1.38      ng       3410: }
                   3411: 
1.44      ng       3412: #--- change scores for all the students in a section/class
                   3413: #    record does not get update if unchanged
1.38      ng       3414: sub editgrades {
1.41      ng       3415:     my ($request) = @_;
                   3416: 
1.324     albertel 3417:     my $symb=&get_symb($request);
1.433     banghart 3418:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3419:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3420:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3421:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3422: 
1.477     albertel 3423:     my $result= &Apache::loncommon::start_data_table().
                   3424: 	&Apache::loncommon::start_data_table_header_row().
                   3425: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3426: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       3427:     my %scoreptr = (
                   3428: 		    'correct'  =>'correct_by_override',
                   3429: 		    'incorrect'=>'incorrect_by_override',
                   3430: 		    'excused'  =>'excused',
                   3431: 		    'ungraded' =>'ungraded_attempted',
                   3432: 		    'nothing'  => '',
                   3433: 		    );
1.257     albertel 3434:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3435: 
1.44      ng       3436:     my (@partid);
                   3437:     my %weight = ();
1.54      albertel 3438:     my %columns = ();
1.44      ng       3439:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3440: 
1.324     albertel 3441:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3442:     my $header;
1.257     albertel 3443:     while ($ctr < $env{'form.totalparts'}) {
                   3444: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3445: 	push @partid,$partid;
1.257     albertel 3446: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3447: 	$ctr++;
1.54      albertel 3448:     }
1.324     albertel 3449:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3450:     foreach my $partid (@partid) {
1.478     albertel 3451: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3452: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 3453: 	$columns{$partid}=2;
                   3454: 	foreach my $stores (@parts) {
                   3455: 	    my ($part,$type) = &split_part_type($stores);
                   3456: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3457: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3458: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3459: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3460: 	    $display =~ s/Number of Attempts/Tries/;
1.478     albertel 3461: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3462: 		'<th align="center">'.&mt('New '.$display).'</th>';
1.54      albertel 3463: 	    $columns{$partid}+=2;
                   3464: 	}
                   3465:     }
                   3466:     foreach my $partid (@partid) {
1.324     albertel 3467: 	my $display_part=&get_display_part($partid,$symb);
1.478     albertel 3468: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3469: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3470: 	    '</th>';
1.54      albertel 3471: 
1.44      ng       3472:     }
1.477     albertel 3473:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3474: 	&Apache::loncommon::start_data_table_header_row().
                   3475: 	$header.
                   3476: 	&Apache::loncommon::end_data_table_header_row();
                   3477:     my @noupdate;
1.126     ng       3478:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3479:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3480: 	my $line;
1.257     albertel 3481: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3482: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3483: 	my %newrecord;
                   3484: 	my $updateflag = 0;
1.281     albertel 3485: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3486: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3487: 	if (!&canmodify($usec)) {
1.126     ng       3488: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3489: 	    push(@noupdate,
1.478     albertel 3490: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3491: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3492: 	    next;
                   3493: 	}
1.269     raeburn  3494:         my %aggregate = ();
                   3495:         my $aggregateflag = 0;
1.281     albertel 3496: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3497: 	foreach (@partid) {
1.257     albertel 3498: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3499: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3500: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3501: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3502: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3503: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3504: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3505: 	    my $score;
                   3506: 	    if ($partial eq '') {
1.257     albertel 3507: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3508: 	    } elsif ($partial > 0) {
                   3509: 		$score = 'correct_by_override';
                   3510: 	    } elsif ($partial == 0) {
                   3511: 		$score = 'incorrect_by_override';
                   3512: 	    }
1.257     albertel 3513: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3514: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3515: 
1.292     albertel 3516: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3517: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3518: 	    if ($dropMenu eq 'reset status' &&
                   3519: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3520: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3521: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3522: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3523: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3524: 		$updateflag = 1;
1.269     raeburn  3525:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3526:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3527:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3528:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3529:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3530:                     $aggregateflag = 1;
                   3531:                 }
1.139     albertel 3532: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3533: 		$updateflag = 1;
                   3534: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3535: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3536: 		$rec_update++;
1.125     ng       3537: 	    }
                   3538: 
1.93      albertel 3539: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3540: 		'<td align="center">'.$awarded.
                   3541: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3542: 
1.54      albertel 3543: 
                   3544: 	    my $partid=$_;
                   3545: 	    foreach my $stores (@parts) {
                   3546: 		my ($part,$type) = &split_part_type($stores);
                   3547: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3548: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3549: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3550: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3551: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3552: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3553: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3554: 		    $updateflag=1;
                   3555: 		}
1.93      albertel 3556: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3557: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3558: 	    }
1.44      ng       3559: 	}
1.477     albertel 3560: 	$line.="\n";
1.301     albertel 3561: 
                   3562: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3563: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3564: 
1.44      ng       3565: 	if ($updateflag) {
                   3566: 	    $count++;
1.257     albertel 3567: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3568: 				    $udom,$uname);
1.301     albertel 3569: 
                   3570: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3571: 					      $cnum,$udom,$uname)) {
                   3572: 		# need to figure out if should be in queue.
                   3573: 		my %record =  
                   3574: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3575: 					     $udom,$uname);
                   3576: 		my $all_graded = 1;
                   3577: 		my $none_graded = 1;
                   3578: 		foreach my $part (@parts) {
                   3579: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3580: 			$all_graded = 0;
                   3581: 		    } else {
                   3582: 			$none_graded = 0;
                   3583: 		    }
                   3584: 		}
                   3585: 
                   3586: 		if ($all_graded || $none_graded) {
                   3587: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3588: 							   $symb,$cdom,$cnum,
                   3589: 							   $udom,$uname);
                   3590: 		}
                   3591: 	    }
                   3592: 
1.477     albertel 3593: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3594: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3595: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3596: 	    $updateCtr++;
1.93      albertel 3597: 	} else {
1.477     albertel 3598: 	    push(@noupdate,
                   3599: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3600: 	    $noupdateCtr++;
1.44      ng       3601: 	}
1.269     raeburn  3602:         if ($aggregateflag) {
                   3603:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3604: 				  $cdom,$cnum);
1.269     raeburn  3605:         }
1.93      albertel 3606:     }
1.477     albertel 3607:     if (@noupdate) {
1.126     ng       3608: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3609: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3610: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3611: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3612: 	    &mt('No Changes Occurred For the Students Below').
                   3613: 	    '</td>'.
1.477     albertel 3614: 	    &Apache::loncommon::end_data_table_row();
                   3615: 	foreach my $line (@noupdate) {
                   3616: 	    $result.=
                   3617: 		&Apache::loncommon::start_data_table_row().
                   3618: 		$line.
                   3619: 		&Apache::loncommon::end_data_table_row();
                   3620: 	}
1.44      ng       3621:     }
1.477     albertel 3622:     $result .= &Apache::loncommon::end_data_table().
                   3623: 	&show_grading_menu_form($symb);
1.478     albertel 3624:     my $msg = '<p><b>'.
                   3625: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3626: 	    $rec_update,$count).'</b><br />'.
                   3627: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3628: 	'</b></p>';
1.44      ng       3629:     return $title.$msg.$result;
1.5       albertel 3630: }
1.54      albertel 3631: 
                   3632: sub split_part_type {
                   3633:     my ($partstr) = @_;
                   3634:     my ($temp,@allparts)=split(/_/,$partstr);
                   3635:     my $type=pop(@allparts);
1.439     albertel 3636:     my $part=join('_',@allparts);
1.54      albertel 3637:     return ($part,$type);
                   3638: }
                   3639: 
1.44      ng       3640: #------------- end of section for handling grading by section/class ---------
                   3641: #
                   3642: #----------------------------------------------------------------------------
                   3643: 
1.5       albertel 3644: 
1.44      ng       3645: #----------------------------------------------------------------------------
                   3646: #
                   3647: #-------------------------- Next few routines handles grading by csv upload
                   3648: #
                   3649: #--- Javascript to handle csv upload
1.27      albertel 3650: sub csvupload_javascript_reverse_associate {
1.246     albertel 3651:     my $error1=&mt('You need to specify the username or ID');
                   3652:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3653:   return(<<ENDPICK);
                   3654:   function verify(vf) {
                   3655:     var foundsomething=0;
                   3656:     var founduname=0;
1.243     albertel 3657:     var foundID=0;
1.27      albertel 3658:     for (i=0;i<=vf.nfields.value;i++) {
                   3659:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3660:       if (i==0 && tw!=0) { foundID=1; }
                   3661:       if (i==1 && tw!=0) { founduname=1; }
                   3662:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3663:     }
1.246     albertel 3664:     if (founduname==0 && foundID==0) {
                   3665: 	alert('$error1');
                   3666: 	return;
1.27      albertel 3667:     }
                   3668:     if (foundsomething==0) {
1.246     albertel 3669: 	alert('$error2');
                   3670: 	return;
1.27      albertel 3671:     }
                   3672:     vf.submit();
                   3673:   }
                   3674:   function flip(vf,tf) {
                   3675:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3676:     var i;
                   3677:     for (i=0;i<=vf.nfields.value;i++) {
                   3678:       //can not pick the same destination field for both name and domain
                   3679:       if (((i ==0)||(i ==1)) && 
                   3680:           ((tf==0)||(tf==1)) && 
                   3681:           (i!=tf) &&
                   3682:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3683:         eval('vf.f'+i+'.selectedIndex=0;')
                   3684:       }
                   3685:     }
                   3686:   }
                   3687: ENDPICK
                   3688: }
                   3689: 
                   3690: sub csvupload_javascript_forward_associate {
1.246     albertel 3691:     my $error1=&mt('You need to specify the username or ID');
                   3692:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3693:   return(<<ENDPICK);
                   3694:   function verify(vf) {
                   3695:     var foundsomething=0;
                   3696:     var founduname=0;
1.243     albertel 3697:     var foundID=0;
1.27      albertel 3698:     for (i=0;i<=vf.nfields.value;i++) {
                   3699:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3700:       if (tw==1) { foundID=1; }
                   3701:       if (tw==2) { founduname=1; }
                   3702:       if (tw>3) { foundsomething=1; }
1.27      albertel 3703:     }
1.246     albertel 3704:     if (founduname==0 && foundID==0) {
                   3705: 	alert('$error1');
                   3706: 	return;
1.27      albertel 3707:     }
                   3708:     if (foundsomething==0) {
1.246     albertel 3709: 	alert('$error2');
                   3710: 	return;
1.27      albertel 3711:     }
                   3712:     vf.submit();
                   3713:   }
                   3714:   function flip(vf,tf) {
                   3715:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3716:     var i;
                   3717:     //can not pick the same destination field twice
                   3718:     for (i=0;i<=vf.nfields.value;i++) {
                   3719:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3720:         eval('vf.f'+i+'.selectedIndex=0;')
                   3721:       }
                   3722:     }
                   3723:   }
                   3724: ENDPICK
                   3725: }
                   3726: 
1.26      albertel 3727: sub csvuploadmap_header {
1.324     albertel 3728:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3729:     my $javascript;
1.257     albertel 3730:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3731: 	$javascript=&csvupload_javascript_reverse_associate();
                   3732:     } else {
                   3733: 	$javascript=&csvupload_javascript_forward_associate();
                   3734:     }
1.45      ng       3735: 
1.324     albertel 3736:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3737:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3738:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3739:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3740:     $request->print(<<ENDPICK);
1.26      albertel 3741: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3742: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3743: $result
1.326     albertel 3744: <hr />
1.26      albertel 3745: <h3>Identify fields</h3>
                   3746: Total number of records found in file: $distotal <hr />
                   3747: Enter as many fields as you can. The system will inform you and bring you back
                   3748: to this page if the data selected is insufficient to run your class.<hr />
                   3749: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3750: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3751: <input type="hidden" name="associate"  value="" />
                   3752: <input type="hidden" name="phase"      value="three" />
                   3753: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3754: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3755: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3756: <input type="hidden" name="upfile_associate" 
1.257     albertel 3757:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3758: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3759: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3760: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3761: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3762: <hr />
                   3763: <script type="text/javascript" language="Javascript">
                   3764: $javascript
                   3765: </script>
                   3766: ENDPICK
1.118     ng       3767:     return '';
1.26      albertel 3768: 
                   3769: }
                   3770: 
                   3771: sub csvupload_fields {
1.324     albertel 3772:     my ($symb) = @_;
                   3773:     my (@parts) = &getpartlist($symb);
1.243     albertel 3774:     my @fields=(['ID','Student ID'],
                   3775: 		['username','Student Username'],
                   3776: 		['domain','Student Domain']);
1.324     albertel 3777:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3778:     foreach my $part (sort(@parts)) {
                   3779: 	my @datum;
                   3780: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3781: 	my $name=$part;
                   3782: 	if  (!$display) { $display = $name; }
                   3783: 	@datum=($name,$display);
1.244     albertel 3784: 	if ($name=~/^stores_(.*)_awarded/) {
                   3785: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3786: 	}
1.41      ng       3787: 	push(@fields,\@datum);
                   3788:     }
                   3789:     return (@fields);
1.26      albertel 3790: }
                   3791: 
                   3792: sub csvuploadmap_footer {
1.41      ng       3793:     my ($request,$i,$keyfields) =@_;
                   3794:     $request->print(<<ENDPICK);
1.26      albertel 3795: </table>
                   3796: <input type="hidden" name="nfields" value="$i" />
                   3797: <input type="hidden" name="keyfields" value="$keyfields" />
                   3798: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3799: </form>
                   3800: ENDPICK
                   3801: }
                   3802: 
1.283     albertel 3803: sub checkforfile_js {
1.86      ng       3804:     my $result =<<CSVFORMJS;
                   3805: <script type="text/javascript" language="javascript">
                   3806:     function checkUpload(formname) {
                   3807: 	if (formname.upfile.value == "") {
                   3808: 	    alert("Please use the browse button to select a file from your local directory.");
                   3809: 	    return false;
                   3810: 	}
                   3811: 	formname.submit();
                   3812:     }
                   3813:     </script>
                   3814: CSVFORMJS
1.283     albertel 3815:     return $result;
                   3816: }
                   3817: 
                   3818: sub upcsvScores_form {
                   3819:     my ($request) = shift;
1.324     albertel 3820:     my ($symb)=&get_symb($request);
1.283     albertel 3821:     if (!$symb) {return '';}
                   3822:     my $result=&checkforfile_js();
1.257     albertel 3823:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3824:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3825:     $result.=$table;
1.326     albertel 3826:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3827:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3828:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3829: 	'.</b></td></tr>'."\n";
                   3830:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3831:     my $upload=&mt("Upload Scores");
1.86      ng       3832:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3833:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3834:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3835:     $result.=<<ENDUPFORM;
1.106     albertel 3836: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3837: <input type="hidden" name="symb" value="$symb" />
                   3838: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3839: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3840: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3841: $upfile_select
1.370     www      3842: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3843: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3844: </form>
                   3845: ENDUPFORM
1.370     www      3846:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3847:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3848:     .'</td></tr></table>'."\n";
1.86      ng       3849:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3850:     $result.=&show_grading_menu_form($symb);
1.86      ng       3851:     return $result;
                   3852: }
                   3853: 
                   3854: 
1.26      albertel 3855: sub csvuploadmap {
1.41      ng       3856:     my ($request)= @_;
1.324     albertel 3857:     my ($symb)=&get_symb($request);
1.41      ng       3858:     if (!$symb) {return '';}
1.72      ng       3859: 
1.41      ng       3860:     my $datatoken;
1.257     albertel 3861:     if (!$env{'form.datatoken'}) {
1.41      ng       3862: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3863:     } else {
1.257     albertel 3864: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3865: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3866:     }
1.41      ng       3867:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3868:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3869:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3870:     my ($i,$keyfields);
                   3871:     if (@records) {
1.324     albertel 3872: 	my @fields=&csvupload_fields($symb);
1.45      ng       3873: 
1.257     albertel 3874: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3875: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3876: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3877: 							  \@fields);
                   3878: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3879: 	    chop($keyfields);
                   3880: 	} else {
                   3881: 	    unshift(@fields,['none','']);
                   3882: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3883: 							    \@fields);
1.311     banghart 3884:             foreach my $rec (@records) {
                   3885:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3886:                 if (%temp) {
                   3887:                     $keyfields=join(',',sort(keys(%temp)));
                   3888:                     last;
                   3889:                 }
                   3890:             }
1.41      ng       3891: 	}
                   3892:     }
                   3893:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3894:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3895: 
1.41      ng       3896:     return '';
1.27      albertel 3897: }
                   3898: 
1.246     albertel 3899: sub csvuploadoptions {
1.41      ng       3900:     my ($request)= @_;
1.324     albertel 3901:     my ($symb)=&get_symb($request);
1.257     albertel 3902:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3903:     my $ignore=&mt('Ignore First Line');
                   3904:     $request->print(<<ENDPICK);
                   3905: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3906: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3907: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3908: <!--
1.246     albertel 3909: <p>
                   3910: <label>
                   3911:    <input type="checkbox" name="show_full_results" />
                   3912:    Show a table of all changes
                   3913: </label>
                   3914: </p>
1.302     albertel 3915: -->
1.246     albertel 3916: <p>
                   3917: <label>
                   3918:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3919:    Overwrite any existing score
                   3920: </label>
                   3921: </p>
                   3922: ENDPICK
                   3923:     my %fields=&get_fields();
                   3924:     if (!defined($fields{'domain'})) {
1.257     albertel 3925: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3926: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3927:     }
1.257     albertel 3928:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3929: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3930: 	my $cleankey=$1;
                   3931: 	if ($cleankey eq 'command') { next; }
                   3932: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3933: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3934:     }
                   3935:     # FIXME do a check for any duplicated user ids...
                   3936:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3937:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3938: <hr /></form>'."\n");
1.324     albertel 3939:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3940:     return '';
                   3941: }
                   3942: 
                   3943: sub get_fields {
                   3944:     my %fields;
1.257     albertel 3945:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3946:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3947: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3948: 	    if ($env{'form.f'.$i} ne 'none') {
                   3949: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3950: 	    }
                   3951: 	} else {
1.257     albertel 3952: 	    if ($env{'form.f'.$i} ne 'none') {
                   3953: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3954: 	    }
                   3955: 	}
1.27      albertel 3956:     }
1.246     albertel 3957:     return %fields;
                   3958: }
                   3959: 
                   3960: sub csvuploadassign {
                   3961:     my ($request)= @_;
1.324     albertel 3962:     my ($symb)=&get_symb($request);
1.246     albertel 3963:     if (!$symb) {return '';}
1.345     bowersj2 3964:     my $error_msg = '';
1.246     albertel 3965:     &Apache::loncommon::load_tmp_file($request);
                   3966:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3967:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3968:     my %fields=&get_fields();
1.41      ng       3969:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3970:     my $courseid=$env{'request.course.id'};
1.97      albertel 3971:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3972:     my @notallowed;
1.41      ng       3973:     my @skipped;
                   3974:     my $countdone=0;
                   3975:     foreach my $grade (@gradedata) {
                   3976: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3977: 	my $domain;
                   3978: 	if ($entries{$fields{'domain'}}) {
                   3979: 	    $domain=$entries{$fields{'domain'}};
                   3980: 	} else {
1.257     albertel 3981: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3982: 	}
1.243     albertel 3983: 	$domain=~s/\s//g;
1.41      ng       3984: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3985: 	$username=~s/\s//g;
1.243     albertel 3986: 	if (!$username) {
                   3987: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3988: 	    $id=~s/\s//g;
1.243     albertel 3989: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3990: 	    $username=$ids{$id};
                   3991: 	}
1.41      ng       3992: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3993: 	    my $id=$entries{$fields{'ID'}};
                   3994: 	    $id=~s/\s//g;
                   3995: 	    if ($id) {
                   3996: 		push(@skipped,"$id:$domain");
                   3997: 	    } else {
                   3998: 		push(@skipped,"$username:$domain");
                   3999: 	    }
1.41      ng       4000: 	    next;
                   4001: 	}
1.108     albertel 4002: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 4003: 	if (!&canmodify($usec)) {
                   4004: 	    push(@notallowed,"$username:$domain");
                   4005: 	    next;
                   4006: 	}
1.244     albertel 4007: 	my %points;
1.41      ng       4008: 	my %grades;
                   4009: 	foreach my $dest (keys(%fields)) {
1.244     albertel 4010: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   4011: 		$dest eq 'domain') { next; }
                   4012: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   4013: 	    if ($dest=~/stores_(.*)_points/) {
                   4014: 		my $part=$1;
                   4015: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   4016: 					      $symb,$domain,$username);
1.345     bowersj2 4017:                 if ($wgt) {
                   4018:                     $entries{$fields{$dest}}=~s/\s//g;
                   4019:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 4020:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   4021:                                           : 'correct_by_override';
1.345     bowersj2 4022:                     $grades{"resource.$part.awarded"}=$pcr;
                   4023:                     $grades{"resource.$part.solved"}=$award;
                   4024:                     $points{$part}=1;
                   4025:                 } else {
                   4026:                     $error_msg = "<br />" .
                   4027:                         &mt("Some point values were assigned"
                   4028:                             ." for problems with a weight "
                   4029:                             ."of zero. These values were "
                   4030:                             ."ignored.");
                   4031:                 }
1.244     albertel 4032: 	    } else {
                   4033: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   4034: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   4035: 		my $store_key=$dest;
                   4036: 		$store_key=~s/^stores/resource/;
                   4037: 		$store_key=~s/_/\./g;
                   4038: 		$grades{$store_key}=$entries{$fields{$dest}};
                   4039: 	    }
1.41      ng       4040: 	}
1.398     albertel 4041: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 4042: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 4043: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   4044: 					   $env{'request.course.id'},
                   4045: 					   $domain,$username);
                   4046: 	if ($result eq 'ok') {
                   4047: 	    $request->print('.');
                   4048: 	} else {
                   4049: 	    $request->print("<p>
1.398     albertel 4050:                               <span class=\"LC_error\">
                   4051:                                  Failed to save student $username:$domain.
                   4052:                                  Message when trying to save was ($result)
                   4053:                               </span>
1.302     albertel 4054:                              </p>" );
                   4055: 	}
1.41      ng       4056: 	$request->rflush();
                   4057: 	$countdone++;
                   4058:     }
1.398     albertel 4059:     $request->print("<br />Saved $countdone students\n");
1.41      ng       4060:     if (@skipped) {
1.398     albertel 4061: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 4062: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4063:     }
                   4064:     if (@notallowed) {
1.398     albertel 4065: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 4066: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4067:     }
1.106     albertel 4068:     $request->print("<br />\n");
1.324     albertel 4069:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4070:     return $error_msg;
1.26      albertel 4071: }
1.44      ng       4072: #------------- end of section for handling csv file upload ---------
                   4073: #
                   4074: #-------------------------------------------------------------------
                   4075: #
1.122     ng       4076: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4077: #
                   4078: #--- Select a page/sequence and a student to grade
1.68      ng       4079: sub pickStudentPage {
                   4080:     my ($request) = shift;
                   4081: 
                   4082:     $request->print(<<LISTJAVASCRIPT);
                   4083: <script type="text/javascript" language="javascript">
                   4084: 
                   4085: function checkPickOne(formname) {
1.76      ng       4086:     if (radioSelection(formname.student) == null) {
1.68      ng       4087: 	alert("Please select the student you wish to grade.");
                   4088: 	return;
                   4089:     }
1.125     ng       4090:     ptr = pullDownSelection(formname.selectpage);
                   4091:     formname.page.value = formname["page"+ptr].value;
                   4092:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4093:     formname.submit();
                   4094: }
                   4095: 
                   4096: </script>
                   4097: LISTJAVASCRIPT
1.118     ng       4098:     &commonJSfunctions($request);
1.324     albertel 4099:     my ($symb) = &get_symb($request);
1.257     albertel 4100:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4101:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4102:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4103: 
1.398     albertel 4104:     my $result='<h3><span class="LC_info">&nbsp;'.
1.485     albertel 4105: 	&mt('Manual Grading by Page or Sequence').'</span></h3>';
1.68      ng       4106: 
1.80      ng       4107:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.423     albertel 4108:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4109:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4110: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4111: #    my $type=($curpage =~ /\.(page|sequence)/);
1.485     albertel 4112:     my $select = '<select name="selectpage">'."\n";
1.70      ng       4113:     my $ctr=0;
1.68      ng       4114:     foreach (@$titles) {
                   4115: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.485     albertel 4116: 	$select.='<option value="'.$ctr.'" '.
1.401     albertel 4117: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4118: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4119: 	$ctr++;
1.68      ng       4120:     }
1.485     albertel 4121:     $select.= '</select>';
                   4122:     $result.=&mt('&nbsp;<b>Problems from:</b> [_1]',$select)."<br />\n";
                   4123: 
1.70      ng       4124:     $ctr=0;
                   4125:     foreach (@$titles) {
                   4126: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4127: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4128: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4129: 	$ctr++;
                   4130:     }
1.72      ng       4131:     $result.='<input type="hidden" name="page" />'."\n".
                   4132: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4133: 
1.485     albertel 4134:     my $options =
                   4135: 	'<label><input type="radio" name="vProb" value="no" checked="checked" /> '.&mt('no').' </label>'."\n".
                   4136: 	'<label><input type="radio" name="vProb" value="yes" /> '.&mt('yes').' </label>'."<br />\n";
                   4137:     $result.='&nbsp;'.&mt('<b>View Problems Text: </b> [_1]',$options);
                   4138: 
                   4139:     $options =
                   4140: 	'<label><input type="radio" name="lastSub" value="none" /> '.&mt('none').' </label>'."\n".
                   4141: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> '.&mt('by dates and submissions').'</label>'."\n".
                   4142: 	'<label><input type="radio" name="lastSub" value="all" /> '.&mt('all details').' </label>'."\n";
                   4143:     $result.='&nbsp;'.&mt('<b>Submission Details: </b>[_1]',$options);
1.432     banghart 4144:     
                   4145:     $result.=&build_section_inputs();
1.442     banghart 4146:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4147:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4148: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4149: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4150: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4151: 
1.485     albertel 4152:     $result.='&nbsp;'.&mt('<b>Use CODE: [_1] </b>',
                   4153: 			  '<input type="text" name="CODE" value="" />').
                   4154: 			      '<br />'."\n";
1.382     albertel 4155: 
1.80      ng       4156:     $result.='&nbsp;<input type="button" '.
1.485     albertel 4157: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /><br />'."\n";
1.72      ng       4158: 
1.68      ng       4159:     $request->print($result);
                   4160: 
1.485     albertel 4161:     my $studentTable.='&nbsp;<b>'.&mt('Select a student you wish to grade and then click on the Next button.').'</b><br />'.
1.484     albertel 4162: 	&Apache::loncommon::start_data_table().
                   4163: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4164: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4165: 	'<th>'.&nameUserString('header').'</th>'.
1.485     albertel 4166: 	'<th align="right">&nbsp;'.&mt('No.').'</th>'.
1.484     albertel 4167: 	'<th>'.&nameUserString('header').'</th>'.
                   4168: 	&Apache::loncommon::end_data_table_header_row();
1.68      ng       4169:  
1.76      ng       4170:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4171:     my $ptr = 1;
1.294     albertel 4172:     foreach my $student (sort 
                   4173: 			 {
                   4174: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4175: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4176: 			     }
                   4177: 			     return $a cmp $b;
                   4178: 			 } (keys(%$fullname))) {
1.68      ng       4179: 	my ($uname,$udom) = split(/:/,$student);
1.484     albertel 4180: 	$studentTable.=($ptr%2==1 ? &Apache::loncommon::start_data_table_row()
                   4181:                                   : '</td>');
1.126     ng       4182: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4183: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4184: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.484     albertel 4185: 	$studentTable.=
                   4186: 	    ($ptr%2 == 0 ? '</td>'.&Apache::loncommon::end_data_table_row() 
                   4187:                          : '');
1.68      ng       4188: 	$ptr++;
                   4189:     }
1.484     albertel 4190:     if ($ptr%2 == 0) {
                   4191: 	$studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td>'.
                   4192: 	    &Apache::loncommon::end_data_table_row();
                   4193:     }
                   4194:     $studentTable.=&Apache::loncommon::end_data_table()."\n";
1.126     ng       4195:     $studentTable.='<input type="button" '.
1.485     albertel 4196: 	'onClick="javascript:checkPickOne(this.form);" value="'.&mt('Next-&gt;').'" /></form>'."\n";
1.68      ng       4197: 
1.324     albertel 4198:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4199:     $request->print($studentTable);
                   4200: 
                   4201:     return '';
                   4202: }
                   4203: 
                   4204: sub getSymbMap {
1.132     bowersj2 4205:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4206: 
                   4207:     my %symbx = ();
                   4208:     my @titles = ();
1.117     bowersj2 4209:     my $minder = 0;
                   4210: 
                   4211:     # Gather every sequence that has problems.
1.240     albertel 4212:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4213: 					       1,0,1);
1.117     bowersj2 4214:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4215: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4216: 	    my $title = $minder.'.'.
                   4217: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4218: 	    push(@titles, $title); # minder in case two titles are identical
                   4219: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4220: 	    $minder++;
1.241     albertel 4221: 	}
1.68      ng       4222:     }
                   4223:     return \@titles,\%symbx;
                   4224: }
                   4225: 
1.72      ng       4226: #
                   4227: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4228: sub displayPage {
                   4229:     my ($request) = shift;
                   4230: 
1.324     albertel 4231:     my ($symb) = &get_symb($request);
1.257     albertel 4232:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4233:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4234:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4235:     my $pageTitle = $env{'form.page'};
1.103     albertel 4236:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4237:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4238:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4239: 
                   4240:     #need to make sure we have the correct data for later EXT calls, 
                   4241:     #thus invalidate the cache
                   4242:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4243:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4244:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4245:     &Apache::lonnet::clear_EXT_cache_status();
                   4246: 
1.103     albertel 4247:     if (!&canview($usec)) {
1.485     albertel 4248: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested student. ([_1])',$env{'form.student'}).'</span>');
1.324     albertel 4249: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4250: 	return;
                   4251:     }
1.398     albertel 4252:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.485     albertel 4253:     $result.='<h3>&nbsp;'.&mt('Student: [_1]',&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom)).
1.129     ng       4254: 	'</h3>'."\n";
1.382     albertel 4255:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
1.485     albertel 4256: 	$result.='<h3>&nbsp;'.&mt('CODE: [_1]',$env{'form.CODE'}).'</h3>'."\n";
1.382     albertel 4257:     } else {
                   4258: 	delete($env{'form.CODE'});
                   4259:     }
1.71      ng       4260:     &sub_page_js($request);
                   4261:     $request->print($result);
                   4262: 
1.132     bowersj2 4263:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4264:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4265:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4266:     if (!$map) {
1.485     albertel 4267: 	$request->print('<span class="LC_warning">'.&mt('Unable to view requested sequence. ([_1])',$resUrl).'</span>');
1.324     albertel 4268: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4269: 	return; 
                   4270:     }
1.68      ng       4271:     my $iterator = $navmap->getIterator($map->map_start(),
                   4272: 					$map->map_finish());
                   4273: 
1.71      ng       4274:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4275: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4276: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4277: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4278: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4279: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4280: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4281: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4282: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4283: 
1.382     albertel 4284:     if (defined($env{'form.CODE'})) {
                   4285: 	$studentTable.=
                   4286: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4287:     }
1.381     albertel 4288:     my $checkIcon = '<img alt="'.&mt('Check Mark').
1.485     albertel 4289: 	'" src="'.&Apache::loncommon::lonhttpdurl($request->dir_config('lonIconsURL').'/check.gif').'" height="16" border="0" />';
1.71      ng       4290: 
1.485     albertel 4291:     $studentTable.='&nbsp;'.&mt('<b>Note:</b> Problems graded correct by the computer are marked with a [_1] symbol.',$checkIcon)."\n".
1.484     albertel 4292: 	&Apache::loncommon::start_data_table().
                   4293: 	&Apache::loncommon::start_data_table_header_row().
                   4294: 	'<th align="center">&nbsp;Prob.&nbsp;</th>'.
1.485     albertel 4295: 	'<th>&nbsp;'.($env{'form.vProb'} eq 'no' ? &mt('Title') : &mt('Problem Text')).'/'.&mt('Grade').'</th>'.
1.484     albertel 4296: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4297: 
1.329     albertel 4298:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4299:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4300:     $iterator->next(); # skip the first BEGIN_MAP
                   4301:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4302:     while ($depth > 0) {
1.68      ng       4303:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4304:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4305: 
1.385     albertel 4306:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4307: 	    my $parts = $curRes->parts();
1.68      ng       4308:             my $title = $curRes->compTitle();
1.71      ng       4309: 	    my $symbx = $curRes->symb();
1.484     albertel 4310: 	    $studentTable.=
                   4311: 		&Apache::loncommon::start_data_table_row().
                   4312: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4313: 		(scalar(@{$parts}) == 1 ? '' 
                   4314: 		                        : '<br />('.&mt('[_1]&nbsp;parts)',
                   4315: 							scalar(@{$parts}))
                   4316: 		 ).
                   4317: 		 '</td>';
1.71      ng       4318: 	    $studentTable.='<td valign="top">';
1.382     albertel 4319: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4320: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4321: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4322: 					     undef,'both',\%form);
1.71      ng       4323: 	    } else {
1.382     albertel 4324: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4325: 		$companswer =~ s|<form(.*?)>||g;
                   4326: 		$companswer =~ s|</form>||g;
1.71      ng       4327: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4328: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4329: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4330: #		}
1.116     ng       4331: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.485     albertel 4332: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;'.&mt('<b>Correct answer:</b><br />[_1]',$companswer);
1.71      ng       4333: 	    }
                   4334: 
1.257     albertel 4335: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4336: 
1.257     albertel 4337: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4338: 		if ($record{'version'} eq '') {
1.485     albertel 4339: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">'.&mt('No recorded submission for this problem.').'</span><br />';
1.71      ng       4340: 		} else {
1.116     ng       4341: 		    my %responseType = ();
                   4342: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4343: 			my @responseIds =$curRes->responseIds($partid);
                   4344: 			my @responseType =$curRes->responseType($partid);
                   4345: 			my %responseIds;
                   4346: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4347: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4348: 			}
                   4349: 			$responseType{$partid} = \%responseIds;
1.116     ng       4350: 		    }
1.148     albertel 4351: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4352: 
1.71      ng       4353: 		}
1.257     albertel 4354: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4355: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4356: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4357: 									$env{'request.course.id'},
1.71      ng       4358: 									'','.submission');
                   4359:  
                   4360: 	    }
1.103     albertel 4361: 	    if (&canmodify($usec)) {
                   4362: 		foreach my $partid (@{$parts}) {
                   4363: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4364: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4365: 		    $question++;
                   4366: 		}
1.196     albertel 4367: 		$prob++;
1.71      ng       4368: 	    }
                   4369: 	    $studentTable.='</td></tr>';
1.68      ng       4370: 
1.103     albertel 4371: 	}
1.68      ng       4372:         $curRes = $iterator->next();
                   4373:     }
                   4374: 
1.485     albertel 4375:     $studentTable.='</table>'."\n".
                   4376: 	'<input type="button" value="'.&mt('Save').'" '.
1.381     albertel 4377: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4378: 	'</form>'."\n";
1.324     albertel 4379:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4380:     $request->print($studentTable);
                   4381: 
                   4382:     return '';
1.119     ng       4383: }
                   4384: 
                   4385: sub displaySubByDates {
1.148     albertel 4386:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4387:     my $isCODE=0;
1.335     albertel 4388:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4389:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4390:     my $studentTable=&Apache::loncommon::start_data_table().
                   4391: 	&Apache::loncommon::start_data_table_header_row().
                   4392: 	'<th>'.&mt('Date/Time').'</th>'.
                   4393: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4394: 	'<th>'.&mt('Submission').'</th>'.
                   4395: 	'<th>'.&mt('Status').'</th>'.
                   4396: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4397:     my ($version);
                   4398:     my %mark;
1.148     albertel 4399:     my %orders;
1.119     ng       4400:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4401:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4402: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4403:     }
1.335     albertel 4404: 
                   4405:     my $interaction;
1.119     ng       4406:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4407: 	my $timestamp = 
                   4408: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4409: 	if (exists($$record{$version.':resource.0.version'})) {
                   4410: 	    $interaction = $$record{$version.':resource.0.version'};
                   4411: 	}
                   4412: 
                   4413: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4414: 		             : "$version:resource");
1.467     albertel 4415: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4416: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4417: 	if ($isCODE) {
                   4418: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4419: 	}
1.119     ng       4420: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4421: 	my @displaySub = ();
                   4422: 	foreach my $partid (@{$parts}) {
1.335     albertel 4423: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4424: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4425: 	    
                   4426: 
1.122     ng       4427: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4428: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4429: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4430: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4431: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4432: 
                   4433: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4434: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4435: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4436: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4437: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4438: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4439: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4440: 		    } else {
1.467     albertel 4441: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4442: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4443: 		    }
1.335     albertel 4444: 		    my $responseType=($isTask ? 'Task'
                   4445:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4446: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4447: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4448: 			$orders{$partid}->{$responseId}=
                   4449: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4450: 		    }
1.147     albertel 4451: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4452: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4453: 		}
                   4454: 	    }
1.335     albertel 4455: 	    if (exists($$record{"$where.$partid.checkedin"})) {
1.485     albertel 4456: 		$displaySub[1].=&mt('Checked in by [_1] into slot [_2]',
                   4457: 				    $$record{"$where.$partid.checkedin"},
                   4458: 				    $$record{"$where.$partid.checkedin.slot"}).
                   4459: 					'<br />';
1.335     albertel 4460: 	    }
                   4461: 	    if (exists $$record{"$where.$partid.award"}) {
1.485     albertel 4462: 		$displaySub[1].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4463: 		    lc($$record{"$where.$partid.award"}).' '.
                   4464: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4465: 		    '<br />';
                   4466: 	    }
1.335     albertel 4467: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4468: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4469: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4470: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4471: 		$displaySub[2].=
                   4472: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4473: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4474: 	    }
                   4475: 	}
                   4476: 	# needed because old essay regrader has not parts info
                   4477: 	if (exists $$record{"$version:resource.regrader"}) {
                   4478: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4479: 	}
                   4480: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4481: 	if ($displaySub[2]) {
1.467     albertel 4482: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4483: 	}
1.467     albertel 4484: 	$studentTable.='&nbsp;</td>'.
                   4485: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4486:     }
1.467     albertel 4487:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4488:     return $studentTable;
1.71      ng       4489: }
                   4490: 
                   4491: sub updateGradeByPage {
                   4492:     my ($request) = shift;
                   4493: 
1.257     albertel 4494:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4495:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4496:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4497:     my $pageTitle = $env{'form.page'};
1.103     albertel 4498:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4499:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4500:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4501:     if (!&canmodify($usec)) {
1.398     albertel 4502: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4503: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4504: 	return;
                   4505:     }
1.398     albertel 4506:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4507:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4508: 	'</h3>'."\n";
1.70      ng       4509: 
1.68      ng       4510:     $request->print($result);
                   4511: 
1.132     bowersj2 4512:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4513:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4514:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4515:     if (!$map) {
1.398     albertel 4516: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4517: 	my ($symb)=&get_symb($request);
                   4518: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4519: 	return; 
                   4520:     }
1.71      ng       4521:     my $iterator = $navmap->getIterator($map->map_start(),
                   4522: 					$map->map_finish());
1.70      ng       4523: 
1.484     albertel 4524:     my $studentTable=
                   4525: 	&Apache::loncommon::start_data_table().
                   4526: 	&Apache::loncommon::start_data_table_header_row().
1.485     albertel 4527: 	'<th align="center">&nbsp;'.&mt('Prob.').'&nbsp;</th>'.
                   4528: 	'<th>&nbsp;'.&mt('Title').'&nbsp;</th>'.
                   4529: 	'<th>&nbsp;'.&mt('Previous Score').'&nbsp;</th>'.
                   4530: 	'<th>&nbsp;'.&mt('New Score').'&nbsp;</th>'.
1.484     albertel 4531: 	&Apache::loncommon::end_data_table_header_row();
1.71      ng       4532: 
                   4533:     $iterator->next(); # skip the first BEGIN_MAP
                   4534:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4535:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4536:     while ($depth > 0) {
1.71      ng       4537:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4538:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4539: 
1.385     albertel 4540:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4541: 	    my $parts = $curRes->parts();
1.71      ng       4542:             my $title = $curRes->compTitle();
                   4543: 	    my $symbx = $curRes->symb();
1.484     albertel 4544: 	    $studentTable.=
                   4545: 		&Apache::loncommon::start_data_table_row().
                   4546: 		'<td align="center" valign="top" >'.$prob.
1.485     albertel 4547: 		(scalar(@{$parts}) == 1 ? '' 
                   4548:                                         : '<br />('.&mt('[quant,_1,&nbsp;parts]',scalar(@{$parts}))
                   4549: 		 ).')</td>';
1.71      ng       4550: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4551: 
                   4552: 	    my %newrecord=();
                   4553: 	    my @displayPts=();
1.269     raeburn  4554:             my %aggregate = ();
                   4555:             my $aggregateflag = 0;
1.71      ng       4556: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4557: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4558: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4559: 
1.257     albertel 4560: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4561: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4562: 		my $partial = $newpts/$wgt;
                   4563: 		my $score;
                   4564: 		if ($partial > 0) {
                   4565: 		    $score = 'correct_by_override';
1.125     ng       4566: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4567: 		    $score = 'incorrect_by_override';
                   4568: 		}
1.257     albertel 4569: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4570: 		if ($dropMenu eq 'excused') {
1.71      ng       4571: 		    $partial = '';
                   4572: 		    $score = 'excused';
1.125     ng       4573: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4574: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4575: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4576: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4577: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4578: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4579: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4580: 		    $changeflag++;
                   4581: 		    $newpts = '';
1.269     raeburn  4582:                     
                   4583:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4584:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4585:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4586:                     if ($aggtries > 0) {
                   4587:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4588:                         $aggregateflag = 1;
                   4589:                     }
1.71      ng       4590: 		}
1.324     albertel 4591: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4592: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4593: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4594: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4595: 		    '&nbsp;<br />';
1.207     albertel 4596: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4597: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4598: 		    '&nbsp;<br />';
1.71      ng       4599: 		$question++;
1.380     albertel 4600: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4601: 
1.71      ng       4602: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4603: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4604: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4605: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4606: 
                   4607: 		$changeflag++;
                   4608: 	    }
                   4609: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4610: 		my %record = 
                   4611: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4612: 					     $udom,$uname);
                   4613: 
                   4614: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4615: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4616: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4617: 		    $newrecord{'resource.CODE'} = '';
                   4618: 		}
1.257     albertel 4619: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4620: 					$udom,$uname);
1.382     albertel 4621: 		%record = &Apache::lonnet::restore($symbx,
                   4622: 						   $env{'request.course.id'},
                   4623: 						   $udom,$uname);
1.380     albertel 4624: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4625: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4626: 	    }
1.380     albertel 4627: 	    
1.269     raeburn  4628:             if ($aggregateflag) {
                   4629:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4630:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4631:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4632:             }
1.125     ng       4633: 
1.71      ng       4634: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4635: 		'<td valign="top">'.$displayPts[1].'</td>'.
1.484     albertel 4636: 		&Apache::loncommon::end_data_table_row();
1.68      ng       4637: 
1.196     albertel 4638: 	    $prob++;
1.68      ng       4639: 	}
1.71      ng       4640:         $curRes = $iterator->next();
1.68      ng       4641:     }
1.98      albertel 4642: 
1.484     albertel 4643:     $studentTable.=&Apache::loncommon::end_data_table();
1.324     albertel 4644:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4645:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4646: 		  'The scores were changed for '.
                   4647: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4648:     $request->print($grademsg.$studentTable);
1.68      ng       4649: 
1.70      ng       4650:     return '';
                   4651: }
                   4652: 
1.72      ng       4653: #-------- end of section for handling grading by page/sequence ---------
                   4654: #
                   4655: #-------------------------------------------------------------------
                   4656: 
1.75      albertel 4657: #--------------------Scantron Grading-----------------------------------
                   4658: #
                   4659: #------ start of section for handling grading by page/sequence ---------
                   4660: 
1.423     albertel 4661: =pod
                   4662: 
                   4663: =head1 Bubble sheet grading routines
                   4664: 
1.424     albertel 4665:   For this documentation:
                   4666: 
                   4667:    'scanline' refers to the full line of characters
                   4668:    from the file that we are parsing that represents one entire sheet
                   4669: 
                   4670:    'bubble line' refers to the data
                   4671:    representing the line of bubbles that are on the physical bubble sheet
                   4672: 
                   4673: 
                   4674: The overall process is that a scanned in bubble sheet data is uploaded
                   4675: into a course. When a user wants to grade, they select a
                   4676: sequence/folder of resources, a file of bubble sheet info, and pick
                   4677: one of the predefined configurations for what each scanline looks
                   4678: like.
                   4679: 
                   4680: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4681: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4682: because too light bubbling), 'double bubble' (each bubble line should
                   4683: have no more that one letter picked), invalid or duplicated CODE,
                   4684: invalid student ID
                   4685: 
                   4686: If the CODE option is used that determines the randomization of the
                   4687: homework problems, either way the student ID is looked up into a
                   4688: username:domain.
                   4689: 
                   4690: During the validation phase the instructor can choose to skip scanlines. 
                   4691: 
1.435     foxr     4692: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4693: 
                   4694:   scantron_original_filename (unmodified original file)
                   4695:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4696:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4697: 
                   4698: Also there is a separate hash nohist_scantrondata that contains extra
                   4699: correction information that isn't representable in the bubble sheet
                   4700: file (see &scantron_getfile() for more information)
                   4701: 
                   4702: After all scanlines are either valid, marked as valid or skipped, then
                   4703: foreach line foreach problem in the picked sequence, an ssi request is
                   4704: made that simulates a user submitting their selected letter(s) against
                   4705: the homework problem.
1.423     albertel 4706: 
                   4707: =over 4
                   4708: 
                   4709: 
                   4710: 
                   4711: =item defaultFormData
                   4712: 
                   4713:   Returns html hidden inputs used to hold context/default values.
                   4714: 
                   4715:  Arguments:
                   4716:   $symb - $symb of the current resource 
                   4717: 
                   4718: =cut
1.422     foxr     4719: 
1.81      albertel 4720: sub defaultFormData {
1.324     albertel 4721:     my ($symb)=@_;
1.447     foxr     4722:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4723:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4724:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4725: }
                   4726: 
1.447     foxr     4727: 
1.423     albertel 4728: =pod 
                   4729: 
                   4730: =item getSequenceDropDown
                   4731: 
                   4732:    Return html dropdown of possible sequences to grade
                   4733:  
                   4734:  Arguments:
                   4735:    $symb - $symb of the current resource 
                   4736: 
                   4737: =cut
1.422     foxr     4738: 
1.75      albertel 4739: sub getSequenceDropDown {
1.423     albertel 4740:     my ($symb)=@_;
1.75      albertel 4741:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4742:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4743:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4744:     my $ctr=0;
                   4745:     foreach (@$titles) {
                   4746: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4747: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4748: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4749: 	    '>'.$showtitle.'</option>'."\n";
                   4750: 	$ctr++;
                   4751:     }
                   4752:     $result.= '</select>';
                   4753:     return $result;
                   4754: }
                   4755: 
1.423     albertel 4756: 
                   4757: =pod 
                   4758: 
                   4759: =item scantron_filenames
                   4760: 
                   4761:    Returns a list of the scantron files in the current course 
                   4762: 
                   4763: =cut
1.422     foxr     4764: 
1.202     albertel 4765: sub scantron_filenames {
1.257     albertel 4766:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4767:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4768:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4769: 				    &propath($cdom,$cname));
1.202     albertel 4770:     my @possiblenames;
1.201     albertel 4771:     foreach my $filename (sort(@files)) {
1.157     albertel 4772: 	($filename)=split(/&/,$filename);
                   4773: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4774: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4775: 	push(@possiblenames,$filename);
                   4776:     }
                   4777:     return @possiblenames;
                   4778: }
                   4779: 
1.423     albertel 4780: =pod 
                   4781: 
                   4782: =item scantron_uploads
                   4783: 
                   4784:    Returns  html drop-down list of scantron files in current course.
                   4785: 
                   4786:  Arguments:
                   4787:    $file2grade - filename to set as selected in the dropdown
                   4788: 
                   4789: =cut
1.422     foxr     4790: 
1.202     albertel 4791: sub scantron_uploads {
1.209     ng       4792:     my ($file2grade) = @_;
1.202     albertel 4793:     my $result=	'<select name="scantron_selectfile">';
                   4794:     $result.="<option></option>";
                   4795:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4796: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4797:     }
                   4798:     $result.="</select>";
                   4799:     return $result;
                   4800: }
                   4801: 
1.423     albertel 4802: =pod 
                   4803: 
                   4804: =item scantron_scantab
                   4805: 
                   4806:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4807:   file.
                   4808: 
                   4809: =cut
1.422     foxr     4810: 
1.82      albertel 4811: sub scantron_scantab {
                   4812:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4813:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4814:     $result.='<option></option>'."\n";
1.82      albertel 4815:     foreach my $line (<$fh>) {
                   4816: 	my ($name,$descrip)=split(/:/,$line);
                   4817: 	if ($name =~ /^\#/) { next; }
                   4818: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4819:     }
                   4820:     $result.='</select>'."\n";
                   4821: 
                   4822:     return $result;
                   4823: }
                   4824: 
1.423     albertel 4825: =pod 
                   4826: 
                   4827: =item scantron_CODElist
                   4828: 
                   4829:   Returns html drop down of the saved CODE lists from current course,
                   4830:   generated from earlier printings.
                   4831: 
                   4832: =cut
1.422     foxr     4833: 
1.186     albertel 4834: sub scantron_CODElist {
1.257     albertel 4835:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4836:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4837:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4838:     my $namechoice='<option></option>';
1.225     albertel 4839:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4840: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4841: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4842: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4843:     }
                   4844:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4845:     return $namechoice;
                   4846: }
                   4847: 
1.423     albertel 4848: =pod 
                   4849: 
                   4850: =item scantron_CODEunique
                   4851: 
                   4852:   Returns the html for "Each CODE to be used once" radio.
                   4853: 
                   4854: =cut
1.422     foxr     4855: 
1.186     albertel 4856: sub scantron_CODEunique {
1.381     albertel 4857:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4858:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4859:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4860:                 </span>
                   4861:                 <span style="white-space: nowrap;">
1.272     albertel 4862:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4863:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4864:                 </span>';
1.186     albertel 4865:     return $result;
                   4866: }
1.423     albertel 4867: 
                   4868: =pod 
                   4869: 
                   4870: =item scantron_selectphase
                   4871: 
                   4872:   Generates the initial screen to start the bubble sheet process.
                   4873:   Allows for - starting a grading run.
1.424     albertel 4874:              - downloading existing scan data (original, corrected
1.423     albertel 4875:                                                 or skipped info)
                   4876: 
                   4877:              - uploading new scan data
                   4878: 
                   4879:  Arguments:
                   4880:   $r          - The Apache request object
                   4881:   $file2grade - name of the file that contain the scanned data to score
                   4882: 
                   4883: =cut
1.186     albertel 4884: 
1.75      albertel 4885: sub scantron_selectphase {
1.209     ng       4886:     my ($r,$file2grade) = @_;
1.324     albertel 4887:     my ($symb)=&get_symb($r);
1.75      albertel 4888:     if (!$symb) {return '';}
1.423     albertel 4889:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4890:     my $default_form_data=&defaultFormData($symb);
                   4891:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4892:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4893:     my $format_selector=&scantron_scantab();
1.186     albertel 4894:     my $CODE_selector=&scantron_CODElist();
                   4895:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4896:     my $result;
1.422     foxr     4897: 
                   4898:     # Chunk of form to prompt for a file to grade and how:
                   4899: 
1.75      albertel 4900:     $result.= <<SCANTRONFORM;
1.162     albertel 4901:     <table width="100%" border="0">
1.75      albertel 4902:     <tr>
1.226     albertel 4903:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4904:       <td bgcolor="#777777">
1.203     albertel 4905:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4906:         $default_form_data
1.75      albertel 4907:         <table width="100%" border="0">
                   4908:           <tr bgcolor="#e6ffff">
1.174     albertel 4909:             <td colspan="2">
                   4910:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4911:             </td>
                   4912:           </tr>
                   4913:           <tr bgcolor="#ffffe6">
1.174     albertel 4914:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4915:           </tr>
                   4916:           <tr bgcolor="#ffffe6">
1.174     albertel 4917:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4918:           </tr>
1.82      albertel 4919:           <tr bgcolor="#ffffe6">
1.174     albertel 4920:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4921:           </tr>
1.157     albertel 4922:           <tr bgcolor="#ffffe6">
1.186     albertel 4923:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4924:           </tr>
                   4925:           <tr bgcolor="#ffffe6">
                   4926:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4927:           </tr>
                   4928:           <tr bgcolor="#ffffe6">
1.187     albertel 4929: 	    <td> Options: </td>
                   4930:             <td>
1.272     albertel 4931: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4932:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4933:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4934: 	    </td>
                   4935:           </tr>
                   4936:           <tr bgcolor="#ffffe6">
1.174     albertel 4937:             <td colspan="2">
1.265     www      4938:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4939:             </td>
                   4940:           </tr>
                   4941:         </table>
1.226     albertel 4942:        </td>
                   4943:      </form>
1.162     albertel 4944:     </tr>
                   4945: SCANTRONFORM
                   4946:    
                   4947:     $r->print($result);
                   4948: 
1.257     albertel 4949:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4950:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4951: 
1.422     foxr     4952: 	# Chunk of form to prompt for a scantron file upload.
                   4953: 
1.162     albertel 4954:         $r->print(<<SCANTRONFORM);
                   4955:     <tr>
                   4956:       <td bgcolor="#777777">
                   4957:         <table width="100%" border="0">
                   4958:           <tr bgcolor="#e6ffff">
                   4959:             <td>
1.174     albertel 4960:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4961:             </td>
                   4962:           </tr>
                   4963:           <tr bgcolor="#ffffe6">
                   4964:             <td>
                   4965: SCANTRONFORM
1.324     albertel 4966:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4967:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4968:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4969:     $r->print(<<UPLOAD);
                   4970:               <script type="text/javascript" language="javascript">
                   4971:     function checkUpload(formname) {
                   4972: 	if (formname.upfile.value == "") {
                   4973: 	    alert("Please use the browse button to select a file from your local directory.");
                   4974: 	    return false;
                   4975: 	}
                   4976: 	formname.submit();
                   4977:     }
                   4978:               </script>
                   4979: 
                   4980:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4981:                 $default_form_data
                   4982:                 <input name='courseid' type='hidden' value='$cnum' />
                   4983:                 <input name='domainid' type='hidden' value='$cdom' />
                   4984:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4985:                 File to upload:<input type="file" name="upfile" size="50" />
                   4986:                 <br />
                   4987:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4988:               </form>
                   4989: UPLOAD
1.162     albertel 4990: 
                   4991:         $r->print(<<SCANTRONFORM);
                   4992:             </td>
                   4993:           </tr>
1.75      albertel 4994:         </table>
                   4995:       </td>
                   4996:     </tr>
1.162     albertel 4997: SCANTRONFORM
                   4998:     }
1.422     foxr     4999: 
                   5000:     # Chunk of the form that prompts to view a scoring office file,
                   5001:     # corrected file, skipped records in a file.
                   5002: 
1.187     albertel 5003:     $r->print(<<SCANTRONFORM);
                   5004:     <tr>
1.226     albertel 5005:       <form action='/adm/grades' name='scantron_download'>
                   5006:         <td bgcolor="#777777">
1.379     albertel 5007: 	  $default_form_data
1.187     albertel 5008:           <input type="hidden" name="command" value="scantron_download" />
                   5009:           <table width="100%" border="0">
                   5010:             <tr bgcolor="#e6ffff">
                   5011:               <td colspan="2">
                   5012:                 &nbsp;<b>Download a scoring office file</b>
                   5013:               </td>
                   5014:             </tr>
                   5015:             <tr bgcolor="#ffffe6">
                   5016:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   5017:             </tr>
                   5018:             <tr bgcolor="#ffffe6">
                   5019:               <td colspan="2">
1.293     www      5020:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 5021:               </td>
                   5022:             </tr>
                   5023:           </table>
1.226     albertel 5024:         </td>
                   5025:       </form>
1.187     albertel 5026:     </tr>
                   5027: SCANTRONFORM
1.162     albertel 5028: 
1.457     banghart 5029:     $r->print('<tr><td bgcolor="#777777">');
                   5030:     &Apache::lonpickcode::code_list($r,2);
                   5031:     $r->print('</td></tr></table>');
                   5032:     $r->print($grading_menu_button);
1.162     albertel 5033:     return
1.75      albertel 5034: }
                   5035: 
1.423     albertel 5036: =pod
                   5037: 
                   5038: =item get_scantron_config
                   5039: 
                   5040:    Parse and return the scantron configuration line selected as a
                   5041:    hash of configuration file fields.
                   5042: 
                   5043:  Arguments:
                   5044:     which - the name of the configuration to parse from the file.
                   5045: 
                   5046: 
                   5047:  Returns:
                   5048:             If the named configuration is not in the file, an empty
                   5049:             hash is returned.
                   5050:     a hash with the fields
                   5051:       name         - internal name for the this configuration setup
                   5052:       description  - text to display to operator that describes this config
                   5053:       CODElocation - if 0 or the string 'none'
                   5054:                           - no CODE exists for this config
                   5055:                      if -1 || the string 'letter'
                   5056:                           - a CODE exists for this config and is
                   5057:                             a string of letters
                   5058:                      Unsupported value (but planned for future support)
                   5059:                           if a positive integer
                   5060:                                - The CODE exists as the first n items from
                   5061:                                  the question section of the form
                   5062:                           if the string 'number'
                   5063:                                - The CODE exists for this config and is
                   5064:                                  a string of numbers
                   5065:       CODEstart   - (only matter if a CODE exists) column in the line where
                   5066:                      the CODE starts
                   5067:       CODElength  - length of the CODE
                   5068:       IDstart     - column where the student ID number starts
                   5069:       IDlength    - length of the student ID info
                   5070:       Qstart      - column where the information from the bubbled
                   5071:                     'questions' start
                   5072:       Qlength     - number of columns comprising a single bubble line from
                   5073:                     the sheet. (usually either 1 or 10)
1.424     albertel 5074:       Qon         - either a single character representing the character used
1.423     albertel 5075:                     to signal a bubble was chosen in the positional setup, or
                   5076:                     the string 'letter' if the letter of the chosen bubble is
                   5077:                     in the final, or 'number' if a number representing the
                   5078:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5079:       Qoff        - the character used to represent that a bubble was
                   5080:                     left blank
1.423     albertel 5081:       PaperID     - if the scanning process generates a unique number for each
                   5082:                     sheet scanned the column that this ID number starts in
                   5083:       PaperIDlength - number of columns that comprise the unique ID number
                   5084:                       for the sheet of paper
1.424     albertel 5085:       FirstName   - column that the first name starts in
1.423     albertel 5086:       FirstNameLength - number of columns that the first name spans
                   5087:  
                   5088:       LastName    - column that the last name starts in
                   5089:       LastNameLength - number of columns that the last name spans
                   5090: 
                   5091: =cut
1.422     foxr     5092: 
1.82      albertel 5093: sub get_scantron_config {
                   5094:     my ($which) = @_;
                   5095:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5096:     my %config;
1.157     albertel 5097:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5098:     foreach my $line (<$fh>) {
                   5099: 	my ($name,$descrip)=split(/:/,$line);
                   5100: 	if ($name ne $which ) { next; }
                   5101: 	chomp($line);
                   5102: 	my @config=split(/:/,$line);
                   5103: 	$config{'name'}=$config[0];
                   5104: 	$config{'description'}=$config[1];
                   5105: 	$config{'CODElocation'}=$config[2];
                   5106: 	$config{'CODEstart'}=$config[3];
                   5107: 	$config{'CODElength'}=$config[4];
                   5108: 	$config{'IDstart'}=$config[5];
                   5109: 	$config{'IDlength'}=$config[6];
                   5110: 	$config{'Qstart'}=$config[7];
                   5111: 	$config{'Qlength'}=$config[8];
                   5112: 	$config{'Qoff'}=$config[9];
                   5113: 	$config{'Qon'}=$config[10];
1.157     albertel 5114: 	$config{'PaperID'}=$config[11];
                   5115: 	$config{'PaperIDlength'}=$config[12];
                   5116: 	$config{'FirstName'}=$config[13];
                   5117: 	$config{'FirstNamelength'}=$config[14];
                   5118: 	$config{'LastName'}=$config[15];
                   5119: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5120: 	last;
                   5121:     }
                   5122:     return %config;
                   5123: }
                   5124: 
1.423     albertel 5125: =pod 
                   5126: 
                   5127: =item username_to_idmap
                   5128: 
                   5129:     creates a hash keyed by student id with values of the corresponding
                   5130:     student username:domain.
                   5131: 
                   5132:   Arguments:
                   5133: 
                   5134:     $classlist - reference to the class list hash. This is a hash
                   5135:                  keyed by student name:domain  whose elements are references
1.424     albertel 5136:                  to arrays containing various chunks of information
1.423     albertel 5137:                  about the student. (See loncoursedata for more info).
                   5138: 
                   5139:   Returns
                   5140:     %idmap - the constructed hash
                   5141: 
                   5142: =cut
                   5143: 
1.82      albertel 5144: sub username_to_idmap {
                   5145:     my ($classlist)= @_;
                   5146:     my %idmap;
                   5147:     foreach my $student (keys(%$classlist)) {
                   5148: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5149: 	    $student;
                   5150:     }
                   5151:     return %idmap;
                   5152: }
1.423     albertel 5153: 
                   5154: =pod
                   5155: 
1.424     albertel 5156: =item scantron_fixup_scanline
1.423     albertel 5157: 
                   5158:    Process a requested correction to a scanline.
                   5159: 
                   5160:   Arguments:
                   5161:     $scantron_config   - hash from &get_scantron_config()
                   5162:     $scan_data         - hash of correction information 
                   5163:                           (see &scantron_getfile())
                   5164:     $line              - existing scanline
                   5165:     $whichline         - line number of the passed in scanline
                   5166:     $field             - type of change to process 
                   5167:                          (either 
                   5168:                           'ID'     -> correct the student ID number
                   5169:                           'CODE'   -> correct the CODE
                   5170:                           'answer' -> fixup the submitted answers)
                   5171:     
                   5172:    $args               - hash of additional info,
                   5173:                           - 'ID' 
                   5174:                                'newid' -> studentID to use in replacement
1.424     albertel 5175:                                           of existing one
1.423     albertel 5176:                           - 'CODE' 
                   5177:                                'CODE_ignore_dup' - set to true if duplicates
                   5178:                                                    should be ignored.
                   5179: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5180:                                         if the existing unfound code should
1.423     albertel 5181:                                         be used as is
                   5182:                           - 'answer'
                   5183:                                'response' - new answer or 'none' if blank
                   5184:                                'question' - the bubble line to change
                   5185: 
                   5186:   Returns:
                   5187:     $line - the modified scanline
                   5188: 
                   5189:   Side effects: 
                   5190:     $scan_data - may be updated
                   5191: 
                   5192: =cut
                   5193: 
1.82      albertel 5194: 
1.157     albertel 5195: sub scantron_fixup_scanline {
                   5196:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.479     foxr     5197:     
                   5198:     
1.157     albertel 5199:     if ($field eq 'ID') {
                   5200: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5201: 	    return ($line,1,'New value too large');
1.157     albertel 5202: 	}
                   5203: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5204: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5205: 				     $args->{'newid'});
                   5206: 	}
                   5207: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5208: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5209: 	if ($args->{'newid'}=~/^\s*$/) {
                   5210: 	    &scan_data($scan_data,"$whichline.user",
                   5211: 		       $args->{'username'}.':'.$args->{'domain'});
                   5212: 	}
1.186     albertel 5213:     } elsif ($field eq 'CODE') {
1.192     albertel 5214: 	if ($args->{'CODE_ignore_dup'}) {
                   5215: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5216: 	}
                   5217: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5218: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5219: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5220: 		return ($line,1,'New CODE value too large');
                   5221: 	    }
                   5222: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5223: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5224: 	    }
                   5225: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5226: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5227: 	}
1.157     albertel 5228:     } elsif ($field eq 'answer') {
1.479     foxr     5229: 	&scantron_get_maxbubble(); # Need the bubble counter info.
1.482     foxr     5230: 	my $length =$scantron_config->{'Qlength'};
1.157     albertel 5231: 	my $off=$scantron_config->{'Qoff'};
                   5232: 	my $on=$scantron_config->{'Qon'};
1.479     foxr     5233:         my $question_number = $args->{'question'} -1;
                   5234:         my $first_position  = $first_bubble_line{$question_number};
                   5235: 	my $bubble_count    = $bubble_lines_per_response{$question_number};
                   5236:         my $bubbles_per_line= $$scantron_config{'Qlength'};
1.482     foxr     5237: 	my $answer=${off}x($bubbles_per_line*$bubble_count);
1.479     foxr     5238:         my $final_answer;
                   5239:         if ($$scantron_config{'Qon'} eq 'letter'  ||
                   5240: 	    $$scantron_config{'Qon'} eq 'number') { 
                   5241: 	    $bubbles_per_line = 10;
                   5242: 	}
                   5243: 	if (defined $args->{'response'}) {
                   5244: 	    
                   5245: 	    if ($args->{'response'} eq 'none') {
                   5246: 		&scan_data($scan_data,
                   5247: 			   "$whichline.no_bubble.".$args->{'question'},'1');
1.274     albertel 5248: 	    } else {
1.479     foxr     5249: 		my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
                   5250: 		if ($on eq 'letter') {
                   5251: 		    my @alphabet=('A'..'Z');
                   5252: 		    $answer=$alphabet[$bubble_number];
                   5253: 		} elsif ($on eq 'number') {
1.482     foxr     5254: 		    $answer= $bubble_number+1;
1.479     foxr     5255: 		    if ($answer == 10) { $answer = '0'; }
                   5256: 		} else {
1.482     foxr     5257: 		    substr($answer,$bubble_number+$bubble_line*$bubbles_per_line,1)=$on;
                   5258: 		    $final_answer = $answer;
1.479     foxr     5259: 		}
                   5260: 		&scan_data($scan_data,
                   5261: 			   "$whichline.no_bubble.".$args->{'question'},undef,'1');
1.482     foxr     5262: 		
                   5263: 		# Positional notation already has the right final answer length..
                   5264: 
                   5265: 		if (($on eq 'letter') || ($on eq 'number')) {
                   5266: 		    for (my $l = 0; $l < $bubble_count; $l++) {
                   5267: 			if ($l eq $bubble_line) {
                   5268: 			    $final_answer .= $answer;
                   5269: 			} else {
                   5270: 			    $final_answer .= ' ';
                   5271: 			}
1.479     foxr     5272: 		    }
                   5273: 		}
1.274     albertel 5274: 	    }
1.479     foxr     5275: 	    # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5276: 	    #substr($line,$where-1,$length)=$answer;
                   5277: 	    substr($line, 
                   5278: 		   $scantron_config->{'Qstart'}+$first_position-1,
1.482     foxr     5279: 		   $bubbles_per_line*$length) = $final_answer;
1.157     albertel 5280: 	}
                   5281:     }
                   5282:     return $line;
                   5283: }
1.423     albertel 5284: 
                   5285: =pod
                   5286: 
                   5287: =item scan_data
                   5288: 
                   5289:     Edit or look up  an item in the scan_data hash.
                   5290: 
                   5291:   Arguments:
                   5292:     $scan_data  - The hash (see scantron_getfile)
                   5293:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5294:                   scantronfilename_key).
1.423     albertel 5295:     $data        - New value of the hash entry.
                   5296:     $delete      - If true, the entry is removed from the hash.
                   5297: 
                   5298:   Returns:
                   5299:     The new value of the hash table field (undefined if deleted).
                   5300: 
                   5301: =cut
                   5302: 
                   5303: 
1.157     albertel 5304: sub scan_data {
                   5305:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5306:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5307:     if (defined($value)) {
                   5308: 	$scan_data->{$filename.'_'.$key} = $value;
                   5309:     }
                   5310:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5311:     return $scan_data->{$filename.'_'.$key};
                   5312: }
1.423     albertel 5313: 
                   5314: =pod 
                   5315: 
                   5316: =item scantron_parse_scanline
                   5317: 
                   5318:   Decodes a scanline from the selected scantron file
                   5319: 
                   5320:  Arguments:
                   5321:     line             - The text of the scantron file line to process
                   5322:     whichline        - Line number
                   5323:     scantron_config  - Hash describing the format of the scantron lines.
                   5324:     scan_data        - Hash of extra information about the scanline
                   5325:                        (see scantron_getfile for more information)
                   5326:     just_header      - True if should not process question answers but only
                   5327:                        the stuff to the left of the answers.
                   5328:  Returns:
                   5329:    Hash containing the result of parsing the scanline
                   5330: 
                   5331:    Keys are all proceeded by the string 'scantron.'
                   5332: 
                   5333:        CODE    - the CODE in use for this scanline
                   5334:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5335:                  by the operator
                   5336:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5337:                             CODEs were selected, but the usage has been
                   5338:                             forced by the operator
                   5339:        ID  - student ID
                   5340:        PaperID - if used, the ID number printed on the sheet when the 
                   5341:                  paper was scanned
                   5342:        FirstName - first name from the sheet
                   5343:        LastName  - last name from the sheet
                   5344: 
                   5345:      if just_header was not true these key may also exist
                   5346: 
1.447     foxr     5347:        missingerror - a list of bubble ranges that are considered to be answers
                   5348:                       to a single question that don't have any bubbles filled in.
                   5349:                       Of the form questionnumber:firstbubblenumber:count.
                   5350:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5351:                       to a single question that have more than one bubble filled in.
                   5352:                       Of the form questionnumber::firstbubblenumber:count
                   5353:    
                   5354:                 In the above, count is the number of bubble responses in the
                   5355:                 input line needed to represent the possible answers to the question.
                   5356:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5357:                 per line would have count = 2.
                   5358: 
1.423     albertel 5359:        maxquest     - the number of the last bubble line that was parsed
                   5360: 
                   5361:        (<number> starts at 1)
                   5362:        <number>.answer - zero or more letters representing the selected
                   5363:                          letters from the scanline for the bubble line 
                   5364:                          <number>.
                   5365:                          if blank there was either no bubble or there where
                   5366:                          multiple bubbles, (consult the keys missingerror and
                   5367:                          doubleerror if this is an error condition)
                   5368: 
                   5369: =cut
                   5370: 
1.82      albertel 5371: sub scantron_parse_scanline {
1.423     albertel 5372:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5373: 
1.82      albertel 5374:     my %record;
1.422     foxr     5375:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5376:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5377:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5378: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5379: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5380: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5381: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5382: 	    $record{'scantron.CODE'}=substr($data,
                   5383: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5384: 					    $$scantron_config{'CODElength'});
1.191     albertel 5385: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5386: 		$record{'scantron.useCODE'}=1;
                   5387: 	    }
1.192     albertel 5388: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5389: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5390: 	    }
1.82      albertel 5391: 	} else {
                   5392: 	    #FIXME interpret first N questions
                   5393: 	}
                   5394:     }
1.83      albertel 5395:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5396: 				  $$scantron_config{'IDlength'});
1.157     albertel 5397:     $record{'scantron.PaperID'}=
                   5398: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5399: 	       $$scantron_config{'PaperIDlength'});
                   5400:     $record{'scantron.FirstName'}=
                   5401: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5402: 	       $$scantron_config{'FirstNamelength'});
                   5403:     $record{'scantron.LastName'}=
                   5404: 	substr($data,$$scantron_config{'LastName'}-1,
                   5405: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5406:     if ($just_header) { return \%record; }
1.194     albertel 5407: 
1.82      albertel 5408:     my @alphabet=('A'..'Z');
                   5409:     my $questnum=0;
1.447     foxr     5410:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5411: 
1.470     foxr     5412:     chomp($questions);		# Get rid of any trailing \n.
                   5413:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5414:     while (length($questions)) {
1.447     foxr     5415: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5416: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5417: 
                   5418: 
                   5419: 
1.82      albertel 5420: 	$questnum++;
1.447     foxr     5421: 	my $currentquest = substr($questions,0,$answer_length);
                   5422: 	$questions       = substr($questions,0,$answer_length)='';
                   5423: 	if (length($currentquest) < $answer_length) { next; }
                   5424: 
                   5425: 	# Qon letter implies for each slot in currentquest we have:
                   5426: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5427:         #    about anything else (esp. a value of Qoff for missing
                   5428: 	#    bubbles.
                   5429: 
                   5430: 
1.239     albertel 5431: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5432: 
                   5433: 	    if ($currentquest =~ /\?/
                   5434: 		|| $currentquest =~ /\*/
                   5435: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5436: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5437: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5438: 		    my $bubble = substr($currentquest, $ans, 1);
                   5439: 		    if ($bubble =~ /[A-Z]/ ) {
                   5440: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5441: 		    } else {
                   5442: 			$record{"scantron.$ansnum.answer"}='';
                   5443: 		    }
1.447     foxr     5444: 		    $ansnum++;
                   5445: 		}
                   5446: 
1.389     albertel 5447: 	    } elsif (!defined($currentquest)
1.447     foxr     5448: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5449: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5450: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5451: 		    $record{"scantron.$ansnum.answer"}='';
                   5452: 		    $ansnum++;
                   5453: 
                   5454: 		}
1.239     albertel 5455: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5456: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5457: 		   #  $ansnum += $answers_needed;
1.239     albertel 5458: 		}
                   5459: 	    } else {
1.447     foxr     5460: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5461: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5462: 		    $ansnum++;
                   5463: 		}
1.239     albertel 5464: 	    }
1.447     foxr     5465: 
                   5466: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5467: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5468:         #    and *? for double bubbles on a line.
                   5469: 	#    these answers are also stored as letters.
                   5470: 
1.239     albertel 5471: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5472: 	    if ($currentquest =~ /\?/
                   5473: 		|| $currentquest =~ /\*/
                   5474: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5475: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5476: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5477: 		    my $bubble = substr($currentquest, $ans, 1);
                   5478: 		    if ($bubble =~ /\d/) {
                   5479: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5480: 		    } else {
1.461     foxr     5481: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5482: 		    }
1.447     foxr     5483: 		    $ansnum++;
                   5484: 		}
                   5485: 
1.389     albertel 5486: 	    } elsif (!defined($currentquest)
1.447     foxr     5487: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5488: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5489: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5490: 		    $record{"scantron.$ansnum.answer"}='';
                   5491: 		    $ansnum++;
                   5492: 
                   5493: 		}
1.239     albertel 5494: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5495: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5496: 		    $ansnum += $answers_needed;
1.239     albertel 5497: 		}
1.447     foxr     5498: 
1.239     albertel 5499: 	    } else {
1.447     foxr     5500: 		$currentquest = &digits_to_letters($currentquest);
                   5501: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5502: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5503: 		    $ansnum++;
1.371     albertel 5504: 		}
1.239     albertel 5505: 	    }
1.82      albertel 5506: 	} else {
1.447     foxr     5507: 
                   5508: 	    # Otherwise there's a positional notation;
                   5509: 	    # each bubble line requires Qlength items, and there are filled in
                   5510: 	    # bubbles for each case where there 'Qon' characters.
                   5511: 	    #
                   5512: 
1.239     albertel 5513: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5514: 
                   5515: 	    # If the split only  giveas us one element.. the full length of the
                   5516: 	    # answser string, no bubbles are filled in:
                   5517: 
                   5518: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5519: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5520: 		    $record{"scantron.$ansnum.answer"}='';
                   5521: 		    $ansnum++;
                   5522: 
                   5523: 		}
1.239     albertel 5524: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5525: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5526: 		}
1.482     foxr     5527: 		
                   5528: 		#  If the bubble is not the last position, there will be
                   5529: 		# 2 elements.  If it is the last position, there will be 1 element.
                   5530: 
                   5531: 	    } elsif (scalar(@array) le 2) {
1.447     foxr     5532: 
1.459     foxr     5533: 		my $location      = length($array[0]);
1.483     foxr     5534: 		my $line_num      = int($location / $$scantron_config{'Qlength'});
1.447     foxr     5535: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
1.483     foxr     5536: 		
1.447     foxr     5537: 
                   5538: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5539: 		    if ($ans eq $line_num) {
                   5540: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5541: 		    } else {
                   5542: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5543: 		    }
                   5544: 		    $ansnum++;
                   5545: 		}
1.239     albertel 5546: 	    }
1.447     foxr     5547: 	    #  If there's more than one instance of a bubble character
                   5548: 	    #  That's a double bubble; with positional notation we can
                   5549: 	    #  record all the bubbles filled in as well as the 
                   5550: 	    #  fact this response consists of multiple bubbles.
                   5551: 	    #
                   5552: 	    else {
1.239     albertel 5553: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5554: 
                   5555: 		my $first_answer = $ansnum;
                   5556: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5557: 		    my $item = $first_answer+$ans;
                   5558: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5559: 		}
                   5560: 
1.239     albertel 5561: 		my @ans=@array;
1.462     foxr     5562: 		my $i=0;
                   5563: 		my $increment = 0;
1.239     albertel 5564: 		while ($#ans) {
1.462     foxr     5565: 		    $i+=length($ans[0]) + $increment;
                   5566: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5567: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5568: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5569: 		    shift(@ans);
1.462     foxr     5570: 		    $increment = 1;
1.239     albertel 5571: 		}
1.462     foxr     5572: 		$ansnum += $answers_needed;
1.239     albertel 5573: 	    }
1.82      albertel 5574: 	}
                   5575:     }
1.83      albertel 5576:     $record{'scantron.maxquest'}=$questnum;
                   5577:     return \%record;
1.82      albertel 5578: }
                   5579: 
1.423     albertel 5580: =pod
                   5581: 
                   5582: =item scantron_add_delay
                   5583: 
                   5584:    Adds an error message that occurred during the grading phase to a
                   5585:    queue of messages to be shown after grading pass is complete
                   5586: 
                   5587:  Arguments:
1.424     albertel 5588:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5589:    $scanline    - the scanline that caused the error
                   5590:    $errormesage - the error message
                   5591:    $errorcode   - a numeric code for the error
                   5592: 
                   5593:  Side Effects:
1.424     albertel 5594:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5595: 
                   5596: =cut
                   5597: 
1.82      albertel 5598: sub scantron_add_delay {
1.140     albertel 5599:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5600:     push(@$delayqueue,
                   5601: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5602: 	  'ecode' => $errorcode }
                   5603: 	 );
1.82      albertel 5604: }
                   5605: 
1.423     albertel 5606: =pod
                   5607: 
                   5608: =item scantron_find_student
                   5609: 
1.424     albertel 5610:    Finds the username for the current scanline
                   5611: 
                   5612:   Arguments:
                   5613:    $scantron_record - hash result from scantron_parse_scanline
                   5614:    $scan_data       - hash of correction information 
                   5615:                       (see &scantron_getfile() form more information)
                   5616:    $idmap           - hash from &username_to_idmap()
                   5617:    $line            - number of current scanline
                   5618:  
                   5619:   Returns:
                   5620:    Either 'username:domain' or undef if unknown
                   5621: 
1.423     albertel 5622: =cut
                   5623: 
1.82      albertel 5624: sub scantron_find_student {
1.157     albertel 5625:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5626:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5627:     if ($scanID =~ /^\s*$/) {
                   5628:  	return &scan_data($scan_data,"$line.user");
                   5629:     }
1.83      albertel 5630:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5631:  	if (lc($id) eq lc($scanID)) {
                   5632:  	    return $$idmap{$id};
                   5633:  	}
1.83      albertel 5634:     }
                   5635:     return undef;
                   5636: }
                   5637: 
1.423     albertel 5638: =pod
                   5639: 
                   5640: =item scantron_filter
                   5641: 
1.424     albertel 5642:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5643:    hidden resources was selected
                   5644: 
1.423     albertel 5645: =cut
                   5646: 
1.83      albertel 5647: sub scantron_filter {
                   5648:     my ($curres)=@_;
1.331     albertel 5649: 
                   5650:     if (ref($curres) && $curres->is_problem()) {
                   5651: 	# if the user has asked to not have either hidden
                   5652: 	# or 'randomout' controlled resources to be graded
                   5653: 	# don't include them
                   5654: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5655: 	    && $curres->randomout) {
                   5656: 	    return 0;
                   5657: 	}
1.83      albertel 5658: 	return 1;
                   5659:     }
                   5660:     return 0;
1.82      albertel 5661: }
                   5662: 
1.423     albertel 5663: =pod
                   5664: 
                   5665: =item scantron_process_corrections
                   5666: 
1.424     albertel 5667:    Gets correction information out of submitted form data and corrects
                   5668:    the scanline
                   5669: 
1.423     albertel 5670: =cut
                   5671: 
1.157     albertel 5672: sub scantron_process_corrections {
                   5673:     my ($r) = @_;
1.257     albertel 5674:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5675:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5676:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5677:     my $which=$env{'form.scantron_line'};
1.200     albertel 5678:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5679:     my ($skip,$err,$errmsg);
1.257     albertel 5680:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5681: 	$skip=1;
1.257     albertel 5682:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5683: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5684: 	    $env{'form.scantron_domain'};
1.157     albertel 5685: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5686: 	($line,$err,$errmsg)=
                   5687: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5688: 				     'ID',{'newid'=>$newid,
1.257     albertel 5689: 				    'username'=>$env{'form.scantron_username'},
                   5690: 				    'domain'=>$env{'form.scantron_domain'}});
                   5691:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5692: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5693: 	my $newCODE;
1.192     albertel 5694: 	my %args;
1.190     albertel 5695: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5696: 	    $newCODE='use_unfound';
1.190     albertel 5697: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5698: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5699: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5700: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5701: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5702: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5703: 	}
1.257     albertel 5704: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5705: 	    $args{'CODE_ignore_dup'}=1;
                   5706: 	}
                   5707: 	$args{'CODE'}=$newCODE;
1.186     albertel 5708: 	($line,$err,$errmsg)=
                   5709: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5710: 				     'CODE',\%args);
1.257     albertel 5711:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5712: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5713: 	    ($line,$err,$errmsg)=
                   5714: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5715: 					 $which,'answer',
                   5716: 					 { 'question'=>$question,
1.257     albertel 5717: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5718: 	    if ($err) { last; }
                   5719: 	}
                   5720:     }
                   5721:     if ($err) {
1.398     albertel 5722: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5723:     } else {
1.200     albertel 5724: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5725: 	&scantron_putfile($scanlines,$scan_data);
                   5726:     }
                   5727: }
                   5728: 
1.423     albertel 5729: =pod
                   5730: 
                   5731: =item reset_skipping_status
                   5732: 
1.424     albertel 5733:    Forgets the current set of remember skipped scanlines (and thus
                   5734:    reverts back to considering all lines in the
                   5735:    scantron_skipped_<filename> file)
                   5736: 
1.423     albertel 5737: =cut
                   5738: 
1.200     albertel 5739: sub reset_skipping_status {
                   5740:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5741:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5742:     &scantron_putfile(undef,$scan_data);
                   5743: }
                   5744: 
1.423     albertel 5745: =pod
                   5746: 
                   5747: =item start_skipping
                   5748: 
1.424     albertel 5749:    Marks a scanline to be skipped. 
                   5750: 
1.423     albertel 5751: =cut
                   5752: 
1.376     albertel 5753: sub start_skipping {
1.200     albertel 5754:     my ($scan_data,$i)=@_;
                   5755:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5756:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5757: 	$remembered{$i}=2;
                   5758:     } else {
                   5759: 	$remembered{$i}=1;
                   5760:     }
1.200     albertel 5761:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5762: }
                   5763: 
1.423     albertel 5764: =pod
                   5765: 
                   5766: =item should_be_skipped
                   5767: 
1.424     albertel 5768:    Checks whether a scanline should be skipped.
                   5769: 
1.423     albertel 5770: =cut
                   5771: 
1.200     albertel 5772: sub should_be_skipped {
1.376     albertel 5773:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5774:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5775: 	# not redoing old skips
1.376     albertel 5776: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5777: 	return 0;
                   5778:     }
                   5779:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5780: 
                   5781:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5782: 	return 0;
                   5783:     }
1.200     albertel 5784:     return 1;
                   5785: }
                   5786: 
1.423     albertel 5787: =pod
                   5788: 
                   5789: =item remember_current_skipped
                   5790: 
1.424     albertel 5791:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5792:    file and remembers them into scan_data for later use.
                   5793: 
1.423     albertel 5794: =cut
                   5795: 
1.200     albertel 5796: sub remember_current_skipped {
                   5797:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5798:     my %to_remember;
                   5799:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5800: 	if ($scanlines->{'skipped'}[$i]) {
                   5801: 	    $to_remember{$i}=1;
                   5802: 	}
                   5803:     }
1.376     albertel 5804: 
1.200     albertel 5805:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5806:     &scantron_putfile(undef,$scan_data);
                   5807: }
                   5808: 
1.423     albertel 5809: =pod
                   5810: 
                   5811: =item check_for_error
                   5812: 
1.424     albertel 5813:     Checks if there was an error when attempting to remove a specific
                   5814:     scantron_.. bubble sheet data file. Prints out an error if
                   5815:     something went wrong.
                   5816: 
1.423     albertel 5817: =cut
                   5818: 
1.200     albertel 5819: sub check_for_error {
                   5820:     my ($r,$result)=@_;
                   5821:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5822: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5823:     }
                   5824: }
1.157     albertel 5825: 
1.423     albertel 5826: =pod
                   5827: 
                   5828: =item scantron_warning_screen
                   5829: 
1.424     albertel 5830:    Interstitial screen to make sure the operator has selected the
                   5831:    correct options before we start the validation phase.
                   5832: 
1.423     albertel 5833: =cut
                   5834: 
1.203     albertel 5835: sub scantron_warning_screen {
                   5836:     my ($button_text)=@_;
1.257     albertel 5837:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5838:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5839:     my $CODElist;
1.284     albertel 5840:     if ($scantron_config{'CODElocation'} &&
                   5841: 	$scantron_config{'CODEstart'} &&
                   5842: 	$scantron_config{'CODElength'}) {
                   5843: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5844: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5845: 	$CODElist=
                   5846: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5847: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5848:     }
1.203     albertel 5849:     return (<<STUFF);
                   5850: <p>
1.398     albertel 5851: <span class="LC_warning">Please double check the information
                   5852:                  below before clicking on '$button_text'</span>
1.203     albertel 5853: </p>
                   5854: <table>
1.284     albertel 5855: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5856: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5857: $CODElist
1.203     albertel 5858: </table>
                   5859: <br />
                   5860: <p> If this information is correct, please click on '$button_text'.</p>
                   5861: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5862: 
                   5863: <br />
                   5864: STUFF
                   5865: }
                   5866: 
1.423     albertel 5867: =pod
                   5868: 
                   5869: =item scantron_do_warning
                   5870: 
1.424     albertel 5871:    Check if the operator has picked something for all required
                   5872:    fields. Error out if something is missing.
                   5873: 
1.423     albertel 5874: =cut
                   5875: 
1.203     albertel 5876: sub scantron_do_warning {
                   5877:     my ($r)=@_;
1.324     albertel 5878:     my ($symb)=&get_symb($r);
1.203     albertel 5879:     if (!$symb) {return '';}
1.324     albertel 5880:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5881:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5882:     if ( $env{'form.selectpage'} eq '' ||
                   5883: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5884: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5885: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5886: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5887: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5888: 	} 
1.257     albertel 5889: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5890: 	    $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 5891: 	} 
1.257     albertel 5892: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5893: 	    $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 5894: 	} 
                   5895:     } else {
1.265     www      5896: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5897: 	$r->print(<<STUFF);
1.203     albertel 5898: $warning
1.265     www      5899: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5900: <input type="hidden" name="command" value="scantron_validate" />
                   5901: STUFF
1.237     albertel 5902:     }
1.352     albertel 5903:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5904:     return '';
                   5905: }
                   5906: 
1.423     albertel 5907: =pod
                   5908: 
                   5909: =item scantron_form_start
                   5910: 
1.424     albertel 5911:     html hidden input for remembering all selected grading options
                   5912: 
1.423     albertel 5913: =cut
                   5914: 
1.203     albertel 5915: sub scantron_form_start {
                   5916:     my ($max_bubble)=@_;
                   5917:     my $result= <<SCANTRONFORM;
                   5918: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5919:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5920:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5921:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5922:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5923:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5924:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5925:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5926:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5927:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5928: SCANTRONFORM
1.447     foxr     5929: 
                   5930:   my $line = 0;
                   5931:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5932:        my $chunk =
                   5933: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5934:        $chunk .=
                   5935: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5936:        $result .= $chunk;
                   5937:        $line++;
                   5938:    }
1.203     albertel 5939:     return $result;
                   5940: }
                   5941: 
1.423     albertel 5942: =pod
                   5943: 
                   5944: =item scantron_validate_file
                   5945: 
1.424     albertel 5946:     Dispatch routine for doing validation of a bubble sheet data file.
                   5947: 
                   5948:     Also processes any necessary information resets that need to
                   5949:     occur before validation begins (ignore previous corrections,
                   5950:     restarting the skipped records processing)
                   5951: 
1.423     albertel 5952: =cut
                   5953: 
1.157     albertel 5954: sub scantron_validate_file {
                   5955:     my ($r) = @_;
1.324     albertel 5956:     my ($symb)=&get_symb($r);
1.157     albertel 5957:     if (!$symb) {return '';}
1.324     albertel 5958:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5959:     
                   5960:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5961:     # them when doing the corrections reset
1.257     albertel 5962:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5963: 	&reset_skipping_status();
                   5964:     }
1.257     albertel 5965:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5966: 	&remember_current_skipped();
1.257     albertel 5967: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5968:     }
                   5969: 
1.257     albertel 5970:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5971: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5972: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5973: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5974: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5975:     }
1.200     albertel 5976: 
1.257     albertel 5977:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5978: 	&scantron_process_corrections($r);
                   5979:     }
1.424     albertel 5980:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5981:     #get the student pick code ready
                   5982:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5983:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5984:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5985:     $r->print($result);
                   5986:     
1.334     albertel 5987:     my @validate_phases=( 'sequence',
                   5988: 			  'ID',
1.157     albertel 5989: 			  'CODE',
                   5990: 			  'doublebubble',
                   5991: 			  'missingbubbles');
1.257     albertel 5992:     if (!$env{'form.validatepass'}) {
                   5993: 	$env{'form.validatepass'} = 0;
1.157     albertel 5994:     }
1.257     albertel 5995:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5996: 
1.448     foxr     5997: 
1.157     albertel 5998:     my $stop=0;
                   5999:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   6000: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   6001: 	$r->rflush();
                   6002: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   6003: 	{
                   6004: 	    no strict 'refs';
                   6005: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   6006: 	}
                   6007:     }
                   6008:     if (!$stop) {
1.203     albertel 6009: 	my $warning=&scantron_warning_screen('Start Grading');
                   6010: 	$r->print(<<STUFF);
                   6011: Validation process complete.<br />
                   6012: $warning
                   6013: <input type="submit" name="submit" value="Start Grading" />
                   6014: <input type="hidden" name="command" value="scantron_process" />
                   6015: STUFF
                   6016: 
1.157     albertel 6017:     } else {
                   6018: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   6019: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   6020:     }
                   6021:     if ($stop) {
1.334     albertel 6022: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   6023: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   6024: 	    $r->print(' this error <br />');
                   6025: 
                   6026: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   6027: 	} else {
                   6028: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   6029: 	    $r->print(' using corrected info <br />');
                   6030: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   6031: 	    $r->print(" this scanline saving it for later.");
                   6032: 	}
1.157     albertel 6033:     }
1.352     albertel 6034:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 6035:     return '';
                   6036: }
                   6037: 
1.423     albertel 6038: 
                   6039: =pod
                   6040: 
                   6041: =item scantron_remove_file
                   6042: 
1.424     albertel 6043:    Removes the requested bubble sheet data file, makes sure that
                   6044:    scantron_original_<filename> is never removed
                   6045: 
                   6046: 
1.423     albertel 6047: =cut
                   6048: 
1.200     albertel 6049: sub scantron_remove_file {
1.192     albertel 6050:     my ($which)=@_;
1.257     albertel 6051:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6052:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6053:     my $file='scantron_';
1.200     albertel 6054:     if ($which eq 'corrected' || $which eq 'skipped') {
                   6055: 	$file.=$which.'_';
1.192     albertel 6056:     } else {
                   6057: 	return 'refused';
                   6058:     }
1.257     albertel 6059:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 6060:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   6061: }
                   6062: 
1.423     albertel 6063: 
                   6064: =pod
                   6065: 
                   6066: =item scantron_remove_scan_data
                   6067: 
1.424     albertel 6068:    Removes all scan_data correction for the requested bubble sheet
                   6069:    data file.  (In the case that both the are doing skipped records we need
                   6070:    to remember the old skipped lines for the time being so that element
                   6071:    persists for a while.)
                   6072: 
1.423     albertel 6073: =cut
                   6074: 
1.200     albertel 6075: sub scantron_remove_scan_data {
1.257     albertel 6076:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6077:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 6078:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   6079:     my @todelete;
1.257     albertel 6080:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 6081:     foreach my $key (@keys) {
                   6082: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 6083: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 6084: 		$key=~/remember_skipping/) {
                   6085: 		next;
                   6086: 	    }
1.192     albertel 6087: 	    push(@todelete,$key);
                   6088: 	}
                   6089:     }
1.200     albertel 6090:     my $result;
1.192     albertel 6091:     if (@todelete) {
1.200     albertel 6092: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 6093:     }
                   6094:     return $result;
                   6095: }
                   6096: 
1.423     albertel 6097: 
                   6098: =pod
                   6099: 
                   6100: =item scantron_getfile
                   6101: 
1.424     albertel 6102:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6103:     the scan_data hash
                   6104:   
                   6105:   Arguments:
                   6106:     None
                   6107: 
                   6108:   Returns:
                   6109:     2 hash references
                   6110: 
                   6111:      - first one has 
                   6112:          orig      -
                   6113:          corrected -
                   6114:          skipped   -  each of which points to an array ref of the specified
                   6115:                       file broken up into individual lines
                   6116:          count     - number of scanlines
                   6117:  
                   6118:      - second is the scan_data hash possible keys are
1.425     albertel 6119:        ($number refers to scanline numbered $number and thus the key affects
                   6120:         only that scanline
                   6121:         $bubline refers to the specific bubble line element and the aspects
                   6122:         refers to that specific bubble line element)
                   6123: 
                   6124:        $number.user - username:domain to use
                   6125:        $number.CODE_ignore_dup 
                   6126:                     - ignore the duplicate CODE error 
                   6127:        $number.useCODE
                   6128:                     - use the CODE in the scanline as is
                   6129:        $number.no_bubble.$bubline
                   6130:                     - it is valid that there is no bubbled in bubble
                   6131:                       at $number $bubline
                   6132:        remember_skipping
                   6133:                     - a frozen hash containing keys of $number and values
                   6134:                       of either 
                   6135:                         1 - we are on a 'do skipped records pass' and plan
                   6136:                             on processing this line
                   6137:                         2 - we are on a 'do skipped records pass' and this
                   6138:                             scanline has been marked to skip yet again
1.424     albertel 6139: 
1.423     albertel 6140: =cut
                   6141: 
1.157     albertel 6142: sub scantron_getfile {
1.200     albertel 6143:     #FIXME really would prefer a scantron directory
1.257     albertel 6144:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6145:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6146:     my $lines;
                   6147:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6148: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6149:     my %scanlines;
                   6150:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6151:     my $temp=$scanlines{'orig'};
                   6152:     $scanlines{'count'}=$#$temp;
                   6153: 
                   6154:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6155: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6156:     if ($lines eq '-1') {
                   6157: 	$scanlines{'corrected'}=[];
                   6158:     } else {
                   6159: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6160:     }
                   6161:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6162: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6163:     if ($lines eq '-1') {
                   6164: 	$scanlines{'skipped'}=[];
                   6165:     } else {
                   6166: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6167:     }
1.175     albertel 6168:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6169:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6170:     my %scan_data = @tmp;
                   6171:     return (\%scanlines,\%scan_data);
                   6172: }
                   6173: 
1.423     albertel 6174: =pod
                   6175: 
                   6176: =item lonnet_putfile
                   6177: 
1.424     albertel 6178:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6179: 
                   6180:  Arguments:
                   6181:    $contents - data to store
                   6182:    $filename - filename to store $contents into
                   6183: 
                   6184:  Returns:
                   6185:    result value from &Apache::lonnet::finishuserfileupload
                   6186: 
1.423     albertel 6187: =cut
                   6188: 
1.157     albertel 6189: sub lonnet_putfile {
                   6190:     my ($contents,$filename)=@_;
1.257     albertel 6191:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6192:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6193:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6194:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6195: 
                   6196: }
                   6197: 
1.423     albertel 6198: =pod
                   6199: 
                   6200: =item scantron_putfile
                   6201: 
1.424     albertel 6202:     Stores the current version of the bubble sheet data files, and the
                   6203:     scan_data hash. (Does not modify the original version only the
                   6204:     corrected and skipped versions.
                   6205: 
                   6206:  Arguments:
                   6207:     $scanlines - hash ref that looks like the first return value from
                   6208:                  &scantron_getfile()
                   6209:     $scan_data - hash ref that looks like the second return value from
                   6210:                  &scantron_getfile()
                   6211: 
1.423     albertel 6212: =cut
                   6213: 
1.157     albertel 6214: sub scantron_putfile {
                   6215:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6216:     #FIXME really would prefer a scantron directory
1.257     albertel 6217:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6218:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6219:     if ($scanlines) {
                   6220: 	my $prefix='scantron_';
1.157     albertel 6221: # no need to update orig, shouldn't change
                   6222: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6223: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6224: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6225: 			$prefix.'corrected_'.
1.257     albertel 6226: 			$env{'form.scantron_selectfile'});
1.200     albertel 6227: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6228: 			$prefix.'skipped_'.
1.257     albertel 6229: 			$env{'form.scantron_selectfile'});
1.200     albertel 6230:     }
1.175     albertel 6231:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6232: }
                   6233: 
1.423     albertel 6234: =pod
                   6235: 
                   6236: =item scantron_get_line
                   6237: 
1.424     albertel 6238:    Returns the correct version of the scanline
                   6239: 
                   6240:  Arguments:
                   6241:     $scanlines - hash ref that looks like the first return value from
                   6242:                  &scantron_getfile()
                   6243:     $scan_data - hash ref that looks like the second return value from
                   6244:                  &scantron_getfile()
                   6245:     $i         - number of the requested line (starts at 0)
                   6246: 
                   6247:  Returns:
                   6248:    A scanline, (either the original or the corrected one if it
                   6249:    exists), or undef if the requested scanline should be
                   6250:    skipped. (Either because it's an skipped scanline, or it's an
                   6251:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6252:    pass.
                   6253: 
1.423     albertel 6254: =cut
                   6255: 
1.157     albertel 6256: sub scantron_get_line {
1.200     albertel 6257:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6258:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6259:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6260:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6261:     return $scanlines->{'orig'}[$i]; 
                   6262: }
                   6263: 
1.423     albertel 6264: =pod
                   6265: 
                   6266: =item scantron_todo_count
                   6267: 
1.424     albertel 6268:     Counts the number of scanlines that need processing.
                   6269: 
                   6270:  Arguments:
                   6271:     $scanlines - hash ref that looks like the first return value from
                   6272:                  &scantron_getfile()
                   6273:     $scan_data - hash ref that looks like the second return value from
                   6274:                  &scantron_getfile()
                   6275: 
                   6276:  Returns:
                   6277:     $count - number of scanlines to process
                   6278: 
1.423     albertel 6279: =cut
                   6280: 
1.200     albertel 6281: sub get_todo_count {
                   6282:     my ($scanlines,$scan_data)=@_;
                   6283:     my $count=0;
                   6284:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6285: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6286: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6287: 	$count++;
                   6288:     }
                   6289:     return $count;
                   6290: }
                   6291: 
1.423     albertel 6292: =pod
                   6293: 
                   6294: =item scantron_put_line
                   6295: 
1.424     albertel 6296:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6297:     data file.
                   6298: 
                   6299:  Arguments:
                   6300:     $scanlines - hash ref that looks like the first return value from
                   6301:                  &scantron_getfile()
                   6302:     $scan_data - hash ref that looks like the second return value from
                   6303:                  &scantron_getfile()
                   6304:     $i         - line number to update
                   6305:     $newline   - contents of the updated scanline
                   6306:     $skip      - if true make the line for skipping and update the
                   6307:                  'skipped' file
                   6308: 
1.423     albertel 6309: =cut
                   6310: 
1.157     albertel 6311: sub scantron_put_line {
1.200     albertel 6312:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6313:     if ($skip) {
                   6314: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6315: 	&start_skipping($scan_data,$i);
1.157     albertel 6316: 	return;
                   6317:     }
                   6318:     $scanlines->{'corrected'}[$i]=$newline;
                   6319: }
                   6320: 
1.423     albertel 6321: =pod
                   6322: 
                   6323: =item scantron_clear_skip
                   6324: 
1.424     albertel 6325:    Remove a line from the 'skipped' file
                   6326: 
                   6327:  Arguments:
                   6328:     $scanlines - hash ref that looks like the first return value from
                   6329:                  &scantron_getfile()
                   6330:     $scan_data - hash ref that looks like the second return value from
                   6331:                  &scantron_getfile()
                   6332:     $i         - line number to update
                   6333: 
1.423     albertel 6334: =cut
                   6335: 
1.376     albertel 6336: sub scantron_clear_skip {
                   6337:     my ($scanlines,$scan_data,$i)=@_;
                   6338:     if (exists($scanlines->{'skipped'}[$i])) {
                   6339: 	undef($scanlines->{'skipped'}[$i]);
                   6340: 	return 1;
                   6341:     }
                   6342:     return 0;
                   6343: }
                   6344: 
1.423     albertel 6345: =pod
                   6346: 
                   6347: =item scantron_filter_not_exam
                   6348: 
1.424     albertel 6349:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6350:    filter out resources that are not marked as 'exam' mode
                   6351: 
1.423     albertel 6352: =cut
                   6353: 
1.334     albertel 6354: sub scantron_filter_not_exam {
                   6355:     my ($curres)=@_;
                   6356:     
                   6357:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6358: 	# if the user has asked to not have either hidden
                   6359: 	# or 'randomout' controlled resources to be graded
                   6360: 	# don't include them
                   6361: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6362: 	    && $curres->randomout) {
                   6363: 	    return 0;
                   6364: 	}
                   6365: 	return 1;
                   6366:     }
                   6367:     return 0;
                   6368: }
                   6369: 
1.423     albertel 6370: =pod
                   6371: 
                   6372: =item scantron_validate_sequence
                   6373: 
1.424     albertel 6374:     Validates the selected sequence, checking for resource that are
                   6375:     not set to exam mode.
                   6376: 
1.423     albertel 6377: =cut
                   6378: 
1.334     albertel 6379: sub scantron_validate_sequence {
                   6380:     my ($r,$currentphase) = @_;
                   6381: 
                   6382:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6383:     my (undef,undef,$sequence)=
                   6384: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6385: 
                   6386:     my $map=$navmap->getResourceByUrl($sequence);
                   6387: 
                   6388:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6389:                                     value="ignore" />');
                   6390:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6391: 	my @resources=
                   6392: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6393: 	if (@resources) {
1.357     banghart 6394: 	    $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 6395: 	    return (1,$currentphase);
                   6396: 	}
                   6397:     }
                   6398: 
                   6399:     return (0,$currentphase+1);
                   6400: }
                   6401: 
1.423     albertel 6402: =pod
                   6403: 
                   6404: =item scantron_validate_ID
                   6405: 
1.424     albertel 6406:    Validates all scanlines in the selected file to not have any
                   6407:    invalid or underspecified student IDs
                   6408: 
1.423     albertel 6409: =cut
                   6410: 
1.157     albertel 6411: sub scantron_validate_ID {
                   6412:     my ($r,$currentphase) = @_;
                   6413:     
                   6414:     #get student info
                   6415:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6416:     my %idmap=&username_to_idmap($classlist);
                   6417: 
                   6418:     #get scantron line setup
1.257     albertel 6419:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6420:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6421:     
                   6422:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6423: 
                   6424:     my %found=('ids'=>{},'usernames'=>{});
                   6425:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6426: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6427: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6428: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6429: 						 $scan_data);
                   6430: 	my $id=$$scan_record{'scantron.ID'};
                   6431: 	my $found;
                   6432: 	foreach my $checkid (keys(%idmap)) {
                   6433: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6434: 	}
                   6435: 	if ($found) {
                   6436: 	    my $username=$idmap{$found};
                   6437: 	    if ($found{'ids'}{$found}) {
                   6438: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6439: 					 $line,'duplicateID',$found);
1.194     albertel 6440: 		return(1,$currentphase);
1.157     albertel 6441: 	    } elsif ($found{'usernames'}{$username}) {
                   6442: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6443: 					 $line,'duplicateID',$username);
1.194     albertel 6444: 		return(1,$currentphase);
1.157     albertel 6445: 	    }
1.186     albertel 6446: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6447: 	    $found{'ids'}{$found}++;
                   6448: 	    $found{'usernames'}{$username}++;
                   6449: 	} else {
                   6450: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6451: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6452: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6453: 		    &scantron_get_correction($r,$i,$scan_record,
                   6454: 					     \%scantron_config,
                   6455: 					     $line,'duplicateID',$username);
1.194     albertel 6456: 		    return(1,$currentphase);
1.157     albertel 6457: 		} elsif (!defined($username)) {
                   6458: 		    &scantron_get_correction($r,$i,$scan_record,
                   6459: 					     \%scantron_config,
                   6460: 					     $line,'incorrectID');
1.194     albertel 6461: 		    return(1,$currentphase);
1.157     albertel 6462: 		}
                   6463: 		$found{'usernames'}{$username}++;
                   6464: 	    } else {
                   6465: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6466: 					 $line,'incorrectID');
1.194     albertel 6467: 		return(1,$currentphase);
1.157     albertel 6468: 	    }
                   6469: 	}
                   6470:     }
                   6471: 
                   6472:     return (0,$currentphase+1);
                   6473: }
                   6474: 
1.423     albertel 6475: =pod
                   6476: 
                   6477: =item scantron_get_correction
                   6478: 
1.424     albertel 6479:    Builds the interface screen to interact with the operator to fix a
                   6480:    specific error condition in a specific scanline
                   6481: 
                   6482:  Arguments:
                   6483:     $r           - Apache request object
                   6484:     $i           - number of the current scanline
                   6485:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6486:     $scan_config - hash ref as returned from &get_scantron_config()
                   6487:     $line        - full contents of the current scanline
                   6488:     $error       - error condition, valid values are
                   6489:                    'incorrectCODE', 'duplicateCODE',
                   6490:                    'doublebubble', 'missingbubble',
                   6491:                    'duplicateID', 'incorrectID'
                   6492:     $arg         - extra information needed
                   6493:        For errors:
                   6494:          - duplicateID   - paper number that this studentID was seen before on
                   6495:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6496:                            seen on before
                   6497:          - incorrectCODE - current incorrect CODE 
                   6498:          - doublebubble  - array ref of the bubble lines that have double
                   6499:                            bubble errors
                   6500:          - missingbubble - array ref of the bubble lines that have missing
                   6501:                            bubble errors
                   6502: 
1.423     albertel 6503: =cut
                   6504: 
1.157     albertel 6505: sub scantron_get_correction {
                   6506:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6507: 
1.454     banghart 6508: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6509: #to show both the current line and the previous one and allow skipping
                   6510: #the previous one or the current one
                   6511: 
1.161     albertel 6512:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6513:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6514: 	$r->print(" for PaperID <tt>".
                   6515: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6516:     } else {
                   6517: 	$r->print(" in scanline $i <pre>".
                   6518: 		  $line."</pre> \n");
                   6519:     }
1.242     albertel 6520:     my $message="<p>The ID on the form is  <tt>".
                   6521: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6522: 	"The name on the paper is ".
                   6523: 	$$scan_record{'scantron.LastName'}.",".
                   6524: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6525: 
1.157     albertel 6526:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6527:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6528:     if ($error =~ /ID$/) {
1.186     albertel 6529: 	if ($error eq 'incorrectID') {
1.157     albertel 6530: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6531: 	} elsif ($error eq 'duplicateID') {
                   6532: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6533: 	}
1.242     albertel 6534: 	$r->print($message);
1.157     albertel 6535: 	$r->print("<p>How should I handle this? <br /> \n");
                   6536: 	$r->print("\n<ul><li> ");
                   6537: 	#FIXME it would be nice if this sent back the user ID and
                   6538: 	#could do partial userID matches
                   6539: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6540: 				       'scantron_username','scantron_domain'));
                   6541: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6542: 	$r->print("\n@".
1.257     albertel 6543: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6544: 
                   6545: 	$r->print('</li>');
1.186     albertel 6546:     } elsif ($error =~ /CODE$/) {
                   6547: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6548: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6549: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6550: 	    $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 6551: 	}
1.224     albertel 6552: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6553: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6554: 	$r->print($message);
1.186     albertel 6555: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6556: 	$r->print("\n<br /> ");
1.194     albertel 6557: 	my $i=0;
1.273     albertel 6558: 	if ($error eq 'incorrectCODE' 
                   6559: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6560: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6561: 	    if ($closest > 0) {
                   6562: 		foreach my $testcode (@{$closest}) {
                   6563: 		    my $checked='';
1.401     albertel 6564: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6565: 		    $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' />");
                   6566: 		    $r->print("\n<br />");
                   6567: 		    $i++;
                   6568: 		}
1.194     albertel 6569: 	    }
                   6570: 	}
1.273     albertel 6571: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6572: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6573: 	    $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>");
                   6574: 	    $r->print("\n<br />");
                   6575: 	}
1.194     albertel 6576: 
1.188     albertel 6577: 	$r->print(<<ENDSCRIPT);
                   6578: <script type="text/javascript">
                   6579: function change_radio(field) {
1.190     albertel 6580:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6581:     var i;
                   6582:     for (i=0;i<slct.length;i++) {
                   6583:         if (slct[i].value==field) { slct[i].checked=true; }
                   6584:     }
                   6585: }
                   6586: </script>
                   6587: ENDSCRIPT
1.187     albertel 6588: 	my $href="/adm/pickcode?".
1.359     www      6589: 	   "form=".&escape("scantronupload").
                   6590: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6591: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6592: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6593: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6594: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6595: 	    $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')\" />");
                   6596: 	    $r->print("\n<br />");
                   6597: 	}
1.272     albertel 6598: 	$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 6599: 	$r->print("\n<br /><br />");
1.157     albertel 6600:     } elsif ($error eq 'doublebubble') {
                   6601: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6602: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6603: 		  join(',',@{$arg}).'" />');
1.242     albertel 6604: 	$r->print($message);
1.157     albertel 6605: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6606: 	foreach my $question (@{$arg}) {
1.447     foxr     6607: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6608: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6609: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6610: 				      @select_array);
1.157     albertel 6611: 	}
                   6612:     } elsif ($error eq 'missingbubble') {
                   6613: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6614: 	$r->print($message);
1.157     albertel 6615: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6616: 	$r->print("Some questions have no scanned bubbles\n");
                   6617: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6618: 		  join(',',@{$arg}).'" />');
                   6619: 	foreach my $question (@{$arg}) {
1.448     foxr     6620: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6621: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6622: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6623: 	}
                   6624:     } else {
                   6625: 	$r->print("\n<ul>");
                   6626:     }
                   6627:     $r->print("\n</li></ul>");
                   6628: 
                   6629: }
1.423     albertel 6630: 
                   6631: =pod
                   6632: 
                   6633: =item scantron_bubble_selector
                   6634:   
                   6635:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6636:    possibly showing the existing the selected bubbles if known
1.423     albertel 6637: 
                   6638:  Arguments:
                   6639:     $r           - Apache request object
                   6640:     $scan_config - hash from &get_scantron_config()
                   6641:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6642:     @lines       - array of answer lines.
1.423     albertel 6643: 
                   6644: =cut
                   6645: 
1.157     albertel 6646: sub scantron_bubble_selector {
1.461     foxr     6647:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6648:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6649: 
1.461     foxr     6650: 
1.274     albertel 6651:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6652: 
1.461     foxr     6653:     my $bubble_length = scalar(@lines);
1.460     foxr     6654: 
1.447     foxr     6655: 
1.274     albertel 6656:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6657: 
1.448     foxr     6658:     my $response = $quest-1;
                   6659:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6660: 
1.422     foxr     6661:     my $total_lines = $lines*2;
1.157     albertel 6662:     my @alphabet=('A'..'Z');
1.479     foxr     6663: 
1.422     foxr     6664:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6665: 
                   6666:     for (my $l = 0; $l < $lines; $l++) {
                   6667: 	if ($l != 0) {
                   6668: 	    $r->print('<tr>');
                   6669: 	}
1.462     foxr     6670: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6671: 	for (my $i=0;$i<$max;$i++) {
                   6672: 	    $r->print("\n".'<td align="center">');
                   6673: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6674: 		$r->print('X'); 
                   6675: 		shift(@selected) ;
                   6676: 	    } else { 
                   6677: 		$r->print('&nbsp;'); 
                   6678: 	    }
                   6679: 	    $r->print('</td>');
                   6680: 	    
                   6681: 	}
                   6682: 
                   6683: 	if ($l == 0) {
                   6684: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6685: 
                   6686: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6687: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6688: 	
                   6689: 	}
                   6690: 
                   6691: 	$r->print('</tr><tr>');
                   6692: 
                   6693: 	# FIXME: This may have to be a bit more clever for
                   6694: 	#        multiline questions (different values e.g..).
                   6695: 
                   6696: 	for (my $i=0;$i<$max;$i++) {
1.479     foxr     6697: 	    my $value = "$l:$i";	# Relative bubble line #: Bubble in line.
1.422     foxr     6698: 	    $r->print("\n".
                   6699: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
1.479     foxr     6700: 		      $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
1.422     foxr     6701: 	}
                   6702: 	$r->print('</tr>');
                   6703: 
                   6704: 	    
1.157     albertel 6705:     }
1.422     foxr     6706:     $r->print('</table>');
1.157     albertel 6707: }
                   6708: 
1.423     albertel 6709: =pod
                   6710: 
                   6711: =item num_matches
                   6712: 
1.424     albertel 6713:    Counts the number of characters that are the same between the two arguments.
                   6714: 
                   6715:  Arguments:
                   6716:    $orig - CODE from the scanline
                   6717:    $code - CODE to match against
                   6718: 
                   6719:  Returns:
                   6720:    $count - integer count of the number of same characters between the
                   6721:             two arguments
                   6722: 
1.423     albertel 6723: =cut
                   6724: 
1.194     albertel 6725: sub num_matches {
                   6726:     my ($orig,$code) = @_;
                   6727:     my @code=split(//,$code);
                   6728:     my @orig=split(//,$orig);
                   6729:     my $same=0;
                   6730:     for (my $i=0;$i<scalar(@code);$i++) {
                   6731: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6732:     }
                   6733:     return $same;
                   6734: }
                   6735: 
1.423     albertel 6736: =pod
                   6737: 
                   6738: =item scantron_get_closely_matching_CODEs
                   6739: 
1.424     albertel 6740:    Cycles through all CODEs and finds the set that has the greatest
                   6741:    number of same characters as the provided CODE
                   6742: 
                   6743:  Arguments:
                   6744:    $allcodes - hash ref returned by &get_codes()
                   6745:    $CODE     - CODE from the current scanline
                   6746: 
                   6747:  Returns:
                   6748:    2 element list
                   6749:     - first elements is number of how closely matching the best fit is 
                   6750:       (5 means best set has 5 matching characters)
                   6751:     - second element is an arrary ref containing the set of valid CODEs
                   6752:       that best fit the passed in CODE
                   6753: 
1.423     albertel 6754: =cut
                   6755: 
1.194     albertel 6756: sub scantron_get_closely_matching_CODEs {
                   6757:     my ($allcodes,$CODE)=@_;
                   6758:     my @CODEs;
                   6759:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6760: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6761:     }
                   6762: 
                   6763:     return ($#CODEs,$CODEs[-1]);
                   6764: }
                   6765: 
1.423     albertel 6766: =pod
                   6767: 
                   6768: =item get_codes
                   6769: 
1.424     albertel 6770:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6771:    set of remembered CODEs.
                   6772: 
                   6773:  Arguments:
                   6774:   $old_name - name of the set of remembered CODEs
                   6775:   $cdom     - domain of the course
                   6776:   $cnum     - internal course name
                   6777: 
                   6778:  Returns:
                   6779:   %allcodes - keys are the valid CODEs, values are all 1
                   6780: 
1.423     albertel 6781: =cut
                   6782: 
1.194     albertel 6783: sub get_codes {
1.280     foxr     6784:     my ($old_name, $cdom, $cnum) = @_;
                   6785:     if (!$old_name) {
                   6786: 	$old_name=$env{'form.scantron_CODElist'};
                   6787:     }
                   6788:     if (!$cdom) {
                   6789: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6790:     }
                   6791:     if (!$cnum) {
                   6792: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6793:     }
1.278     albertel 6794:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6795: 				    $cdom,$cnum);
                   6796:     my %allcodes;
                   6797:     if ($result{"type\0$old_name"} eq 'number') {
                   6798: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6799:     } else {
                   6800: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6801:     }
1.194     albertel 6802:     return %allcodes;
                   6803: }
                   6804: 
1.423     albertel 6805: =pod
                   6806: 
                   6807: =item scantron_validate_CODE
                   6808: 
1.424     albertel 6809:    Validates all scanlines in the selected file to not have any
                   6810:    invalid or underspecified CODEs and that none of the codes are
                   6811:    duplicated if this was requested.
                   6812: 
1.423     albertel 6813: =cut
                   6814: 
1.157     albertel 6815: sub scantron_validate_CODE {
                   6816:     my ($r,$currentphase) = @_;
1.257     albertel 6817:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6818:     if ($scantron_config{'CODElocation'} &&
                   6819: 	$scantron_config{'CODEstart'} &&
                   6820: 	$scantron_config{'CODElength'}) {
1.257     albertel 6821: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6822: 	    &FIXME_blow_up()
                   6823: 	}
                   6824:     } else {
                   6825: 	return (0,$currentphase+1);
                   6826:     }
                   6827:     
                   6828:     my %usedCODEs;
                   6829: 
1.194     albertel 6830:     my %allcodes=&get_codes();
1.186     albertel 6831: 
1.447     foxr     6832:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6833: 
1.186     albertel 6834:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6835:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6836: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6837: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6838: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6839: 						 $scan_data);
                   6840: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6841: 	my $error=0;
1.224     albertel 6842: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6843: 	    &scantron_get_correction($r,$i,$scan_record,
                   6844: 				     \%scantron_config,
                   6845: 				     $line,'incorrectCODE',\%allcodes);
                   6846: 	    return(1,$currentphase);
                   6847: 	}
1.221     albertel 6848: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6849: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6850: 	    &scantron_get_correction($r,$i,$scan_record,
                   6851: 				     \%scantron_config,
1.194     albertel 6852: 				     $line,'incorrectCODE',\%allcodes);
                   6853: 	    return(1,$currentphase);
1.186     albertel 6854: 	}
1.214     albertel 6855: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6856: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6857: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6858: 	    &scantron_get_correction($r,$i,$scan_record,
                   6859: 				     \%scantron_config,
1.194     albertel 6860: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6861: 	    return(1,$currentphase);
1.186     albertel 6862: 	}
1.194     albertel 6863: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6864:     }
1.157     albertel 6865:     return (0,$currentphase+1);
                   6866: }
                   6867: 
1.423     albertel 6868: =pod
                   6869: 
                   6870: =item scantron_validate_doublebubble
                   6871: 
1.424     albertel 6872:    Validates all scanlines in the selected file to not have any
                   6873:    bubble lines with multiple bubbles marked.
                   6874: 
1.423     albertel 6875: =cut
                   6876: 
1.157     albertel 6877: sub scantron_validate_doublebubble {
                   6878:     my ($r,$currentphase) = @_;
                   6879:     #get student info
                   6880:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6881:     my %idmap=&username_to_idmap($classlist);
                   6882: 
                   6883:     #get scantron line setup
1.257     albertel 6884:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6885:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6886: 
                   6887:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6888: 
1.157     albertel 6889:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6890: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6891: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6892: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6893: 						 $scan_data);
                   6894: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6895: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6896: 				 'doublebubble',
                   6897: 				 $$scan_record{'scantron.doubleerror'});
                   6898:     	return (1,$currentphase);
                   6899:     }
                   6900:     return (0,$currentphase+1);
                   6901: }
                   6902: 
1.423     albertel 6903: =pod
                   6904: 
                   6905: =item scantron_get_maxbubble
                   6906: 
1.424     albertel 6907:    Returns the maximum number of bubble lines that are expected to
                   6908:    occur. Does this by walking the selected sequence rendering the
                   6909:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6910:    for what the current value of the problem counter is.
                   6911: 
1.447     foxr     6912:    Caches the results to $env{'form.scantron_maxbubble'},
                   6913:    $env{'form.scantron.bubble_lines.n'} and 
                   6914:    $env{'form.scantron.first_bubble_line.n'}
                   6915:    which are the total number of bubble, lines, the number of bubble
                   6916:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6917: 
1.423     albertel 6918: =cut
                   6919: 
1.330     albertel 6920: sub scantron_get_maxbubble {    
1.257     albertel 6921:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6922: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6923: 	&restore_bubble_lines();
1.257     albertel 6924: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6925:     }
1.330     albertel 6926: 
1.447     foxr     6927:     my (undef, undef, $sequence) =
1.257     albertel 6928: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6929: 
1.447     foxr     6930:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6931:     my $map=$navmap->getResourceByUrl($sequence);
                   6932:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6933: 
                   6934:     &Apache::lonxml::clear_problem_counter();
                   6935: 
1.435     foxr     6936:     my $uname       = $env{'form.student'};
                   6937:     my $udom        = $env{'form.userdom'};
                   6938:     my $cid         = $env{'request.course.id'};
                   6939:     my $total_lines = 0;
                   6940:     %bubble_lines_per_response = ();
1.447     foxr     6941:     %first_bubble_line         = ();
1.435     foxr     6942: 
1.447     foxr     6943:   
                   6944:     my $response_number = 0;
                   6945:     my $bubble_line     = 0;
1.191     albertel 6946:     foreach my $resource (@resources) {
1.435     foxr     6947: 	my $symb = $resource->symb();
1.447     foxr     6948: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6949: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6950: 					('symb' => $resource->symb()),
                   6951: 					('grade_target' => 'analyze'),
                   6952: 					('grade_courseid' => $cid),
                   6953: 					('grade_domain' => $udom),
                   6954: 					('grade_username' => $uname));
1.436     albertel 6955: 	my (undef, $an) =
1.435     foxr     6956: 	    split(/_HASH_REF__/,$result, 2);
                   6957: 
                   6958: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6959: 
                   6960: 
                   6961: 
                   6962: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6963: 
1.460     foxr     6964: 
                   6965: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
1.447     foxr     6966: 
                   6967: 	    # TODO - make this a persistent hash not an array.
                   6968: 
                   6969: 
                   6970: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6971: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6972: 	    $response_number++;
                   6973: 
                   6974: 	    $bubble_line +=  $lines;
                   6975: 	    $total_lines +=  $lines;
1.435     foxr     6976: 	}
                   6977: 
1.191     albertel 6978:     }
                   6979:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6980: 
                   6981:     &save_bubble_lines();
1.330     albertel 6982:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6983: 	$total_lines;
1.257     albertel 6984:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6985: }
                   6986: 
1.423     albertel 6987: =pod
                   6988: 
                   6989: =item scantron_validate_missingbubbles
                   6990: 
1.424     albertel 6991:    Validates all scanlines in the selected file to not have any
1.447     foxr     6992:     answers that don't have bubbles that have not been verified
                   6993:     to be bubble free.
1.424     albertel 6994: 
1.423     albertel 6995: =cut
                   6996: 
1.157     albertel 6997: sub scantron_validate_missingbubbles {
                   6998:     my ($r,$currentphase) = @_;
                   6999:     #get student info
                   7000:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7001:     my %idmap=&username_to_idmap($classlist);
                   7002: 
                   7003:     #get scantron line setup
1.257     albertel 7004:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7005:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 7006:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 7007:     if (!$max_bubble) { $max_bubble=2**31; }
                   7008:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 7009: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7010: 	if ($line=~/^[\s\cz]*$/) { next; }
                   7011: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7012: 						 $scan_data);
                   7013: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   7014: 	my @to_correct;
1.470     foxr     7015: 	
                   7016: 	# Probably here's where the error is...
                   7017: 
1.157     albertel 7018: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   7019: 	    if ($missing > $max_bubble) { next; }
                   7020: 	    push(@to_correct,$missing);
                   7021: 	}
                   7022: 	if (@to_correct) {
                   7023: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   7024: 				     $line,'missingbubble',\@to_correct);
                   7025: 	    return (1,$currentphase);
                   7026: 	}
                   7027: 
                   7028:     }
                   7029:     return (0,$currentphase+1);
                   7030: }
                   7031: 
1.423     albertel 7032: =pod
                   7033: 
                   7034: =item scantron_process_students
                   7035: 
                   7036:    Routine that does the actual grading of the bubble sheet information.
                   7037: 
                   7038:    The parsed scanline hash is added to %env 
                   7039: 
                   7040:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   7041:    foreach resource , with the form data of
                   7042: 
                   7043: 	'submitted'     =>'scantron' 
                   7044: 	'grade_target'  =>'grade',
                   7045: 	'grade_username'=> username of student
                   7046: 	'grade_domain'  => domain of student
                   7047: 	'grade_courseid'=> of course
                   7048: 	'grade_symb'    => symb of resource to grade
                   7049: 
                   7050:     This triggers a grading pass. The problem grading code takes care
                   7051:     of converting the bubbled letter information (now in %env) into a
                   7052:     valid submission.
                   7053: 
                   7054: =cut
                   7055: 
1.82      albertel 7056: sub scantron_process_students {
1.75      albertel 7057:     my ($r) = @_;
1.257     albertel 7058:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 7059:     my ($symb)=&get_symb($r);
1.81      albertel 7060:     if (!$symb) {return '';}
1.324     albertel 7061:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 7062: 
1.257     albertel 7063:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 7064:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 7065:     my $classlist=&Apache::loncoursedata::get_classlist();
                   7066:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 7067:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 7068:     my $map=$navmap->getResourceByUrl($sequence);
                   7069:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 7070: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 7071:     my $result= <<SCANTRONFORM;
1.81      albertel 7072: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   7073:   <input type="hidden" name="command" value="scantron_configphase" />
                   7074:   $default_form_data
                   7075: SCANTRONFORM
1.82      albertel 7076:     $r->print($result);
                   7077: 
                   7078:     my @delayqueue;
1.140     albertel 7079:     my %completedstudents;
                   7080:     
1.200     albertel 7081:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 7082:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 7083:  				    'Scantron Progress',$count,
1.195     albertel 7084: 				    'inline',undef,'scantronupload');
1.140     albertel 7085:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   7086: 					  'Processing first student');
                   7087:     my $start=&Time::HiRes::time();
1.158     albertel 7088:     my $i=-1;
1.200     albertel 7089:     my ($uname,$udom,$started);
1.447     foxr     7090: 
                   7091:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   7092: 
1.157     albertel 7093:     while ($i<$scanlines->{'count'}) {
                   7094:  	($uname,$udom)=('','');
                   7095:  	$i++;
1.200     albertel 7096:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7097:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7098: 	if ($started) {
                   7099: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7100: 						     'last student');
                   7101: 	}
                   7102: 	$started=1;
1.157     albertel 7103:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7104:  						 $scan_data);
                   7105:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7106:  					      \%idmap,$i)) {
                   7107:   	    &scantron_add_delay(\@delayqueue,$line,
                   7108:  				'Unable to find a student that matches',1);
                   7109:  	    next;
                   7110:   	}
                   7111:  	if (exists $completedstudents{$uname}) {
                   7112:  	    &scantron_add_delay(\@delayqueue,$line,
                   7113:  				'Student '.$uname.' has multiple sheets',2);
                   7114:  	    next;
                   7115:  	}
                   7116:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7117: 
                   7118: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7119:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7120: 
                   7121: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7122: 	    &scantron_putfile($scanlines,$scan_data);
                   7123: 	}
1.161     albertel 7124: 	
                   7125: 	my $i=0;
1.83      albertel 7126: 	foreach my $resource (@resources) {
1.85      albertel 7127: 	    $i++;
1.193     albertel 7128: 	    my %form=('submitted'     =>'scantron',
                   7129: 		      'grade_target'  =>'grade',
                   7130: 		      'grade_username'=>$uname,
                   7131: 		      'grade_domain'  =>$udom,
1.257     albertel 7132: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7133: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7134: 	    if (exists($scan_record->{'scantron.CODE'})
                   7135: 		&& 
                   7136: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7137: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7138: 	    } else {
                   7139: 		$form{'CODE'}='';
1.193     albertel 7140: 	    }
                   7141: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7142: 	    if ($result ne '') {
                   7143: 	    }
1.213     albertel 7144: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7145: 	}
1.140     albertel 7146: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7147: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7148:     } continue {
1.330     albertel 7149: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7150: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7151:     }
1.140     albertel 7152:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7153: #    my $lasttime = &Time::HiRes::time()-$start;
                   7154: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7155: 
1.200     albertel 7156:     $r->print("</form>");
1.324     albertel 7157:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7158:     return '';
1.75      albertel 7159: }
1.157     albertel 7160: 
1.423     albertel 7161: =pod
                   7162: 
                   7163: =item scantron_upload_scantron_data
                   7164: 
                   7165:     Creates the screen for adding a new bubble sheet data file to a course.
                   7166: 
                   7167: =cut
                   7168: 
1.157     albertel 7169: sub scantron_upload_scantron_data {
                   7170:     my ($r)=@_;
1.257     albertel 7171:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7172:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7173: 							  'domainid',
                   7174: 							  'coursename');
1.257     albertel 7175:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7176: 						   'domainid');
1.324     albertel 7177:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 7178:     $r->print(<<UPLOAD);
                   7179: <script type="text/javascript" language="javascript">
                   7180:     function checkUpload(formname) {
                   7181: 	if (formname.upfile.value == "") {
                   7182: 	    alert("Please use the browse button to select a file from your local directory.");
                   7183: 	    return false;
                   7184: 	}
                   7185: 	formname.submit();
                   7186:     }
                   7187: </script>
                   7188: 
                   7189: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7190: $default_form_data
1.181     albertel 7191: <table>
                   7192: <tr><td>$select_link </td></tr>
                   7193: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7194: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7195: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7196: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7197: </table>
1.157     albertel 7198: <input name='command' value='scantronupload_save' type='hidden' />
                   7199: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7200: </form>
                   7201: UPLOAD
                   7202:     return '';
                   7203: }
                   7204: 
1.423     albertel 7205: =pod
                   7206: 
                   7207: =item scantron_upload_scantron_data_save
                   7208: 
                   7209:    Adds a provided bubble information data file to the course if user
                   7210:    has the correct privileges to do so.  
                   7211: 
                   7212: =cut
                   7213: 
1.157     albertel 7214: sub scantron_upload_scantron_data_save {
                   7215:     my($r)=@_;
1.324     albertel 7216:     my ($symb)=&get_symb($r,1);
1.182     albertel 7217:     my $doanotherupload=
                   7218: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7219: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7220: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7221: 	'</form>'."\n";
1.257     albertel 7222:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7223: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7224: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7225: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7226: 	if ($symb) {
1.324     albertel 7227: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7228: 	} else {
                   7229: 	    $r->print($doanotherupload);
                   7230: 	}
1.162     albertel 7231: 	return '';
                   7232:     }
1.257     albertel 7233:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7234:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7235:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7236:     #FIXME
                   7237:     #copied from lonnet::userfileupload()
                   7238:     #make that function able to target a specified course
                   7239:     # Replace Windows backslashes by forward slashes
                   7240:     $fname=~s/\\/\//g;
                   7241:     # Get rid of everything but the actual filename
                   7242:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7243:     # Replace spaces by underscores
                   7244:     $fname=~s/\s+/\_/g;
                   7245:     # Replace all other weird characters by nothing
                   7246:     $fname=~s/[^\w\.\-]//g;
                   7247:     # See if there is anything left
                   7248:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7249:     my $uploadedfile=$fname;
1.157     albertel 7250:     $fname='scantron_orig_'.$fname;
1.257     albertel 7251:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7252: 	$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 7253:     } else {
1.275     albertel 7254: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7255: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7256: 	    $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 7257: 	} else {
1.398     albertel 7258: 	    $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 7259: 	}
                   7260:     }
1.174     albertel 7261:     if ($symb) {
1.209     ng       7262: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7263:     } else {
1.182     albertel 7264: 	$r->print($doanotherupload);
1.174     albertel 7265:     }
1.157     albertel 7266:     return '';
                   7267: }
                   7268: 
1.423     albertel 7269: =pod
                   7270: 
                   7271: =item valid_file
                   7272: 
1.424     albertel 7273:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7274: 
                   7275: =cut
                   7276: 
1.202     albertel 7277: sub valid_file {
                   7278:     my ($requested_file)=@_;
                   7279:     foreach my $filename (sort(&scantron_filenames())) {
                   7280: 	if ($requested_file eq $filename) { return 1; }
                   7281:     }
                   7282:     return 0;
                   7283: }
                   7284: 
1.423     albertel 7285: =pod
                   7286: 
                   7287: =item scantron_download_scantron_data
                   7288: 
                   7289:    Shows a list of the three internal files (original, corrected,
                   7290:    skipped) for a specific bubble sheet data file that exists in the
                   7291:    course.
                   7292: 
                   7293: =cut
                   7294: 
1.202     albertel 7295: sub scantron_download_scantron_data {
                   7296:     my ($r)=@_;
1.324     albertel 7297:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7298:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7299:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7300:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7301:     if (! &valid_file($file)) {
                   7302: 	$r->print(<<ERROR);
                   7303: 	<p>
                   7304: 	    The requested file name was invalid.
                   7305:         </p>
                   7306: ERROR
1.324     albertel 7307: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7308: 	return;
                   7309:     }
                   7310:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7311:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7312:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7313:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7314:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7315:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7316:     $r->print(<<DOWNLOAD);
                   7317:     <p>
                   7318: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7319:     </p>
                   7320:     <p>
                   7321: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7322:     </p>
                   7323:     <p>
                   7324: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7325:     </p>
                   7326: DOWNLOAD
1.324     albertel 7327:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7328:     return '';
                   7329: }
1.157     albertel 7330: 
1.423     albertel 7331: =pod
                   7332: 
                   7333: =back
                   7334: 
                   7335: =cut
                   7336: 
1.75      albertel 7337: #-------- end of section for handling grading scantron forms -------
                   7338: #
                   7339: #-------------------------------------------------------------------
                   7340: 
1.72      ng       7341: #-------------------------- Menu interface -------------------------
                   7342: #
                   7343: #--- Show a Grading Menu button - Calls the next routine ---
                   7344: sub show_grading_menu_form {
1.324     albertel 7345:     my ($symb)=@_;
1.125     ng       7346:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7347: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7348: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7349: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7350: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7351: 	'</form>'."\n";
                   7352:     return $result;
                   7353: }
                   7354: 
1.77      ng       7355: # -- Retrieve choices for grading form
                   7356: sub savedState {
                   7357:     my %savedState = ();
1.257     albertel 7358:     if ($env{'form.saveState'}) {
                   7359: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7360: 	    my ($key,$value) = split(/=/,$_,2);
                   7361: 	    $savedState{$key} = $value;
                   7362: 	}
                   7363:     }
                   7364:     return \%savedState;
                   7365: }
1.76      ng       7366: 
1.443     banghart 7367: sub grading_menu {
                   7368:     my ($request) = @_;
                   7369:     my ($symb)=&get_symb($request);
                   7370:     if (!$symb) {return '';}
                   7371:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7372:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7373: 
1.444     banghart 7374:     $request->print($table);
1.443     banghart 7375:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7376:                   'handgrade'=>$hdgrade,
                   7377:                   'probTitle'=>$probTitle,
                   7378:                   'command'=>'submit_options',
                   7379:                   'saveState'=>"",
                   7380:                   'gradingMenu'=>1,
                   7381:                   'showgrading'=>"yes");
                   7382:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7383:     my @menu = ({ url => $url,
                   7384:                      name => &mt('Manual Grading/View Submissions'),
                   7385:                      short_description => 
                   7386:     &mt('Start the process of hand grading submissions.'),
                   7387:                  });
                   7388:     $fields{'command'} = 'csvform';
                   7389:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7390:     push (@menu, { url => $url,
                   7391:                    name => &mt('Upload Scores'),
                   7392:                    short_description => 
                   7393:             &mt('Specify a file containing the class scores for current resource.')});
                   7394:     $fields{'command'} = 'processclicker';
                   7395:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7396:     push (@menu, { url => $url,
                   7397:                    name => &mt('Process Clicker'),
                   7398:                    short_description => 
                   7399:             &mt('Specify a file containing the clicker information for this resource.')});
                   7400:     $fields{'command'} = 'scantron_selectphase';
                   7401:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7402:     push (@menu, { url => $url,
1.454     banghart 7403:                    name => &mt('Grade/Manage Scantron Forms'),
                   7404:                    short_description => 
                   7405:             &mt('')});
1.443     banghart 7406:     $fields{'command'} = 'verify';
                   7407:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7408:     push (@menu, { url => "",
1.443     banghart 7409:                    name => &mt('Verify Receipt'),
                   7410:                    short_description => 
                   7411:             &mt('')});
                   7412:     #
                   7413:     # Create the menu
                   7414:     my $Str;
1.444     banghart 7415:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7416:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7417:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7418:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7419: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7420: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7421: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7422: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7423: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7424: 
1.443     banghart 7425:     foreach my $menudata (@menu) {
1.445     banghart 7426:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7427:             $Str .='    <h3><a '.
                   7428:                 $menudata->{'jscript'}.
                   7429:                 ' href="'.
                   7430:                 $menudata->{'url'}.'" >'.
                   7431:                 $menudata->{'name'}."</a></h3>\n";
                   7432:         } else {
1.485     albertel 7433:             $Str .='    <h3><input type="button" value="'.&mt('Verify Receipt').'" '.
1.445     banghart 7434:                 $menudata->{'jscript'}.
1.458     banghart 7435:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7436:                 ' /></h3>';
1.446     banghart 7437:             $Str .= ('&nbsp;'x8).
1.485     albertel 7438: 		&mt(' receipt: [_1]',
                   7439: 		    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7440:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />');
1.444     banghart 7441:         }
1.443     banghart 7442:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7443:             "\n";
                   7444:     }
1.444     banghart 7445:     $Str .="</form>\n";
1.443     banghart 7446:     $request->print(<<GRADINGMENUJS);
                   7447: <script type="text/javascript" language="javascript">
                   7448:     function checkChoice(formname,val,cmdx) {
                   7449: 	if (val <= 2) {
                   7450: 	    var cmd = radioSelection(formname.radioChoice);
                   7451: 	    var cmdsave = cmd;
                   7452: 	} else {
                   7453: 	    cmd = cmdx;
                   7454: 	    cmdsave = 'submission';
                   7455: 	}
                   7456: 	formname.command.value = cmd;
                   7457: 	if (val < 5) formname.submit();
                   7458: 	if (val == 5) {
1.458     banghart 7459: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7460: 	        return false;
                   7461: 	    } else {
                   7462: 	        formname.submit();
                   7463: 	    }
1.445     banghart 7464: 	}
                   7465:     }
1.443     banghart 7466: 
                   7467:     function checkReceiptNo(formname,nospace) {
                   7468: 	var receiptNo = formname.receipt.value;
                   7469: 	var checkOpt = false;
                   7470: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7471: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7472: 	if (checkOpt) {
                   7473: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7474: 	    formname.receipt.value = "";
                   7475: 	    formname.receipt.focus();
                   7476: 	    return false;
                   7477: 	}
                   7478: 	return true;
                   7479:     }
                   7480: </script>
                   7481: GRADINGMENUJS
                   7482:     &commonJSfunctions($request);
                   7483:     return $Str;    
                   7484: }
                   7485: 
                   7486: 
                   7487: #--- Displays the submissions first page -------
                   7488: sub submit_options {
1.72      ng       7489:     my ($request) = @_;
1.324     albertel 7490:     my ($symb)=&get_symb($request);
1.72      ng       7491:     if (!$symb) {return '';}
1.76      ng       7492:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7493: 
                   7494:     $request->print(<<GRADINGMENUJS);
                   7495: <script type="text/javascript" language="javascript">
1.116     ng       7496:     function checkChoice(formname,val,cmdx) {
                   7497: 	if (val <= 2) {
                   7498: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7499: 	    var cmdsave = cmd;
1.116     ng       7500: 	} else {
                   7501: 	    cmd = cmdx;
1.118     ng       7502: 	    cmdsave = 'submission';
1.116     ng       7503: 	}
                   7504: 	formname.command.value = cmd;
1.118     ng       7505: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7506: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7507: 	if (val < 5) formname.submit();
                   7508: 	if (val == 5) {
1.72      ng       7509: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7510: 	    formname.submit();
                   7511: 	}
1.238     albertel 7512: 	if (val < 7) formname.submit();
1.72      ng       7513:     }
                   7514: 
                   7515:     function checkReceiptNo(formname,nospace) {
                   7516: 	var receiptNo = formname.receipt.value;
                   7517: 	var checkOpt = false;
                   7518: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7519: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7520: 	if (checkOpt) {
                   7521: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7522: 	    formname.receipt.value = "";
                   7523: 	    formname.receipt.focus();
                   7524: 	    return false;
                   7525: 	}
                   7526: 	return true;
                   7527:     }
                   7528: </script>
                   7529: GRADINGMENUJS
1.118     ng       7530:     &commonJSfunctions($request);
1.324     albertel 7531:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7532:     my $result;
1.76      ng       7533:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7534:     my $savedState = &savedState();
1.118     ng       7535:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7536:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7537:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7538:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7539: 
                   7540:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7541: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7542: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7543: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7544: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7545: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7546: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7547: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7548: 
1.472     albertel 7549:     $result.='
                   7550:     <div class="LC_grade_select_mode">
1.473     albertel 7551:       <div class="LC_grade_select_mode_current">
                   7552:         <h2>
                   7553:           '.&mt('Grade Current Resource').'
                   7554:         </h2>
                   7555:         <div class="LC_grade_select_mode_body">
                   7556:           <div class="LC_grades_resource_info">
                   7557:            '.$table.'
                   7558:           </div>
                   7559:           <div class="LC_grade_select_mode_selector">
                   7560:              <div class="LC_grade_select_mode_selector_header">
                   7561:                 '.&mt('Sections').'
                   7562:              </div>
                   7563:              <div class="LC_grade_select_mode_selector_body">
                   7564: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7565:     if (ref($sections)) {
1.472     albertel 7566: 	foreach my $section (sort (@$sections)) {
                   7567: 	    $result.='<option value="'.$section.'" '.
                   7568: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7569: 	}
1.116     ng       7570:     }
1.401     albertel 7571:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7572:     $result.='
1.473     albertel 7573:              </div>
                   7574:           </div>
                   7575:           <div class="LC_grade_select_mode_selector">
                   7576:              <div class="LC_grade_select_mode_selector_header">
                   7577:                 '.&mt('Groups').'
                   7578:              </div>
                   7579:              <div class="LC_grade_select_mode_selector_body">
                   7580:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7581:              </div>
1.472     albertel 7582:           </div>
1.473     albertel 7583:           <div class="LC_grade_select_mode_selector">
                   7584:              <div class="LC_grade_select_mode_selector_header">
                   7585:                 '.&mt('Access Status').'
                   7586:              </div>
                   7587:              <div class="LC_grade_select_mode_selector_body">
                   7588:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7589:              </div>
1.472     albertel 7590:           </div>
1.473     albertel 7591:           <div class="LC_grade_select_mode_selector">
                   7592:              <div class="LC_grade_select_mode_selector_header">
                   7593:                 '.&mt('Submission Status').'
                   7594:              </div>
                   7595:              <div class="LC_grade_select_mode_selector_body">
                   7596:                <select name="submitonly" size="5">
                   7597: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7598: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7599: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7600: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7601:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7602:                </select>
                   7603:              </div>
1.472     albertel 7604:           </div>
1.473     albertel 7605:           <div class="LC_grade_select_mode_type_body">
                   7606:             <div class="LC_grade_select_mode_type">
                   7607:               <label>
                   7608:                 <input type="radio" name="radioChoice" value="submission" '.
                   7609:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7610:              &mt('Select individual students to grade and view submissions.').'
                   7611: 	      </label> 
                   7612:             </div>
                   7613:             <div class="LC_grade_select_mode_type">
                   7614: 	      <label>
                   7615:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7616:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7617:                     &mt('Grade all selected students in a grading table.').'
                   7618:               </label>
                   7619:             </div>
                   7620:             <div class="LC_grade_select_mode_type">
                   7621: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7622:             </div>
1.472     albertel 7623:           </div>
1.473     albertel 7624:         </div>
                   7625:       </div>
                   7626:       <div class="LC_grade_select_mode_page">
                   7627:         <h2>
                   7628:          '.&mt('Grade Complete Folder for One Student').'
                   7629:         </h2>
                   7630:         <div class="LC_grades_select_mode_body">
                   7631:           <div class="LC_grade_select_mode_type_body">
                   7632:             <div class="LC_grade_select_mode_type">
                   7633:               <label>
                   7634:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7635: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7636:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7637:               </label>
                   7638:             </div>
                   7639:             <div class="LC_grade_select_mode_type">
                   7640: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7641:             </div>
1.472     albertel 7642:           </div>
                   7643:         </div>
                   7644:       </div>
                   7645:     </div>
                   7646:   </form>';
1.44      ng       7647:     return $result;
1.2       albertel 7648: }
                   7649: 
1.285     albertel 7650: sub reset_perm {
                   7651:     undef(%perm);
                   7652: }
                   7653: 
                   7654: sub init_perm {
                   7655:     &reset_perm();
1.300     albertel 7656:     foreach my $test_perm ('vgr','mgr','opa') {
                   7657: 
                   7658: 	my $scope = $env{'request.course.id'};
                   7659: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7660: 
                   7661: 	    $scope .= '/'.$env{'request.course.sec'};
                   7662: 	    if ( $perm{$test_perm}=
                   7663: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7664: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7665: 	    } else {
                   7666: 		delete($perm{$test_perm});
                   7667: 	    }
1.285     albertel 7668: 	}
                   7669:     }
                   7670: }
                   7671: 
1.400     www      7672: sub gather_clicker_ids {
1.408     albertel 7673:     my %clicker_ids;
1.400     www      7674: 
                   7675:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7676: 
                   7677:     # Set up a couple variables.
1.407     albertel 7678:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7679:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7680:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7681: 
1.407     albertel 7682:     foreach my $student (keys(%$classlist)) {
1.438     www      7683:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7684:         my $username = $classlist->{$student}->[$username_idx];
                   7685:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7686:         my $clickers =
1.408     albertel 7687: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7688:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7689:             $id=~s/^[\#0]+//;
1.421     www      7690:             $id=~s/[\-\:]//g;
1.407     albertel 7691:             if (exists($clicker_ids{$id})) {
1.408     albertel 7692: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7693:             } else {
1.408     albertel 7694: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7695:             }
                   7696:         }
                   7697:     }
1.407     albertel 7698:     return %clicker_ids;
1.400     www      7699: }
                   7700: 
1.402     www      7701: sub gather_adv_clicker_ids {
1.408     albertel 7702:     my %clicker_ids;
1.402     www      7703:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7704:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7705:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7706:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7707:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7708:             my ($puname,$pudom)=split(/\:/,$person);
                   7709:             my $clickers =
1.408     albertel 7710: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7711:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7712: 		$id=~s/^[\#0]+//;
1.421     www      7713:                 $id=~s/[\-\:]//g;
1.408     albertel 7714: 		if (exists($clicker_ids{$id})) {
                   7715: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7716: 		} else {
                   7717: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7718: 		}
1.405     www      7719:             }
1.402     www      7720:         }
                   7721:     }
1.407     albertel 7722:     return %clicker_ids;
1.402     www      7723: }
                   7724: 
1.413     www      7725: sub clicker_grading_parameters {
                   7726:     return ('gradingmechanism' => 'scalar',
                   7727:             'upfiletype' => 'scalar',
                   7728:             'specificid' => 'scalar',
                   7729:             'pcorrect' => 'scalar',
                   7730:             'pincorrect' => 'scalar');
                   7731: }
                   7732: 
1.400     www      7733: sub process_clicker {
                   7734:     my ($r)=@_;
                   7735:     my ($symb)=&get_symb($r);
                   7736:     if (!$symb) {return '';}
                   7737:     my $result=&checkforfile_js();
                   7738:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7739:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7740:     $result.=$table;
                   7741:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7742:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7743:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7744:         '.</b></td></tr>'."\n";
                   7745:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7746: # Attempt to restore parameters from last session, set defaults if not present
                   7747:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7748:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7749:                                                  \%Saveable_Parameters);
                   7750:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7751:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7752:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7753:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7754: 
                   7755:     my %checked;
                   7756:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7757:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7758:           $checked{$gradingmechanism}="checked='checked'";
                   7759:        }
                   7760:     }
                   7761: 
1.400     www      7762:     my $upload=&mt("Upload File");
                   7763:     my $type=&mt("Type");
1.402     www      7764:     my $attendance=&mt("Award points just for participation");
                   7765:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7766:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7767:     my $pcorrect=&mt("Percentage points for correct solution");
                   7768:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7769:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7770: 						   ('iclicker' => 'i>clicker',
                   7771:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7772:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7773:     $result.=<<ENDUPFORM;
1.402     www      7774: <script type="text/javascript">
                   7775: function sanitycheck() {
                   7776: // Accept only integer percentages
                   7777:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7778:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7779: // Find out grading choice
                   7780:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7781:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7782:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7783:       }
                   7784:    }
                   7785: // By default, new choice equals user selection
                   7786:    newgradingchoice=gradingchoice;
                   7787: // Not good to give more points for false answers than correct ones
                   7788:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7789:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7790:    }
                   7791: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7792:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7793:       document.forms.gradesupload.pcorrect.value=100;
                   7794:       document.forms.gradesupload.pincorrect.value=100;
                   7795:    }
                   7796: // If the values are different, cannot be attendance only
                   7797:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7798:        (gradingchoice=='attendance')) {
                   7799:        newgradingchoice='personnel';
                   7800:    }
                   7801: // Change grading choice to new one
                   7802:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7803:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7804:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7805:       } else {
                   7806:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7807:       }
                   7808:    }
                   7809: // Remember the old state
                   7810:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7811: }
                   7812: </script>
1.400     www      7813: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7814: <input type="hidden" name="symb" value="$symb" />
                   7815: <input type="hidden" name="command" value="processclickerfile" />
                   7816: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7817: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7818: <input type="file" name="upfile" size="50" />
                   7819: <br /><label>$type: $selectform</label>
1.451     albertel 7820: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7821: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7822: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7823: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7824: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7825: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7826: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7827: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7828: </form>
                   7829: ENDUPFORM
                   7830:     $result.='</td></tr></table>'."\n".
                   7831:              '</td></tr></table><br /><br />'."\n";
                   7832:     $result.=&show_grading_menu_form($symb);
                   7833:     return $result;
                   7834: }
                   7835: 
                   7836: sub process_clicker_file {
                   7837:     my ($r)=@_;
                   7838:     my ($symb)=&get_symb($r);
                   7839:     if (!$symb) {return '';}
1.413     www      7840: 
                   7841:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7842:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7843:                                               \%Saveable_Parameters);
                   7844: 
1.400     www      7845:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7846:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7847: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7848: 	return $result.&show_grading_menu_form($symb);
1.404     www      7849:     }
1.407     albertel 7850:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7851:     my %correct_ids;
1.404     www      7852:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7853: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7854:     }
                   7855:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7856: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7857: 	   $correct_id=~tr/a-z/A-Z/;
                   7858: 	   $correct_id=~s/\s//gs;
                   7859: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7860:            $correct_id=~s/[\-\:]//g;
1.414     www      7861:            if ($correct_id) {
                   7862: 	      $correct_ids{$correct_id}='specified';
                   7863:            }
                   7864:         }
1.400     www      7865:     }
1.404     www      7866:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7867: 	$result.=&mt('Score based on attendance only');
1.404     www      7868:     } else {
1.408     albertel 7869: 	my $number=0;
1.411     www      7870: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7871: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7872: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7873: 	    if ($correct_ids{$id} eq 'specified') {
                   7874: 		$result.=&mt('specified');
                   7875: 	    } else {
                   7876: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7877: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7878: 	    }
                   7879: 	    $number++;
                   7880: 	}
1.411     www      7881:         $result.="</p>\n";
1.408     albertel 7882: 	if ($number==0) {
                   7883: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7884: 	    return $result.&show_grading_menu_form($symb);
                   7885: 	}
1.404     www      7886:     }
1.405     www      7887:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7888:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7889: 		     '<span class="LC_error">',
                   7890: 		     '</span>',
                   7891: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7892:         return $result.&show_grading_menu_form($symb);
                   7893:     }
1.410     www      7894: 
                   7895: # Were able to get all the info needed, now analyze the file
                   7896: 
1.411     www      7897:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7898:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7899:     my $heading=&mt('Scanning clicker file');
                   7900:     $result.=(<<ENDHEADER);
                   7901: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7902: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7903: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7904: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7905: <input type="hidden" name="symb" value="$symb" />
                   7906: <input type="hidden" name="command" value="assignclickergrades" />
                   7907: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7908: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7909: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7910: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7911: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7912: ENDHEADER
1.408     albertel 7913:     my %responses;
                   7914:     my @questiontitles;
1.405     www      7915:     my $errormsg='';
                   7916:     my $number=0;
                   7917:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7918: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7919:     }
1.419     www      7920:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7921:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7922:     }
1.411     www      7923:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7924:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7925:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7926:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7927:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7928:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7929:              '<br />';
1.414     www      7930: # Remember Question Titles
                   7931: # FIXME: Possibly need delimiter other than ":"
                   7932:     for (my $i=0;$i<$number;$i++) {
                   7933:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7934:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7935:     }
1.411     www      7936:     my $correct_count=0;
                   7937:     my $student_count=0;
                   7938:     my $unknown_count=0;
1.414     www      7939: # Match answers with usernames
                   7940: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7941:     foreach my $id (keys(%responses)) {
1.410     www      7942:        if ($correct_ids{$id}) {
1.414     www      7943:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7944:           $correct_count++;
1.410     www      7945:        } elsif ($clicker_ids{$id}) {
1.437     www      7946:           if ($clicker_ids{$id}=~/\,/) {
                   7947: # More than one user with the same clicker!
                   7948:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7949:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7950:                            "<select name='multi".$id."'>";
                   7951:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7952:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7953:              }
                   7954:              $result.='</select>';
                   7955:              $unknown_count++;
                   7956:           } else {
                   7957: # Good: found one and only one user with the right clicker
                   7958:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7959:              $student_count++;
                   7960:           }
1.410     www      7961:        } else {
1.411     www      7962:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7963:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7964:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7965:                    "\n".&mt("Domain").": ".
                   7966:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7967:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7968:           $unknown_count++;
1.410     www      7969:        }
1.405     www      7970:     }
1.412     www      7971:     $result.='<hr />'.
                   7972:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7973:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7974:        if ($correct_count==0) {
                   7975:           $errormsg.="Found no correct answers answers for grading!";
                   7976:        } elsif ($correct_count>1) {
1.414     www      7977:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7978:        }
                   7979:     }
1.428     www      7980:     if ($number<1) {
                   7981:        $errormsg.="Found no questions.";
                   7982:     }
1.412     www      7983:     if ($errormsg) {
                   7984:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7985:     } else {
                   7986:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7987:     }
                   7988:     $result.='</form></td></tr></table>'."\n".
1.410     www      7989:              '</td></tr></table><br /><br />'."\n";
1.404     www      7990:     return $result.&show_grading_menu_form($symb);
1.400     www      7991: }
                   7992: 
1.405     www      7993: sub iclicker_eval {
1.406     www      7994:     my ($questiontitles,$responses)=@_;
1.405     www      7995:     my $number=0;
                   7996:     my $errormsg='';
                   7997:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7998:         my %components=&Apache::loncommon::record_sep($line);
                   7999:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 8000: 	if ($entries[0] eq 'Question') {
                   8001: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   8002: 		$$questiontitles[$number]=$entries[$i];
                   8003: 		$number++;
                   8004: 	    }
                   8005: 	}
                   8006: 	if ($entries[0]=~/^\#/) {
                   8007: 	    my $id=$entries[0];
                   8008: 	    my @idresponses;
                   8009: 	    $id=~s/^[\#0]+//;
                   8010: 	    for (my $i=0;$i<$number;$i++) {
                   8011: 		my $idx=3+$i*6;
                   8012: 		push(@idresponses,$entries[$idx]);
                   8013: 	    }
                   8014: 	    $$responses{$id}=join(',',@idresponses);
                   8015: 	}
1.405     www      8016:     }
                   8017:     return ($errormsg,$number);
                   8018: }
                   8019: 
1.419     www      8020: sub interwrite_eval {
                   8021:     my ($questiontitles,$responses)=@_;
                   8022:     my $number=0;
                   8023:     my $errormsg='';
1.420     www      8024:     my $skipline=1;
                   8025:     my $questionnumber=0;
                   8026:     my %idresponses=();
1.419     www      8027:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   8028:         my %components=&Apache::loncommon::record_sep($line);
                   8029:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      8030:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   8031:         if ($entries[1] eq 'Response') { $skipline=1; }
                   8032:         next if $skipline;
                   8033:         if ($entries[0]!=$questionnumber) {
                   8034:            $questionnumber=$entries[0];
                   8035:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   8036:            $number++;
1.419     www      8037:         }
1.420     www      8038:         my $id=$entries[4];
                   8039:         $id=~s/^[\#0]+//;
1.421     www      8040:         $id=~s/^v\d*\://i;
                   8041:         $id=~s/[\-\:]//g;
1.420     www      8042:         $idresponses{$id}[$number]=$entries[6];
                   8043:     }
                   8044:     foreach my $id (keys %idresponses) {
                   8045:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   8046:        $$responses{$id}=~s/^\s*\,//;
1.419     www      8047:     }
                   8048:     return ($errormsg,$number);
                   8049: }
                   8050: 
1.414     www      8051: sub assign_clicker_grades {
                   8052:     my ($r)=@_;
                   8053:     my ($symb)=&get_symb($r);
                   8054:     if (!$symb) {return '';}
1.416     www      8055: # See which part we are saving to
                   8056:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   8057: # FIXME: This should probably look for the first handgradeable part
                   8058:     my $part=$$partlist[0];
                   8059: # Start screen output
1.414     www      8060:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      8061: 
1.414     www      8062:     my $heading=&mt('Assigning grades based on clicker file');
                   8063:     $result.=(<<ENDHEADER);
                   8064: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   8065: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   8066: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   8067: ENDHEADER
                   8068: # Get correct result
                   8069: # FIXME: Possibly need delimiter other than ":"
                   8070:     my @correct=();
1.415     www      8071:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   8072:     my $number=$env{'form.number'};
                   8073:     if ($gradingmechanism ne 'attendance') {
1.414     www      8074:        foreach my $key (keys(%env)) {
                   8075:           if ($key=~/^form\.correct\:/) {
                   8076:              my @input=split(/\,/,$env{$key});
                   8077:              for (my $i=0;$i<=$#input;$i++) {
                   8078:                  if (($correct[$i]) && ($input[$i]) &&
                   8079:                      ($correct[$i] ne $input[$i])) {
                   8080:                     $result.='<br /><span class="LC_warning">'.
                   8081:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   8082:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   8083:                  } elsif ($input[$i]) {
                   8084:                     $correct[$i]=$input[$i];
                   8085:                  }
                   8086:              }
                   8087:           }
                   8088:        }
1.415     www      8089:        for (my $i=0;$i<$number;$i++) {
1.414     www      8090:           if (!$correct[$i]) {
                   8091:              $result.='<br /><span class="LC_error">'.
                   8092:                       &mt('No correct result given for question "[_1]"!',
                   8093:                           $env{'form.question:'.$i}).'</span>';
                   8094:           }
                   8095:        }
                   8096:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8097:     }
                   8098: # Start grading
1.415     www      8099:     my $pcorrect=$env{'form.pcorrect'};
                   8100:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8101:     my $storecount=0;
1.415     www      8102:     foreach my $key (keys(%env)) {
1.420     www      8103:        my $user='';
1.415     www      8104:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8105:           $user=$1;
                   8106:        }
                   8107:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8108:           my $id=$1;
                   8109:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8110:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8111:           } elsif ($env{'form.multi'.$id}) {
                   8112:              $user=$env{'form.multi'.$id};
1.420     www      8113:           }
                   8114:        }
                   8115:        if ($user) { 
1.415     www      8116:           my @answer=split(/\,/,$env{$key});
                   8117:           my $sum=0;
                   8118:           for (my $i=0;$i<$number;$i++) {
                   8119:              if ($answer[$i]) {
                   8120:                 if ($gradingmechanism eq 'attendance') {
                   8121:                    $sum+=$pcorrect;
                   8122:                 } else {
                   8123:                    if ($answer[$i] eq $correct[$i]) {
                   8124:                       $sum+=$pcorrect;
                   8125:                    } else {
                   8126:                       $sum+=$pincorrect;
                   8127:                    }
                   8128:                 }
                   8129:              }
                   8130:           }
1.416     www      8131:           my $ave=$sum/(100*$number);
                   8132: # Store
                   8133:           my ($username,$domain)=split(/\:/,$user);
                   8134:           my %grades=();
                   8135:           $grades{"resource.$part.solved"}='correct_by_override';
                   8136:           $grades{"resource.$part.awarded"}=$ave;
                   8137:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8138:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8139:                                                  $env{'request.course.id'},
                   8140:                                                  $domain,$username);
                   8141:           if ($returncode ne 'ok') {
                   8142:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8143:           } else {
                   8144:              $storecount++;
                   8145:           }
1.415     www      8146:        }
                   8147:     }
                   8148: # We are done
1.416     www      8149:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8150:              '</td></tr></table>'."\n".
1.414     www      8151:              '</td></tr></table><br /><br />'."\n";
                   8152:     return $result.&show_grading_menu_form($symb);
                   8153: }
                   8154: 
1.1       albertel 8155: sub handler {
1.41      ng       8156:     my $request=$_[0];
1.434     albertel 8157:     &reset_caches();
1.257     albertel 8158:     if ($env{'browser.mathml'}) {
1.141     www      8159: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8160:     } else {
1.141     www      8161: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8162:     }
                   8163:     $request->send_http_header;
1.44      ng       8164:     return '' if $request->header_only;
1.41      ng       8165:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8166:     my $symb=&get_symb($request,1);
1.160     albertel 8167:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8168:     my $command=$commands[0];
1.447     foxr     8169: 
1.160     albertel 8170:     if ($#commands > 0) {
                   8171: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8172:     }
1.447     foxr     8173: 
                   8174: 
1.353     albertel 8175:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8176:     if ($symb eq '' && $command eq '') {
1.257     albertel 8177: 	if ($env{'user.adv'}) {
                   8178: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8179: 		($env{'form.codethree'})) {
                   8180: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8181: 		    $env{'form.codethree'};
1.41      ng       8182: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8183: 		    &Apache::lonnet::checkin($token);
                   8184: 		if ($tsymb) {
1.137     albertel 8185: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8186: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8187: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8188: 					  ('grade_username' => $tuname,
                   8189: 					   'grade_domain' => $tudom,
                   8190: 					   'grade_courseid' => $tcrsid,
                   8191: 					   'grade_symb' => $tsymb)));
1.41      ng       8192: 		    } else {
1.45      ng       8193: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8194: 		    }
1.41      ng       8195: 		} else {
1.45      ng       8196: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8197: 		}
1.14      www      8198: 	    } else {
1.41      ng       8199: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8200: 	    }
                   8201: 	}
                   8202:     } else {
1.285     albertel 8203: 	&init_perm();
1.104     albertel 8204: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8205: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8206: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8207: 	    &pickStudentPage($request);
1.103     albertel 8208: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8209: 	    &displayPage($request);
1.104     albertel 8210: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8211: 	    &updateGradeByPage($request);
1.104     albertel 8212: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8213: 	    &processGroup($request);
1.104     albertel 8214: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8215: 	    $request->print(&grading_menu($request));
                   8216: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8217: 	    $request->print(&submit_options($request));
1.104     albertel 8218: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8219: 	    $request->print(&viewgrades($request));
1.104     albertel 8220: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8221: 	    $request->print(&processHandGrade($request));
1.106     albertel 8222: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8223: 	    $request->print(&editgrades($request));
1.106     albertel 8224: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8225: 	    $request->print(&verifyreceipt($request));
1.400     www      8226:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8227:             $request->print(&process_clicker($request));
                   8228:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8229:             $request->print(&process_clicker_file($request));
1.414     www      8230:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8231:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8232: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8233: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8234: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8235: 	    $request->print(&csvupload($request));
1.106     albertel 8236: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8237: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8238: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8239: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8240: 		$request->print(&csvuploadoptions($request));
1.41      ng       8241: 	    } else {
1.257     albertel 8242: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8243: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8244: 		} else {
1.257     albertel 8245: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8246: 		}
                   8247: 		$request->print(&csvuploadmap($request));
                   8248: 	    }
1.246     albertel 8249: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8250: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8251: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8252: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8253:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8254:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8255: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8256: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8257: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8258: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8259:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8260:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8261: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8262:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8263:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8264:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8265: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8266:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8267:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8268: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8269:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8270: 	} elsif ($command) {
1.157     albertel 8271: 	    $request->print("Access Denied ($command)");
1.26      albertel 8272: 	}
1.2       albertel 8273:     }
1.353     albertel 8274:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8275:     &reset_caches();
1.44      ng       8276:     return '';
                   8277: }
                   8278: 
1.1       albertel 8279: 1;
                   8280: 
1.13      albertel 8281: __END__;

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