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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.449   ! banghart    4: # $Id: grades.pm,v 1.448 2007/10/09 10:31:21 foxr 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.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
1.447     foxr       50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       51:                                    # index is "symb.part_id"
                     52: 
1.447     foxr       53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     54: 
                     55: # Save and restore the bubble lines array to the form env.
                     56: 
                     57: 
                     58: sub save_bubble_lines {
1.448     foxr       59:     &Apache::lonnet::logthis("Saving bubble_lines...");
1.447     foxr       60:     foreach my $line (keys(%bubble_lines_per_response)) {
1.448     foxr       61: 	&Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
1.447     foxr       62: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     63: 	$env{"form.scantron.first_bubble_line.$line"} =
                     64: 	    $first_bubble_line{$line};
                     65:     }
                     66: }
                     67: 
                     68: 
                     69: sub restore_bubble_lines {
                     70:     my $line = 0;
                     71:     %bubble_lines_per_response = ();
                     72:     while ($env{"form.scantron.bubblelines.$line"}) {
                     73: 	my $value = $env{"form.scantron.bubblelines.$line"};
1.448     foxr       74: 	&Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
1.447     foxr       75: 	$bubble_lines_per_response{$line} = $value;
                     76: 	$first_bubble_line{$line}  =
                     77: 	    $env{"form.scantron.first_bubble_line.$line"};
                     78: 	$line++;
                     79:     }
                     80: 
                     81: }
                     82: 
                     83: #  Given the parsed scanline, get the response for 
                     84: #  'answer' number n:
                     85: 
                     86: sub get_response_bubbles {
                     87:     my ($parsed_line, $response)  = @_;
                     88: 
                     89:     my $bubble_line = $first_bubble_line{$response};
1.448     foxr       90:     my $bubble_lines= $bubble_lines_per_response{$response};
1.447     foxr       91:     my $selected = "";
                     92: 
                     93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                     94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
                     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.398     albertel  174: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(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.398     albertel  257: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    258: 		$resID.'</span></td>'.
1.375     albertel  259: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    260: #	    '<td><b>Handgrade: </b>'.$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">'.
                    335: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  336: 	    '<tr valign="top"><td>'.$grayFont.'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.148     albertel  355: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  356: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  357: 	    $middlerow.'</tr>'.
1.398     albertel  358: 	    '<tr valign="top"><td>'.$grayFont.'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.148     albertel  368: 		    $toprow.='<td><b>true</b></td>';
                    369: 		} else {
                    370: 		    $toprow.='<td><i>true</i></td>';
                    371: 		}
                    372: 	    } else {
                    373: 		$toprow.='<td>false</td>';
                    374: 	    }
1.398     albertel  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  376: 	}
                    377: 	return '<blockquote><table border="1">'.
                    378: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  379: 	    '<tr valign="top"><td>'.$grayFont.'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.442     banghart  480:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  481:     if (!ref($getsec)) {
                    482: 	if ($getsec ne '' && $getsec ne 'all') {
                    483: 	    @getsec=($getsec);
                    484: 	}
                    485:     } else {
                    486: 	@getsec=@{$getsec};
                    487:     }
                    488:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    489: 
1.449   ! banghart  490:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  491:     # Bail out if we were unable to get the classlist
1.56      matthew   492:     return if (! defined($classlist));
1.449   ! banghart  493:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   494:     #
                    495:     my %sections;
                    496:     my %fullnames;
1.205     matthew   497:     foreach my $student (keys(%$classlist)) {
                    498:         my $end      = 
                    499:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    500:         my $start    = 
                    501:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    502:         my $id       = 
                    503:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    504:         my $section  = 
                    505:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    506:         my $fullname = 
                    507:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    508:         my $status   = 
                    509:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449   ! banghart  510:         my $group   = 
        !           511:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        512: 	# filter students according to status selected
1.442     banghart  513: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    514: 	    if (!($stu_status =~ $status)) {
1.205     matthew   515: 		delete ($classlist->{$student});
1.76      ng        516: 		next;
                    517: 	    }
                    518: 	}
1.205     matthew   519: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  520: 	if (&canview($section)) {
1.291     albertel  521: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  522: 		$sections{$section}++;
1.205     matthew   523: 		$fullnames{$student}=$fullname;
1.103     albertel  524: 	    } else {
1.205     matthew   525: 		delete($classlist->{$student});
1.103     albertel  526: 	    }
                    527: 	} else {
1.205     matthew   528: 	    delete($classlist->{$student});
1.103     albertel  529: 	}
1.44      ng        530:     }
                    531:     my %seen = ();
1.56      matthew   532:     my @sections = sort(keys(%sections));
                    533:     return ($classlist,\@sections,\%fullnames);
1.44      ng        534: }
                    535: 
1.103     albertel  536: sub canmodify {
                    537:     my ($sec)=@_;
                    538:     if ($perm{'mgr'}) {
                    539: 	if (!defined($perm{'mgr_section'})) {
                    540: 	    # can modify whole class
                    541: 	    return 1;
                    542: 	} else {
                    543: 	    if ($sec eq $perm{'mgr_section'}) {
                    544: 		#can modify the requested section
                    545: 		return 1;
                    546: 	    } else {
                    547: 		# can't modify the request section
                    548: 		return 0;
                    549: 	    }
                    550: 	}
                    551:     }
                    552:     #can't modify
                    553:     return 0;
                    554: }
                    555: 
                    556: sub canview {
                    557:     my ($sec)=@_;
                    558:     if ($perm{'vgr'}) {
                    559: 	if (!defined($perm{'vgr_section'})) {
                    560: 	    # can modify whole class
                    561: 	    return 1;
                    562: 	} else {
                    563: 	    if ($sec eq $perm{'vgr_section'}) {
                    564: 		#can modify the requested section
                    565: 		return 1;
                    566: 	    } else {
                    567: 		# can't modify the request section
                    568: 		return 0;
                    569: 	    }
                    570: 	}
                    571:     }
                    572:     #can't modify
                    573:     return 0;
                    574: }
                    575: 
1.44      ng        576: #--- Retrieve the grade status of a student for all the parts
                    577: sub student_gradeStatus {
1.324     albertel  578:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  579:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        580:     my %partstatus = ();
                    581:     foreach (@$partlist) {
1.128     ng        582: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        583: 	$status              = 'nothing' if ($status eq '');
                    584: 	$partstatus{$_}      = $status;
                    585: 	my $subkey           = "resource.$_.submitted_by";
                    586: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    587:     }
                    588:     return %partstatus;
                    589: }
                    590: 
1.45      ng        591: # hidden form and javascript that calls the form
                    592: # Use by verifyscript and viewgrades
                    593: # Shows a student's view of problem and submission
                    594: sub jscriptNform {
1.324     albertel  595:     my ($symb) = @_;
1.442     banghart  596:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        597:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    598: 	'    function viewOneStudent(user,domain) {'."\n".
                    599: 	'	document.onestudent.student.value = user;'."\n".
                    600: 	'	document.onestudent.userdom.value = domain;'."\n".
                    601: 	'	document.onestudent.submit();'."\n".
                    602: 	'    }'."\n".
                    603: 	'</script>'."\n";
                    604:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  605: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  606: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    607: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  608: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        609: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    610: 	'<input type="hidden" name="student" value="" />'."\n".
                    611: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    612: 	'</form>'."\n";
                    613:     return $jscript;
                    614: }
1.39      ng        615: 
1.447     foxr      616: 
                    617: 
1.315     bowersj2  618: # Given the score (as a number [0-1] and the weight) what is the final
                    619: # point value? This function will round to the nearest tenth, third,
                    620: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  621: sub compute_points {
1.315     bowersj2  622:     my ($score, $weight) = @_;
                    623:     
                    624:     my $tolerance = .00001;
                    625:     my $points = $score * $weight;
                    626: 
                    627:     # Check for nearness to 1/x.
                    628:     my $check_for_nearness = sub {
                    629:         my ($factor) = @_;
                    630:         my $num = ($points * $factor) + $tolerance;
                    631:         my $floored_num = floor($num);
1.316     albertel  632:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  633:             return $floored_num / $factor;
                    634:         }
                    635:         return $points;
                    636:     };
                    637: 
                    638:     $points = $check_for_nearness->(10);
                    639:     $points = $check_for_nearness->(3);
                    640:     $points = $check_for_nearness->(4);
                    641:     
                    642:     return $points;
                    643: }
                    644: 
1.44      ng        645: #------------------ End of general use routines --------------------
1.87      www       646: 
                    647: #
                    648: # Find most similar essay
                    649: #
                    650: 
                    651: sub most_similar {
1.426     albertel  652:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       653: 
                    654: # ignore spaces and punctuation
                    655: 
                    656:     $uessay=~s/\W+/ /gs;
                    657: 
1.282     www       658: # ignore empty submissions (occuring when only files are sent)
                    659: 
                    660:     unless ($uessay=~/\w+/) { return ''; }
                    661: 
1.87      www       662: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       663:     my $limit=0.6;
1.87      www       664:     my $sname='';
                    665:     my $sdom='';
                    666:     my $scrsid='';
                    667:     my $sessay='';
                    668: # go through all essays ...
1.426     albertel  669:     foreach my $tkey (keys(%$old_essays)) {
                    670: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       671: # ... except the same student
1.426     albertel  672:         next if (($tname eq $uname) && ($tdom eq $udom));
                    673: 	my $tessay=$old_essays->{$tkey};
                    674: 	$tessay=~s/\W+/ /gs;
1.87      www       675: # String similarity gives up if not even limit
1.426     albertel  676: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       677: # Found one
1.426     albertel  678: 	if ($tsimilar>$limit) {
                    679: 	    $limit=$tsimilar;
                    680: 	    $sname=$tname;
                    681: 	    $sdom=$tdom;
                    682: 	    $scrsid=$tcrsid;
                    683: 	    $sessay=$old_essays->{$tkey};
                    684: 	}
1.87      www       685:     }
1.88      www       686:     if ($limit>0.6) {
1.87      www       687:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    688:     } else {
                    689:        return ('','','','',0);
                    690:     }
                    691: }
                    692: 
1.44      ng        693: #-------------------------------------------------------------------
                    694: 
                    695: #------------------------------------ Receipt Verification Routines
1.45      ng        696: #
1.44      ng        697: #--- Check whether a receipt number is valid.---
                    698: sub verifyreceipt {
                    699:     my $request  = shift;
                    700: 
1.257     albertel  701:     my $courseid = $env{'request.course.id'};
1.184     www       702:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  703: 	$env{'form.receipt'};
1.44      ng        704:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  705:     my ($symb)   = &get_symb($request);
1.44      ng        706: 
1.398     albertel  707:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    708: 	$receipt.'</h3></span>'."\n".
                    709: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        710: 
                    711:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   712:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  713:     
                    714:     my $receiptparts=0;
1.390     albertel  715:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    716: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  717:     my $parts=['0'];
1.324     albertel  718:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  719:     foreach (sort 
                    720: 	     {
                    721: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    722: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    723: 		 }
                    724: 		 return $a cmp $b;
                    725: 	     } (keys(%$fullname))) {
1.44      ng        726: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  727: 	foreach my $part (@$parts) {
                    728: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    729: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    730: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  731: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  732: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    733: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    734: 		if ($receiptparts) {
                    735: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    736: 		}
                    737: 		$contents.='</tr>'."\n";
                    738: 		
                    739: 		$matches++;
                    740: 	    }
1.44      ng        741: 	}
                    742:     }
                    743:     if ($matches == 0) {
                    744: 	$string = $title.'No match found for the above receipt.';
                    745:     } else {
1.324     albertel  746: 	$string = &jscriptNform($symb).$title.
1.44      ng        747: 	    'The above receipt matches the following student'.
                    748: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    749: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    750: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    751: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    752: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  753: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    754: 	if ($receiptparts) {
                    755: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    756: 	}
                    757: 	$string.='</tr>'."\n".$contents.
1.44      ng        758: 	    '</table></td></tr></table>'."\n";
                    759:     }
1.324     albertel  760:     return $string.&show_grading_menu_form($symb);
1.44      ng        761: }
                    762: 
                    763: #--- This is called by a number of programs.
                    764: #--- Called from the Grading Menu - View/Grade an individual student
                    765: #--- Also called directly when one clicks on the subm button 
                    766: #    on the problem page.
1.30      ng        767: sub listStudents {
1.41      ng        768:     my ($request) = shift;
1.49      albertel  769: 
1.324     albertel  770:     my ($symb) = &get_symb($request);
1.257     albertel  771:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    772:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    773:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449   ! banghart  774:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  775:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    776:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    777:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    778: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  779: 
1.398     albertel  780:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    781: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        782: 
1.324     albertel  783:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  784: 
1.45      ng        785:     $request->print(<<LISTJAVASCRIPT);
                    786: <script type="text/javascript" language="javascript">
1.110     ng        787:     function checkSelect(checkBox) {
                    788: 	var ctr=0;
                    789: 	var sense="";
                    790: 	if (checkBox.length > 1) {
                    791: 	    for (var i=0; i<checkBox.length; i++) {
                    792: 		if (checkBox[i].checked) {
                    793: 		    ctr++;
                    794: 		}
                    795: 	    }
                    796: 	    sense = "a student or group of students";
                    797: 	} else {
                    798: 	    if (checkBox.checked) {
                    799: 		ctr = 1;
                    800: 	    }
                    801: 	    sense = "the student";
                    802: 	}
                    803: 	if (ctr == 0) {
1.126     ng        804: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        805: 	    return false;
                    806: 	}
                    807: 	document.gradesub.submit();
                    808:     }
                    809: 
                    810:     function reLoadList(formname) {
1.112     ng        811: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        812: 	formname.command.value = 'submission';
                    813: 	formname.submit();
                    814:     }
1.45      ng        815: </script>
                    816: LISTJAVASCRIPT
                    817: 
1.118     ng        818:     &commonJSfunctions($request);
1.41      ng        819:     $request->print($result);
1.39      ng        820: 
1.401     albertel  821:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    822:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  823:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    824: 	"\n".$table.
1.401     albertel  825: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  826: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    827: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    828: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    829: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  830: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  831: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  832:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  833: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  834:     }
1.442     banghart  835:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    836:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  837:     $env{'form.Status'} = $saveStatus;
1.267     albertel  838:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    839: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    840: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  841: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    842:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    843:         '<option value="1">Whole Points</option>'.
                    844:         '<option value=".5">Half Points</option>'.
1.349     albertel  845:         '<option value=".25">Quarter Points</option>'.
                    846:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  847:         '</select>'.
1.432     banghart  848:         &build_section_inputs().
1.45      ng        849: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  850: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    851: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    852: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    853: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  854: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        855: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    856: 
1.257     albertel  857:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  858: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        859:     } else {
                    860: 	$gradeTable.='<b>Student Status:</b> '.
                    861: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    862:     }
1.112     ng        863: 
1.126     ng        864:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    865: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        866: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  867: 
                    868: # checkall buttons
                    869:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        870:     $gradeTable.='<input type="button" '."\n".
1.45      ng        871: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  872: 	'value="Next->" /> <br />'."\n";
                    873:     $gradeTable.=&check_buttons();
1.401     albertel  874:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  875:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        876:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        877: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    878:     my $loop = 0;
                    879:     while ($loop < 2) {
1.126     ng        880: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  881: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  882: 	if ($env{'form.showgrading'} eq 'yes' 
                    883: 	    && $submitonly ne 'queued'
                    884: 	    && $submitonly ne 'all') {
1.110     ng        885: 	    foreach (sort(@$partlist)) {
1.324     albertel  886: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  887: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    888: 		    ' Status&nbsp;</b></td>';
1.110     ng        889: 	    }
1.301     albertel  890: 	} elsif ($submitonly eq 'queued') {
                    891: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        892: 	}
                    893: 	$loop++;
1.126     ng        894: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        895:     }
1.45      ng        896:     $gradeTable.='</tr>'."\n";
1.41      ng        897: 
1.45      ng        898:     my $ctr = 0;
1.294     albertel  899:     foreach my $student (sort 
                    900: 			 {
                    901: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    902: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    903: 			     }
                    904: 			     return $a cmp $b;
                    905: 			 }
                    906: 			 (keys(%$fullname))) {
1.41      ng        907: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  908: 
1.110     ng        909: 	my %status = ();
1.301     albertel  910: 
                    911: 	if ($submitonly eq 'queued') {
                    912: 	    my %queue_status = 
                    913: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    914: 							$udom,$uname);
                    915: 	    next if (!defined($queue_status{'gradingqueue'}));
                    916: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    917: 	}
                    918: 
                    919: 	if ($env{'form.showgrading'} eq 'yes' 
                    920: 	    && $submitonly ne 'queued'
                    921: 	    && $submitonly ne 'all') {
1.324     albertel  922: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  923: 	    my $submitted = 0;
1.164     albertel  924: 	    my $graded = 0;
1.248     albertel  925: 	    my $incorrect = 0;
1.110     ng        926: 	    foreach (keys(%status)) {
1.145     albertel  927: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  928: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    929: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    930: 		
1.110     ng        931: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    932: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  933: 		    $submitted = 0;
1.150     albertel  934: 		    my ($part)=split(/\./,$partid);
1.110     ng        935: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  936: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        937: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    938: 		}
1.41      ng        939: 	    }
1.248     albertel  940: 	    
1.156     albertel  941: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    942: 				     $submitonly eq 'incorrect' ||
                    943: 				     $submitonly eq 'graded'));
1.248     albertel  944: 	    next if (!$graded && ($submitonly eq 'graded'));
                    945: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        946: 	}
1.34      ng        947: 
1.45      ng        948: 	$ctr++;
1.249     albertel  949: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    950: 
1.104     albertel  951: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        952: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        953: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  954:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    955:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    956: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    957: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    958: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        959: 
1.257     albertel  960: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        961: 		foreach (sort keys(%status)) {
                    962: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  963: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        964: 		}
1.41      ng        965: 	    }
1.126     ng        966: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        967: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        968: 	}
                    969:     }
1.110     ng        970:     if ($ctr%2 ==1) {
1.126     ng        971: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  972: 	    if ($env{'form.showgrading'} eq 'yes' 
                    973: 		&& $submitonly ne 'queued'
                    974: 		&& $submitonly ne 'all') {
1.110     ng        975: 		foreach (@$partlist) {
                    976: 		    $gradeTable.='<td>&nbsp;</td>';
                    977: 		}
1.301     albertel  978: 	    } elsif ($submitonly eq 'queued') {
                    979: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        980: 	    }
                    981: 	$gradeTable.='</tr>';
                    982:     }
                    983: 
1.249     albertel  984:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        985: 	'<input type="button" '.
                    986: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        987: 	'value="Next->" /></form>'."\n";
1.45      ng        988:     if ($ctr == 0) {
1.96      albertel  989: 	my $num_students=(scalar(keys(%$fullname)));
                    990: 	if ($num_students eq 0) {
1.398     albertel  991: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  992: 	} else {
1.171     albertel  993: 	    my $submissions='submissions';
                    994: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    995: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  996: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  997: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  998: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  999: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1000: 	}
1.46      ng       1001:     } elsif ($ctr == 1) {
                   1002: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1003:     }
1.324     albertel 1004:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1005:     $request->print($gradeTable);
1.44      ng       1006:     return '';
1.10      ng       1007: }
                   1008: 
1.44      ng       1009: #---- Called from the listStudents routine
1.249     albertel 1010: 
                   1011: sub check_script {
                   1012:     my ($form, $type)=@_;
                   1013:     my $chkallscript='<script type="text/javascript">
                   1014:     function checkall() {
                   1015:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1016:             ele = document.forms.'.$form.'.elements[i];
                   1017:             if (ele.name == "'.$type.'") {
                   1018:             document.forms.'.$form.'.elements[i].checked=true;
                   1019:                                        }
                   1020:         }
                   1021:     }
                   1022: 
                   1023:     function checksec() {
                   1024:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1025:             ele = document.forms.'.$form.'.elements[i];
                   1026:            string = document.forms.'.$form.'.chksec.value;
                   1027:            if
                   1028:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1029:               document.forms.'.$form.'.elements[i].checked=true;
                   1030:             }
                   1031:         }
                   1032:     }
                   1033: 
                   1034: 
                   1035:     function uncheckall() {
                   1036:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1037:             ele = document.forms.'.$form.'.elements[i];
                   1038:             if (ele.name == "'.$type.'") {
                   1039:             document.forms.'.$form.'.elements[i].checked=false;
                   1040:                                        }
                   1041:         }
                   1042:     }
                   1043: 
                   1044: </script>'."\n";
                   1045:     return $chkallscript;
                   1046: }
                   1047: 
                   1048: sub check_buttons {
                   1049:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1050:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1051:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1052:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1053:     return $buttons;
                   1054: }
                   1055: 
1.44      ng       1056: #     Displays the submissions for one student or a group of students
1.34      ng       1057: sub processGroup {
1.41      ng       1058:     my ($request)  = shift;
                   1059:     my $ctr        = 0;
1.155     albertel 1060:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1061:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1062: 
1.396     banghart 1063:     foreach my $student (@stuchecked) {
                   1064: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1065: 	$env{'form.student'}        = $uname;
                   1066: 	$env{'form.userdom'}        = $udom;
                   1067: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1068: 	&submission($request,$ctr,$total);
                   1069: 	$ctr++;
                   1070:     }
                   1071:     return '';
1.35      ng       1072: }
1.34      ng       1073: 
1.44      ng       1074: #------------------------------------------------------------------------------------
                   1075: #
                   1076: #-------------------------- Next few routines handles grading by student, essentially
                   1077: #                           handles essay response type problem/part
                   1078: #
                   1079: #--- Javascript to handle the submission page functionality ---
                   1080: sub sub_page_js {
                   1081:     my $request = shift;
                   1082:     $request->print(<<SUBJAVASCRIPT);
                   1083: <script type="text/javascript" language="javascript">
1.71      ng       1084:     function updateRadio(formname,id,weight) {
1.125     ng       1085: 	var gradeBox = formname["GD_BOX"+id];
                   1086: 	var radioButton = formname["RADVAL"+id];
                   1087: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1088: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1089: 	gradeBox.value = pts;
                   1090: 	var resetbox = false;
                   1091: 	if (isNaN(pts) || pts < 0) {
                   1092: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1093: 	    for (var i=0; i<radioButton.length; i++) {
                   1094: 		if (radioButton[i].checked) {
                   1095: 		    gradeBox.value = i;
                   1096: 		    resetbox = true;
                   1097: 		}
                   1098: 	    }
                   1099: 	    if (!resetbox) {
                   1100: 		formtextbox.value = "";
                   1101: 	    }
                   1102: 	    return;
1.44      ng       1103: 	}
1.71      ng       1104: 
                   1105: 	if (pts > weight) {
                   1106: 	    var resp = confirm("You entered a value ("+pts+
                   1107: 			       ") greater than the weight for the part. Accept?");
                   1108: 	    if (resp == false) {
1.125     ng       1109: 		gradeBox.value = oldpts;
1.71      ng       1110: 		return;
                   1111: 	    }
1.44      ng       1112: 	}
1.13      albertel 1113: 
1.71      ng       1114: 	for (var i=0; i<radioButton.length; i++) {
                   1115: 	    radioButton[i].checked=false;
                   1116: 	    if (pts == i && pts != "") {
                   1117: 		radioButton[i].checked=true;
                   1118: 	    }
                   1119: 	}
                   1120: 	updateSelect(formname,id);
1.125     ng       1121: 	formname["stores"+id].value = "0";
1.41      ng       1122:     }
1.5       albertel 1123: 
1.72      ng       1124:     function writeBox(formname,id,pts) {
1.125     ng       1125: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1126: 	if (checkSolved(formname,id) == 'update') {
                   1127: 	    gradeBox.value = pts;
                   1128: 	} else {
1.125     ng       1129: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1130: 	    gradeBox.value = oldpts;
1.125     ng       1131: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1132: 	    for (var i=0; i<radioButton.length; i++) {
                   1133: 		radioButton[i].checked=false;
1.72      ng       1134: 		if (i == oldpts) {
1.71      ng       1135: 		    radioButton[i].checked=true;
                   1136: 		}
                   1137: 	    }
1.41      ng       1138: 	}
1.125     ng       1139: 	formname["stores"+id].value = "0";
1.71      ng       1140: 	updateSelect(formname,id);
                   1141: 	return;
1.41      ng       1142:     }
1.44      ng       1143: 
1.71      ng       1144:     function clearRadBox(formname,id) {
                   1145: 	if (checkSolved(formname,id) == 'noupdate') {
                   1146: 	    updateSelect(formname,id);
                   1147: 	    return;
                   1148: 	}
1.125     ng       1149: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1150: 	for (var i=0; i<gradeSelect.length; i++) {
                   1151: 	    if (gradeSelect[i].selected) {
                   1152: 		var selectx=i;
                   1153: 	    }
                   1154: 	}
1.125     ng       1155: 	var stores = formname["stores"+id];
1.71      ng       1156: 	if (selectx == stores.value) { return };
1.125     ng       1157: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1158: 	gradeBox.value = "";
1.125     ng       1159: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1160: 	for (var i=0; i<radioButton.length; i++) {
                   1161: 	    radioButton[i].checked=false;
                   1162: 	}
                   1163: 	stores.value = selectx;
                   1164:     }
1.5       albertel 1165: 
1.71      ng       1166:     function checkSolved(formname,id) {
1.125     ng       1167: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1168: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1169: 	    if (!reply) {return "noupdate";}
1.120     ng       1170: 	    formname.overRideScore.value = 'yes';
1.41      ng       1171: 	}
1.71      ng       1172: 	return "update";
1.13      albertel 1173:     }
1.71      ng       1174: 
                   1175:     function updateSelect(formname,id) {
1.125     ng       1176: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1177: 	return;
1.41      ng       1178:     }
1.33      ng       1179: 
1.121     ng       1180: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1181:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1182: 	formname.gradeOpt.value = val;
1.71      ng       1183: 	if (val == "Save & Next") {
                   1184: 	    for (i=0;i<=total;i++) {
                   1185: 		for (j=0;j<parttot;j++) {
1.125     ng       1186: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1187: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1188: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1189: 			if (points == "") {
1.125     ng       1190: 			    var name = formname["name"+i].value;
1.129     ng       1191: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1192: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1193: 					       ", part "+partid+". Continue?");
1.71      ng       1194: 			    if (resp == false) {
1.125     ng       1195: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1196: 				return false;
                   1197: 			    }
                   1198: 			}
                   1199: 		    }
                   1200: 		    
                   1201: 		}
                   1202: 	    }
                   1203: 	    
                   1204: 	}
1.121     ng       1205: 	if (val == "Grade Student") {
                   1206: 	    formname.showgrading.value = "yes";
                   1207: 	    if (formname.Status.value == "") {
                   1208: 		formname.Status.value = "Active";
                   1209: 	    }
                   1210: 	    formname.studentNo.value = total;
                   1211: 	}
1.120     ng       1212: 	formname.submit();
                   1213:     }
                   1214: 
1.71      ng       1215: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1216:     function checkSubmitPage(formname,total) {
                   1217: 	noscore = new Array(100);
                   1218: 	var ptr = 0;
                   1219: 	for (i=1;i<total;i++) {
1.125     ng       1220: 	    var partid = formname["q_"+i].value;
1.127     ng       1221: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1222: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1223: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1224: 		if (points == "" && status != "correct_by_student") {
                   1225: 		    noscore[ptr] = i;
                   1226: 		    ptr++;
                   1227: 		}
                   1228: 	    }
                   1229: 	}
                   1230: 	if (ptr != 0) {
                   1231: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1232: 	    var prolist = "";
                   1233: 	    if (ptr == 1) {
                   1234: 		prolist = noscore[0];
                   1235: 	    } else {
                   1236: 		var i = 0;
                   1237: 		while (i < ptr-1) {
                   1238: 		    prolist += noscore[i]+", ";
                   1239: 		    i++;
                   1240: 		}
                   1241: 		prolist += "and "+noscore[i];
                   1242: 	    }
                   1243: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1244: 	    if (resp == false) {
                   1245: 		return false;
                   1246: 	    }
                   1247: 	}
1.45      ng       1248: 
1.71      ng       1249: 	formname.submit();
                   1250:     }
                   1251: </script>
                   1252: SUBJAVASCRIPT
                   1253: }
1.45      ng       1254: 
1.71      ng       1255: #--- javascript for essay type problem --
                   1256: sub sub_page_kw_js {
                   1257:     my $request = shift;
1.80      ng       1258:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1259:     &commonJSfunctions($request);
1.350     albertel 1260: 
1.351     albertel 1261:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1262:     <script text="text/javascript">
                   1263:     function checkInput() {
                   1264:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1265:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1266:       var usrctr = document.msgcenter.usrctr.value;
                   1267:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1268:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1269: 
                   1270:       var msgchk = "";
                   1271:       if (document.msgcenter.subchk.checked) {
                   1272:          msgchk = "msgsub,";
                   1273:       }
                   1274:       var includemsg = 0;
                   1275:       for (var i=1; i<=nmsg; i++) {
                   1276:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1277:           var frmmsg = document.msgcenter["msg"+i];
                   1278:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1279:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1280:           showflg.value = "1";
                   1281:           var chkbox = document.msgcenter["msgn"+i];
                   1282:           if (chkbox.checked) {
                   1283:              msgchk += "savemsg"+i+",";
                   1284:              includemsg = 1;
                   1285:           }
                   1286:       }
                   1287:       if (document.msgcenter.newmsgchk.checked) {
                   1288:          msgchk += "newmsg"+usrctr;
                   1289:          includemsg = 1;
                   1290:       }
                   1291:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1292:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1293:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1294:       includemsg.value = msgchk;
                   1295: 
                   1296:       self.close()
                   1297: 
                   1298:     }
                   1299:     </script>
                   1300: INNERJS
                   1301: 
1.351     albertel 1302:     my $inner_js_highlight_central=<<INNERJS;
                   1303:  <script type="text/javascript">
                   1304:     function updateChoice(flag) {
                   1305:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1306:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1307:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1308:       opener.document.SCORE.refresh.value = "on";
                   1309:       if (opener.document.SCORE.keywords.value!=""){
                   1310:          opener.document.SCORE.submit();
                   1311:       }
                   1312:       self.close()
                   1313:     }
                   1314: </script>
                   1315: INNERJS
                   1316: 
                   1317:     my $start_page_msg_central = 
                   1318:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1319: 				       {'js_ready'  => 1,
                   1320: 					'only_body' => 1,
                   1321: 					'bgcolor'   =>'#FFFFFF',});
                   1322:     my $end_page_msg_central = 
                   1323: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1324: 
                   1325: 
                   1326:     my $start_page_highlight_central = 
                   1327:         &Apache::loncommon::start_page('Highlight Central',
                   1328: 				       $inner_js_highlight_central,
1.350     albertel 1329: 				       {'js_ready'  => 1,
                   1330: 					'only_body' => 1,
                   1331: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1332:     my $end_page_highlight_central = 
1.350     albertel 1333: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1334: 
1.219     www      1335:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1336:     $docopen=~s/^document\.//;
1.71      ng       1337:     $request->print(<<SUBJAVASCRIPT);
                   1338: <script type="text/javascript" language="javascript">
1.45      ng       1339: 
1.44      ng       1340: //===================== Show list of keywords ====================
1.122     ng       1341:   function keywords(formname) {
                   1342:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1343:     if (nret==null) return;
1.122     ng       1344:     formname.keywords.value = nret;
1.44      ng       1345: 
1.122     ng       1346:     if (formname.keywords.value != "") {
1.128     ng       1347: 	formname.refresh.value = "on";
1.122     ng       1348: 	formname.submit();
1.44      ng       1349:     }
                   1350:     return;
                   1351:   }
                   1352: 
                   1353: //===================== Script to view submitted by ==================
                   1354:   function viewSubmitter(submitter) {
                   1355:     document.SCORE.refresh.value = "on";
                   1356:     document.SCORE.NCT.value = "1";
                   1357:     document.SCORE.unamedom0.value = submitter;
                   1358:     document.SCORE.submit();
                   1359:     return;
                   1360:   }
                   1361: 
                   1362: //===================== Script to add keyword(s) ==================
                   1363:   function getSel() {
                   1364:     if (document.getSelection) txt = document.getSelection();
                   1365:     else if (document.selection) txt = document.selection.createRange().text;
                   1366:     else return;
                   1367:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1368:     if (cleantxt=="") {
1.46      ng       1369: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1370: 	return;
                   1371:     }
                   1372:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1373:     if (nret==null) return;
1.127     ng       1374:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1375:     if (document.SCORE.keywords.value != "") {
1.127     ng       1376: 	document.SCORE.refresh.value = "on";
1.44      ng       1377: 	document.SCORE.submit();
                   1378:     }
                   1379:     return;
                   1380:   }
                   1381: 
                   1382: //====================== Script for composing message ==============
1.80      ng       1383:    // preload images
                   1384:    img1 = new Image();
                   1385:    img1.src = "$iconpath/mailbkgrd.gif";
                   1386:    img2 = new Image();
                   1387:    img2.src = "$iconpath/mailto.gif";
                   1388: 
1.44      ng       1389:   function msgCenter(msgform,usrctr,fullname) {
                   1390:     var Nmsg  = msgform.savemsgN.value;
                   1391:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1392:     var subject = msgform.msgsub.value;
1.127     ng       1393:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1394:     re = /msgsub/;
                   1395:     var shwsel = "";
                   1396:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1397:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1398:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1399:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1400: 	var testmsg = "savemsg"+i+",";
                   1401: 	re = new RegExp(testmsg,"g");
1.44      ng       1402: 	shwsel = "";
                   1403: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1404: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1405: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1406: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1407: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1408:     }
1.125     ng       1409:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1410:     shwsel = "";
                   1411:     re = /newmsg/;
                   1412:     if (re.test(msgchk)) { shwsel = "checked" }
                   1413:     newMsg(newmsg,shwsel);
                   1414:     msgTail(); 
                   1415:     return;
                   1416:   }
                   1417: 
1.123     ng       1418:   function checkEntities(strx) {
                   1419:     if (strx.length == 0) return strx;
                   1420:     var orgStr = ["&", "<", ">", '"']; 
                   1421:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1422:     var counter = 0;
                   1423:     while (counter < 4) {
                   1424: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1425: 	counter++;
                   1426:     }
                   1427:     return strx;
                   1428:   }
                   1429: 
                   1430:   function strReplace(strx, orgStr, newStr) {
                   1431:     return strx.split(orgStr).join(newStr);
                   1432:   }
                   1433: 
1.44      ng       1434:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1435:     var height = 70*Nmsg+250;
1.44      ng       1436:     var scrollbar = "no";
                   1437:     if (height > 600) {
                   1438: 	height = 600;
                   1439: 	scrollbar = "yes";
                   1440:     }
1.118     ng       1441:     var xpos = (screen.width-600)/2;
                   1442:     xpos = (xpos < 0) ? '0' : xpos;
                   1443:     var ypos = (screen.height-height)/2-30;
                   1444:     ypos = (ypos < 0) ? '0' : ypos;
                   1445: 
1.206     albertel 1446:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1447:     pWin.focus();
                   1448:     pDoc = pWin.document;
1.219     www      1449:     pDoc.$docopen;
1.351     albertel 1450:     pDoc.write('$start_page_msg_central');
1.76      ng       1451: 
                   1452:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1453:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1454:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1455: 
                   1456:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1457:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1458:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1459: }
                   1460:     function displaySubject(msg,shwsel) {
1.76      ng       1461:     pDoc = pWin.document;
                   1462:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1463:     pDoc.write("<td>Subject</td>");
                   1464:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1465:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1466: }
                   1467: 
1.72      ng       1468:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1469:     pDoc = pWin.document;
                   1470:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1471:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1472:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1473:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1474: }
                   1475: 
                   1476:   function newMsg(newmsg,shwsel) {
1.76      ng       1477:     pDoc = pWin.document;
                   1478:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1479:     pDoc.write("<td align=\\"center\\">New</td>");
                   1480:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1481:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1482: }
                   1483: 
                   1484:   function msgTail() {
1.76      ng       1485:     pDoc = pWin.document;
                   1486:     pDoc.write("</table>");
                   1487:     pDoc.write("</td></tr></table>&nbsp;");
                   1488:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1489:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1490:     pDoc.write("</form>");
1.351     albertel 1491:     pDoc.write('$end_page_msg_central');
1.128     ng       1492:     pDoc.close();
1.44      ng       1493: }
                   1494: 
                   1495: //====================== Script for keyword highlight options ==============
                   1496:   function kwhighlight() {
                   1497:     var kwclr    = document.SCORE.kwclr.value;
                   1498:     var kwsize   = document.SCORE.kwsize.value;
                   1499:     var kwstyle  = document.SCORE.kwstyle.value;
                   1500:     var redsel = "";
                   1501:     var grnsel = "";
                   1502:     var blusel = "";
                   1503:     if (kwclr=="red")   {var redsel="checked"};
                   1504:     if (kwclr=="green") {var grnsel="checked"};
                   1505:     if (kwclr=="blue")  {var blusel="checked"};
                   1506:     var sznsel = "";
                   1507:     var sz1sel = "";
                   1508:     var sz2sel = "";
                   1509:     if (kwsize=="0")  {var sznsel="checked"};
                   1510:     if (kwsize=="+1") {var sz1sel="checked"};
                   1511:     if (kwsize=="+2") {var sz2sel="checked"};
                   1512:     var synsel = "";
                   1513:     var syisel = "";
                   1514:     var sybsel = "";
                   1515:     if (kwstyle=="")    {var synsel="checked"};
                   1516:     if (kwstyle=="<i>") {var syisel="checked"};
                   1517:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1518:     highlightCentral();
                   1519:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1520:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1521:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1522:     highlightend();
                   1523:     return;
                   1524:   }
                   1525: 
                   1526:   function highlightCentral() {
1.76      ng       1527: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1528:     var xpos = (screen.width-400)/2;
                   1529:     xpos = (xpos < 0) ? '0' : xpos;
                   1530:     var ypos = (screen.height-330)/2-30;
                   1531:     ypos = (ypos < 0) ? '0' : ypos;
                   1532: 
1.206     albertel 1533:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1534:     hwdWin.focus();
                   1535:     var hDoc = hwdWin.document;
1.219     www      1536:     hDoc.$docopen;
1.351     albertel 1537:     hDoc.write('$start_page_highlight_central');
1.76      ng       1538:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1539:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1540: 
                   1541:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1542:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1543:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1544:   }
                   1545: 
                   1546:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1547:     var hDoc = hwdWin.document;
                   1548:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1549:     hDoc.write("<td align=\\"left\\">");
                   1550:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1551:     hDoc.write("<td align=\\"left\\">");
                   1552:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1553:     hDoc.write("<td align=\\"left\\">");
                   1554:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1555:     hDoc.write("</tr>");
1.44      ng       1556:   }
                   1557: 
                   1558:   function highlightend() { 
1.76      ng       1559:     var hDoc = hwdWin.document;
                   1560:     hDoc.write("</table>");
                   1561:     hDoc.write("</td></tr></table>&nbsp;");
                   1562:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1563:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1564:     hDoc.write("</form>");
1.351     albertel 1565:     hDoc.write('$end_page_highlight_central');
1.128     ng       1566:     hDoc.close();
1.44      ng       1567:   }
                   1568: 
                   1569: </script>
                   1570: SUBJAVASCRIPT
                   1571: }
                   1572: 
1.349     albertel 1573: sub get_increment {
1.348     bowersj2 1574:     my $increment = $env{'form.increment'};
                   1575:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1576:         $increment != .1) {
                   1577:         $increment = 1;
                   1578:     }
                   1579:     return $increment;
                   1580: }
                   1581: 
1.71      ng       1582: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1583: sub gradeBox {
1.322     albertel 1584:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1585:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1586: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1587: 	'/check.gif" height="16" border="0" />';
                   1588:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1589:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1590: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1591:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1592:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1593: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1594:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1595:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1596:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1597: 				       [$partid]);
                   1598:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1599:     if ($last_resets{$partid}) {
                   1600:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1601:     }
1.71      ng       1602:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1603: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1604:     my $ctr = 0;
1.348     bowersj2 1605:     my $thisweight = 0;
1.349     albertel 1606:     my $increment = &get_increment();
1.71      ng       1607:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1608:     while ($thisweight<=$wgt) {
1.381     albertel 1609: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1610: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1611: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1612: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1613: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1614:         $thisweight += $increment;
1.71      ng       1615: 	$ctr++;
                   1616:     }
                   1617:     $result.='</tr></table>';
                   1618:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1619:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1620: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1621: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1622: 	$wgt.')" /></td>'."\n";
                   1623:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1624: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1625: 	' </td><td>'."\n";
                   1626:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1627: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1628:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1629: 	$result.='<option></option>'.
1.401     albertel 1630: 	    '<option selected="selected">excused</option>';
1.71      ng       1631:     } else {
1.401     albertel 1632: 	$result.='<option selected="selected"></option>'.
1.125     ng       1633: 	    '<option>excused</option>';
1.71      ng       1634:     }
1.125     ng       1635:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1636:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1637:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1638: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1639: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1640: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1641:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1642:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1643:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1644:         $aggtries.'" />'."\n";
1.71      ng       1645:     $result.='</td></tr></table>'."\n";
1.323     banghart 1646:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1647:     return $result;
                   1648: }
1.322     albertel 1649: 
                   1650: sub handback_box {
1.323     banghart 1651:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1652:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1653:     my (@respids);
1.375     albertel 1654:      my @part_response_id = &flatten_responseType($responseType);
                   1655:     foreach my $part_response_id (@part_response_id) {
                   1656:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1657:         if ($part eq $partid) {
1.375     albertel 1658:             push(@respids,$resp);
1.323     banghart 1659:         }
                   1660:     }
1.318     banghart 1661:     my $result;
1.323     banghart 1662:     foreach my $respid (@respids) {
1.322     albertel 1663: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1664: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1665: 	next if (!@$files);
                   1666: 	my $file_counter = 1;
1.313     banghart 1667: 	foreach my $file (@$files) {
1.368     banghart 1668: 	    if ($file =~ /\/portfolio\//) {
                   1669:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1670:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1671:     	        $file_disp = "$name.$ext";
                   1672:     	        $file = $file_path.$file_disp;
                   1673:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1674:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1675:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1676:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1677:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1678:     	        $file_counter++;
                   1679: 	    }
1.322     albertel 1680: 	}
1.313     banghart 1681:     }
1.318     banghart 1682:     return $result;    
1.71      ng       1683: }
1.44      ng       1684: 
1.58      albertel 1685: sub show_problem {
1.382     albertel 1686:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1687:     my $rendered;
1.382     albertel 1688:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1689:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1690:     if ($mode eq 'both' or $mode eq 'text') {
                   1691: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1692: 						       $env{'request.course.id'},
                   1693: 						       undef,\%form);
1.144     albertel 1694:     }
1.58      albertel 1695:     if ($removeform) {
                   1696: 	$rendered=~s|<form(.*?)>||g;
                   1697: 	$rendered=~s|</form>||g;
1.374     albertel 1698: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1699:     }
1.144     albertel 1700:     my $companswer;
                   1701:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1702: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1703: 	$companswer=
                   1704: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1705: 						    $env{'request.course.id'},
                   1706: 						    %form);
1.144     albertel 1707:     }
1.58      albertel 1708:     if ($removeform) {
                   1709: 	$companswer=~s|<form(.*?)>||g;
                   1710: 	$companswer=~s|</form>||g;
1.144     albertel 1711: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1712:     }
                   1713:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1714:     $result.='<table border="0" width="100%">';
1.144     albertel 1715:     if ($viewon) {
                   1716: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1717: 	if ($mode eq 'both' or $mode eq 'text') {
                   1718: 	    $result.='View of the problem - ';
                   1719: 	} else {
                   1720: 	    $result.='Correct answer: ';
                   1721: 	}
1.257     albertel 1722: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1723:     }
                   1724:     if ($mode eq 'both') {
                   1725: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1726: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1727:     } elsif ($mode eq 'text') {
                   1728: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1729:     } elsif ($mode eq 'answer') {
                   1730: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1731:     }
1.58      albertel 1732:     $result.='</td></tr></table>';
                   1733:     $result.='</td></tr></table><br />';
1.71      ng       1734:     return $result;
1.58      albertel 1735: }
1.397     albertel 1736: 
1.396     banghart 1737: sub files_exist {
                   1738:     my ($r, $symb) = @_;
                   1739:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1740: 
1.396     banghart 1741:     foreach my $student (@students) {
                   1742:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1743:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1744: 					      $udom,$uname);
1.396     banghart 1745:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1746:         foreach my $submission (@$string) {
                   1747:             my ($partid,$respid) =
                   1748: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1749:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1750: 					   \%record);
                   1751:             return 1 if (@$files);
1.396     banghart 1752:         }
                   1753:     }
1.397     albertel 1754:     return 0;
1.396     banghart 1755: }
1.397     albertel 1756: 
1.394     banghart 1757: sub download_all_link {
                   1758:     my ($r,$symb) = @_;
1.395     albertel 1759:     my $all_students = 
                   1760: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1761: 
                   1762:     my $parts =
                   1763: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1764: 
1.394     banghart 1765:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1766:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1767:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1768:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1769:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1770: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1771:     return
                   1772: }
1.395     albertel 1773: 
1.432     banghart 1774: sub build_section_inputs {
                   1775:     my $section_inputs;
                   1776:     if ($env{'form.section'} eq '') {
                   1777:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1778:     } else {
                   1779:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1780:         foreach my $section (@sections) {
1.432     banghart 1781:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1782:         }
                   1783:     }
                   1784:     return $section_inputs;
                   1785: }
                   1786: 
1.44      ng       1787: # --------------------------- show submissions of a student, option to grade 
                   1788: sub submission {
                   1789:     my ($request,$counter,$total) = @_;
1.257     albertel 1790:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1791:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1792:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1793:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1794:     my $symb = &get_symb($request); 
                   1795:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1796: 
                   1797:     if (!&canview($usec)) {
1.398     albertel 1798: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1799: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1800: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1801: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1802: 	return;
                   1803:     }
                   1804: 
1.257     albertel 1805:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1806:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1807:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1808:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1809:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1810: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1811: 	'/check.gif" height="16" border="0" />';
1.41      ng       1812: 
1.426     albertel 1813:     my %old_essays;
1.41      ng       1814:     # header info
                   1815:     if ($counter == 0) {
                   1816: 	&sub_page_js($request);
1.257     albertel 1817: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1818: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1819: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1820: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1821: 	    &download_all_link($request, $symb);
                   1822: 	}
1.398     albertel 1823: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1824: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1825: 
1.257     albertel 1826: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1827: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1828: 		$checkIcon.' symbol.'."\n";
                   1829: 	    $request->print($checkMark);
                   1830: 	}
1.41      ng       1831: 
1.44      ng       1832: 	# option to display problem, only once else it cause problems 
                   1833:         # with the form later since the problem has a form.
1.257     albertel 1834: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1835: 	    my $mode;
1.257     albertel 1836: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1837: 		$mode='both';
1.257     albertel 1838: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1839: 		$mode='text';
1.257     albertel 1840: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1841: 		$mode='answer';
                   1842: 	    }
1.329     albertel 1843: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1844: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1845: 	}
1.441     www      1846: 
1.44      ng       1847: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1848:         # if this subroutine has been called once.
1.41      ng       1849: 	my %keyhash = ();
1.257     albertel 1850: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1851: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1852: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1853: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1854: 
1.257     albertel 1855: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1856: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1857: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1858: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1859: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1860: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1861: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1862: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1863: 	}
1.257     albertel 1864: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1865: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1866: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1867: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1868: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1869: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1870: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1871: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1872: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1873: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1874: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1875: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1876: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1877: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1878: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1879: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1880: 			&build_section_inputs().
1.326     albertel 1881: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1882: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1883: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1884: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1885: 	if ($env{'form.handgrade'} eq 'yes') {
                   1886: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1887: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1888: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1889: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1890: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1891: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1892: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1893: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1894: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1895: 	    }
1.123     ng       1896: 	}
1.41      ng       1897: 	
                   1898: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1899: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1900: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1901: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1902: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1903: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1904: 		'" />'."\n".
                   1905: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1906: 	    $cts++;
                   1907: 	}
                   1908: 	$request->print($prnmsg);
1.32      ng       1909: 
1.257     albertel 1910: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1911: #
                   1912: # Print out the keyword options line
                   1913: #
1.41      ng       1914: 	    $request->print(<<KEYWORDS);
1.38      ng       1915: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1916: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1917: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1918:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1919: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1920: KEYWORDS
1.88      www      1921: #
                   1922: # Load the other essays for similarity check
                   1923: #
1.324     albertel 1924:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1925: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1926: 	    $apath=&escape($apath);
1.88      www      1927: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1928: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1929:         }
                   1930:     }
1.44      ng       1931: 
1.441     www      1932: # This is where output for one specific student would start
                   1933:     my $bgcolor='#DDEEDD';
                   1934:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1935:     $request->print("\n\n".
                   1936:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1937: 
1.257     albertel 1938:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1939: 	my $mode;
1.257     albertel 1940: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1941: 	    $mode='both';
1.257     albertel 1942: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1943: 	    $mode='text';
1.257     albertel 1944: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1945: 	    $mode='answer';
                   1946: 	}
1.329     albertel 1947: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1948: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1949:     }
1.144     albertel 1950: 
1.257     albertel 1951:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1952:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1953: 
1.44      ng       1954:     # Display student info
1.41      ng       1955:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1956:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1957: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1958: 
1.257     albertel 1959:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1960:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1961: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1962: 
1.118     ng       1963:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1964:     my @col_fullnames;
1.56      matthew  1965:     my ($classlist,$fullname);
1.257     albertel 1966:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1967: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1968: 	for (keys (%$handgrade)) {
1.44      ng       1969: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1970: 					    '.maxcollaborators',
                   1971:                                             $symb,$udom,$uname);
                   1972: 	    next if ($ncol <= 0);
                   1973:             s/\_/\./g;
                   1974:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1975:             my @goodcollaborators = ();
                   1976:             my @badcollaborators  = ();
                   1977: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1978: 		$_ =~ s/[\$\^\(\)]//g;
                   1979: 		next if ($_ eq '');
1.80      ng       1980: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1981: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1982: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1983: 		# Doing this grep allows 'fuzzy' specification
                   1984: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1985: 		if (! scalar(@Matches)) {
                   1986: 		    push @badcollaborators,$_;
                   1987: 		} else {
                   1988: 		    push @goodcollaborators, @Matches;
                   1989: 		}
1.80      ng       1990: 	    }
1.86      ng       1991:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1992:                 $result.='<b>Collaborators: </b>';
1.86      ng       1993:                 foreach (@goodcollaborators) {
                   1994: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1995: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1996: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1997: 		}
1.57      matthew  1998:                 $result.='<br />'."\n";
1.150     albertel 1999: 		my ($part)=split(/\./,$_);
1.86      ng       2000: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 2001: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2002: 		    "\n";
1.86      ng       2003: 	    }
                   2004: 	    if (scalar(@badcollaborators) > 0) {
                   2005: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2006: 		$result.='This student has submitted ';
                   2007: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2008: 		$result .= ': '.join(', ',@badcollaborators);
                   2009: 		$result .= '</td></tr></table>';
                   2010: 	    }         
                   2011: 	    if (scalar(@badcollaborators > $ncol)) {
                   2012: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2013: 		$result .= 'This student has submitted too many '.
                   2014: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2015: 		$result .= '</td></tr></table>';
                   2016: 	    }
1.41      ng       2017: 	}
                   2018:     }
1.44      ng       2019:     $request->print($result."\n");
1.33      ng       2020: 
1.44      ng       2021:     # print student answer/submission
                   2022:     # Options are (1) Handgaded submission only
                   2023:     #             (2) Last submission, includes submission that is not handgraded 
                   2024:     #                  (for multi-response type part)
                   2025:     #             (3) Last submission plus the parts info
                   2026:     #             (4) The whole record for this student
1.257     albertel 2027:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2028: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2029: 	my $lastsubonly=''.
                   2030: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2031: 	     $$timestamp)."</td></tr>\n";
                   2032: 	if ($$timestamp eq '') {
                   2033: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2034: 	} else {
                   2035: 	    my %seenparts;
1.375     albertel 2036: 	    my @part_response_id = &flatten_responseType($responseType);
                   2037: 	    foreach my $part (@part_response_id) {
1.393     albertel 2038: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2039: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2040: 
1.375     albertel 2041: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2042: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2043: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2044: 		    if (exists($seenparts{$partid})) { next; }
                   2045: 		    $seenparts{$partid}=1;
1.207     albertel 2046: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2047: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2048: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2049: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2050: 			'\');" target="_self">'.
1.257     albertel 2051: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2052: 		    $request->print($submitby);
                   2053: 		    next;
                   2054: 		}
                   2055: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2056: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2057: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2058: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2059: 			' )</span>&nbsp; &nbsp;'.
                   2060: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2061: 		    next;
                   2062: 		}
                   2063: 		foreach (@$string) {
                   2064: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2065: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2066: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2067: 		    # Similarity check
                   2068: 		    my $similar='';
1.257     albertel 2069: 		    if($env{'form.checkPlag'}){
1.151     albertel 2070: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2071: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2072: 			if ($osim) {
                   2073: 			    $osim=int($osim*100.0);
1.426     albertel 2074: 			    my %old_course_desc = 
                   2075: 				&Apache::lonnet::coursedescription($ocrsid,
                   2076: 								   {'one_time' => 1});
                   2077: 
                   2078: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2079: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2080: 				    $osim,
                   2081: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2082: 				    $oname,$odom,
1.426     albertel 2083: 				    $old_course_desc{'description'},
1.427     albertel 2084: 				    $old_course_desc{'num'},
1.426     albertel 2085: 				    $old_course_desc{'domain'}).
1.398     albertel 2086: 				'</span></h3><blockquote><i>'.
1.151     albertel 2087: 				&keywords_highlight($oessay).
                   2088: 				'</i></blockquote><hr />';
                   2089: 			}
1.150     albertel 2090: 		    }
1.151     albertel 2091: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2092: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2093: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2094: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2095: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2096: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2097: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2098: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2099: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2100: 			if (@$files) {
1.398     albertel 2101: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2102: 			    my $file_counter = 0;
1.313     banghart 2103: 			    foreach my $file (@$files) {
1.303     banghart 2104: 			        $file_counter ++;
1.232     albertel 2105: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2106: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2107: 			    }
1.236     albertel 2108: 			    $lastsubonly.='<br />';
1.41      ng       2109: 			}
1.151     albertel 2110: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2111: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2112: 					 $respid,\%record,$order);
                   2113: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2114: 		    }
                   2115: 		}
                   2116: 	    }
1.151     albertel 2117: 	}
                   2118: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2119: 	$request->print($lastsubonly);
1.257     albertel 2120:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2121: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2122: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2123:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2124: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2125: 								 $env{'request.course.id'},
1.44      ng       2126: 								 $last,'.submission',
                   2127: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2128:     }
1.120     ng       2129: 
1.121     ng       2130:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2131: 	.$udom.'" />'."\n");
1.41      ng       2132:     
1.44      ng       2133:     # return if view submission with no grading option
1.257     albertel 2134:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2135: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2136: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2137: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2138: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2139: 	if (($env{'form.command'} eq 'submission') || 
                   2140: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2141: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2142: 	}
1.180     albertel 2143: 	$request->print($toGrade);
1.41      ng       2144: 	return;
1.180     albertel 2145:     } else {
                   2146: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2147:     }
1.33      ng       2148: 
1.121     ng       2149:     # essay grading message center
1.257     albertel 2150:     if ($env{'form.handgrade'} eq 'yes') {
                   2151: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2152: 	my $msgfor = $givenn.' '.$lastname;
                   2153: 	if (scalar(@col_fullnames) > 0) {
                   2154: 	    my $lastone = pop @col_fullnames;
                   2155: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2156: 	}
                   2157: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2158: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2159: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2160: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2161: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2162: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2163: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2164: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2165: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2166: 	    '<br />&nbsp;('.
                   2167: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2168: 	$request->print($result);
1.118     ng       2169:     }
1.300     albertel 2170:     if ($perm{'vgr'}) {
1.297     www      2171: 	$request->print('<br />'.
1.300     albertel 2172: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2173: 						   $uname,$udom,'check'));
1.297     www      2174:     }
1.300     albertel 2175:     if ($perm{'opa'}) {
1.297     www      2176: 	$request->print('<br />'.
1.300     albertel 2177: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2178: 					 $uname,$udom,$symb,'check'));
1.297     www      2179:     }
1.41      ng       2180: 
                   2181:     my %seen = ();
                   2182:     my @partlist;
1.129     ng       2183:     my @gradePartRespid;
1.375     albertel 2184:     my @part_response_id = &flatten_responseType($responseType);
                   2185:     foreach my $part_response_id (@part_response_id) {
                   2186:     	my ($partid,$respid) = @{ $part_response_id };
                   2187: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2188: 	next if ($seen{$partid} > 0);
1.41      ng       2189: 	$seen{$partid}++;
1.393     albertel 2190: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2191: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2192: 	push @partlist,$partid;
1.129     ng       2193: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2194: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2195:     }
1.45      ng       2196:     $result='<input type="hidden" name="partlist'.$counter.
                   2197: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2198:     $result.='<input type="hidden" name="gradePartRespid'.
                   2199: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2200:     my $ctr = 0;
                   2201:     while ($ctr < scalar(@partlist)) {
                   2202: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2203: 	    $partlist[$ctr].'" />'."\n";
                   2204: 	$ctr++;
                   2205:     }
                   2206:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2207: 
1.441     www      2208: # Done with printing info for one student
                   2209: 
                   2210:     $request->print('</td></tr></table></p>');
                   2211: 
                   2212: 
1.41      ng       2213:     # print end of form
                   2214:     if ($counter == $total) {
1.297     www      2215: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2216: 	$endform.='<input type="button" value="Save & Next" '.
                   2217: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2218: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2219: 	my $ntstu ='<select name="NTSTU">'.
                   2220: 	    '<option>1</option><option>2</option>'.
                   2221: 	    '<option>3</option><option>5</option>'.
                   2222: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2223: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2224: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2225: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2226: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2227: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2228: 	    '<input type="button" value="Next" '.
1.417     albertel 2229: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2230: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2231:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2232:             "' name='increment' />";
1.45      ng       2233: 	$endform.='</td><tr></table></form>';
1.324     albertel 2234: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2235: 	$request->print($endform);
                   2236:     }
                   2237:     return '';
1.38      ng       2238: }
                   2239: 
1.44      ng       2240: #--- Retrieve the last submission for all the parts
1.38      ng       2241: sub get_last_submission {
1.119     ng       2242:     my ($returnhash)=@_;
1.46      ng       2243:     my (@string,$timestamp);
1.119     ng       2244:     if ($$returnhash{'version'}) {
1.46      ng       2245: 	my %lasthash=();
                   2246: 	my ($version);
1.119     ng       2247: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2248: 	    foreach my $key (sort(split(/\:/,
                   2249: 					$$returnhash{$version.':keys'}))) {
                   2250: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2251: 		$timestamp = 
                   2252: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2253: 	    }
                   2254: 	}
1.397     albertel 2255: 	foreach my $key (keys(%lasthash)) {
                   2256: 	    next if ($key !~ /\.submission$/);
                   2257: 
                   2258: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2259: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2260: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2261: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2262: 	}
                   2263:     }
1.397     albertel 2264:     if (!@string) {
                   2265: 	$string[0] =
1.398     albertel 2266: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2267:     }
                   2268:     return (\@string,\$timestamp);
1.38      ng       2269: }
1.35      ng       2270: 
1.44      ng       2271: #--- High light keywords, with style choosen by user.
1.38      ng       2272: sub keywords_highlight {
1.44      ng       2273:     my $string    = shift;
1.257     albertel 2274:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2275:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2276:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2277:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2278:     foreach my $keyword (@keylist) {
                   2279: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2280:     }
                   2281:     return $string;
1.38      ng       2282: }
1.36      ng       2283: 
1.44      ng       2284: #--- Called from submission routine
1.38      ng       2285: sub processHandGrade {
1.41      ng       2286:     my ($request) = shift;
1.324     albertel 2287:     my $symb   = &get_symb($request);
                   2288:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2289:     my $button = $env{'form.gradeOpt'};
                   2290:     my $ngrade = $env{'form.NCT'};
                   2291:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2292:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2293:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2294: 
1.44      ng       2295:     if ($button eq 'Save & Next') {
                   2296: 	my $ctr = 0;
                   2297: 	while ($ctr < $ngrade) {
1.257     albertel 2298: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2299: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2300: 	    if ($errorflag eq 'no_score') {
                   2301: 		$ctr++;
                   2302: 		next;
                   2303: 	    }
1.104     albertel 2304: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2305: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2306: 		$ctr++;
                   2307: 		next;
                   2308: 	    }
1.257     albertel 2309: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2310: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2311: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2312:             my ($feedurl,$showsymb) =
                   2313: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2314: 	    my $messagetail;
1.62      albertel 2315: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2316: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2317: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2318: 		$subject.=' ['.$restitle.']';
1.44      ng       2319: 		my (@msgnum) = split(/,/,$includemsg);
                   2320: 		foreach (@msgnum) {
1.257     albertel 2321: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2322: 		}
1.80      ng       2323: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2324: 		if ($env{'form.withgrades'.$ctr}) {
                   2325: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2326: 		    $messagetail = " for <a href=\"".
1.418     albertel 2327: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2328: 		}
                   2329: 		$msgstatus = 
                   2330:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2331: 						     $message.$messagetail,
1.418     albertel 2332:                                                      undef,$feedurl,undef,
1.386     raeburn  2333:                                                      undef,undef,$showsymb,
                   2334:                                                      $restitle);
                   2335: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2336: 				$msgstatus);
1.44      ng       2337: 	    }
1.257     albertel 2338: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2339: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2340: 		foreach my $collabstr (@collabstrs) {
                   2341: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2342: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2343: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2344: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2345: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2346: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2347: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2348: 			    next;
1.418     albertel 2349: 			} elsif ($message ne '') {
                   2350: 			    my ($baseurl,$showsymb) = 
                   2351: 				&get_feedurl_and_symb($symb,$collaborator,
                   2352: 						      $udom);
                   2353: 			    if ($env{'form.withgrades'.$ctr}) {
                   2354: 				$messagetail = " for <a href=\"".
1.386     raeburn  2355:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2356: 			    }
1.418     albertel 2357: 			    $msgstatus = 
                   2358: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2359: 			}
1.44      ng       2360: 		    }
                   2361: 		}
                   2362: 	    }
                   2363: 	    $ctr++;
                   2364: 	}
                   2365:     }
                   2366: 
1.257     albertel 2367:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2368: 	# Keywords sorted in alphabatical order
1.257     albertel 2369: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2370: 	my %keyhash = ();
1.257     albertel 2371: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2372: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2373: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2374: 	$env{'form.keywords'} = join(' ',@keywords);
                   2375: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2376: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2377: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2378: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2379: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2380: 
                   2381: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2382: 	# New messages are saved in env for the next student.
1.119     ng       2383: 	# All messages are saved in nohist_handgrade.db
                   2384: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2385: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2386: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2387: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2388: 		$idx++;
                   2389: 	    }
                   2390: 	    $ctr++;
1.41      ng       2391: 	}
1.119     ng       2392: 	$ctr = 0;
                   2393: 	while ($ctr < $ngrade) {
1.257     albertel 2394: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2395: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2396: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2397: 		$idx++;
                   2398: 	    }
                   2399: 	    $ctr++;
1.41      ng       2400: 	}
1.257     albertel 2401: 	$env{'form.savemsgN'} = --$idx;
                   2402: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2403: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2404: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2405:     }
1.44      ng       2406:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2407:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2408:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2409: 	my ($ctr,$total) = (0,0);
                   2410: 	while ($ctr < $ngrade) {
1.257     albertel 2411: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2412: 	    $ctr++;
                   2413: 	}
1.257     albertel 2414: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2415: 	$ctr = 0;
                   2416: 	while ($ctr < $total) {
1.257     albertel 2417: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2418: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2419: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2420: 	    &submission($request,$ctr,$total-1);
1.41      ng       2421: 	    $ctr++;
                   2422: 	}
                   2423: 	return '';
                   2424:     }
1.36      ng       2425: 
1.121     ng       2426: # Go directly to grade student - from submission or link from chart page
1.120     ng       2427:     if ($button eq 'Grade Student') {
1.324     albertel 2428: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2429: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2430: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2431: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2432: 	&submission($request,0,0);
                   2433: 	return '';
                   2434:     }
                   2435: 
1.44      ng       2436:     # Get the next/previous one or group of students
1.257     albertel 2437:     my $firststu = $env{'form.unamedom0'};
                   2438:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2439:     my $ctr = 2;
1.41      ng       2440:     while ($laststu eq '') {
1.257     albertel 2441: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2442: 	$ctr++;
                   2443: 	$laststu = $firststu if ($ctr > $ngrade);
                   2444:     }
1.44      ng       2445: 
1.41      ng       2446:     my (@parsedlist,@nextlist);
                   2447:     my ($nextflg) = 0;
1.294     albertel 2448:     foreach (sort 
                   2449: 	     {
                   2450: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2451: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2452: 		 }
                   2453: 		 return $a cmp $b;
                   2454: 	     } (keys(%$fullname))) {
1.41      ng       2455: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2456: 	    push @parsedlist,$_;
                   2457: 	}
                   2458: 	$nextflg = 1 if ($_ eq $laststu);
                   2459: 	if ($button eq 'Previous') {
                   2460: 	    last if ($_ eq $firststu);
                   2461: 	    push @parsedlist,$_;
                   2462: 	}
                   2463:     }
                   2464:     $ctr = 0;
                   2465:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2466:     my ($partlist) = &response_type($symb);
1.41      ng       2467:     foreach my $student (@parsedlist) {
1.257     albertel 2468: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2469: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2470: 	
                   2471: 	if ($submitonly eq 'queued') {
                   2472: 	    my %queue_status = 
                   2473: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2474: 							$udom,$uname);
                   2475: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2476: 	}
                   2477: 
1.156     albertel 2478: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2479: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2480: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2481: 	    my $submitted = 0;
1.248     albertel 2482: 	    my $ungraded = 0;
                   2483: 	    my $incorrect = 0;
1.145     albertel 2484: 	    foreach (keys(%status)) {
                   2485: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2486: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2487: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2488: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2489: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2490: 		    $submitted = 0;
                   2491: 		}
1.41      ng       2492: 	    }
1.156     albertel 2493: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2494: 				     $submitonly eq 'incorrect' ||
                   2495: 				     $submitonly eq 'graded'));
1.248     albertel 2496: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2497: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2498: 	}
                   2499: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2500: 	last if ($ctr == $ntstu);
1.41      ng       2501: 	$ctr++;
                   2502:     }
1.36      ng       2503: 
1.41      ng       2504:     $ctr = 0;
                   2505:     my $total = scalar(@nextlist)-1;
1.39      ng       2506: 
1.41      ng       2507:     foreach (sort @nextlist) {
                   2508: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2509: 	$env{'form.student'}  = $uname;
                   2510: 	$env{'form.userdom'}  = $udom;
                   2511: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2512: 	&submission($request,$ctr,$total);
                   2513: 	$ctr++;
                   2514:     }
                   2515:     if ($total < 0) {
1.398     albertel 2516: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2517: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2518: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2519: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2520: 	$request->print($the_end);
                   2521:     }
                   2522:     return '';
1.38      ng       2523: }
1.36      ng       2524: 
1.44      ng       2525: #---- Save the score and award for each student, if changed
1.38      ng       2526: sub saveHandGrade {
1.324     albertel 2527:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2528:     my @version_parts;
1.104     albertel 2529:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2530: 					   $env{'request.course.id'});
1.104     albertel 2531:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2532:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2533:     my @parts_graded;
1.77      ng       2534:     my %newrecord  = ();
                   2535:     my ($pts,$wgt) = ('','');
1.269     raeburn  2536:     my %aggregate = ();
                   2537:     my $aggregateflag = 0;
1.301     albertel 2538:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2539:     foreach my $new_part (@parts) {
1.337     banghart 2540: 	#collaborator ($submi may vary for different parts
1.259     banghart 2541: 	if ($submitter && $new_part ne $part) { next; }
                   2542: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2543: 	if ($dropMenu eq 'excused') {
1.259     banghart 2544: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2545: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2546: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2547: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2548: 		}
1.364     banghart 2549: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2550: 	    }
1.125     ng       2551: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2552: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2553: 	    foreach my $key (keys (%record)) {
1.259     banghart 2554: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2555: 	    }
1.259     banghart 2556: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2557: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2558:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2559: 
                   2560:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2561: 					       [$new_part]);
                   2562:             my $aggtries =$totaltries;
1.269     raeburn  2563:             if ($last_resets{$new_part}) {
1.270     albertel 2564:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2565: 					   $new_part);
1.269     raeburn  2566:             }
1.270     albertel 2567: 
                   2568:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2569:             if ($aggtries > 0) {
1.327     albertel 2570:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2571:                 $aggregateflag = 1;
                   2572:             }
1.125     ng       2573: 	} elsif ($dropMenu eq '') {
1.259     banghart 2574: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2575: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2576: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2577: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2578: 		next;
                   2579: 	    }
1.259     banghart 2580: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2581: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2582: 	    my $partial= $pts/$wgt;
1.259     banghart 2583: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2584: 		#do not update score for part if not changed.
1.346     banghart 2585:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2586: 		next;
1.251     banghart 2587: 	    } else {
1.259     banghart 2588: 	        push @parts_graded, $new_part;
1.153     albertel 2589: 	    }
1.259     banghart 2590: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2591: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2592: 	    }
1.259     banghart 2593: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2594: 	    if ($partial == 0) {
1.153     albertel 2595: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2596: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2597: 		}
1.41      ng       2598: 	    } else {
1.153     albertel 2599: 		if ($record{$reckey} ne 'correct_by_override') {
                   2600: 		    $newrecord{$reckey} = 'correct_by_override';
                   2601: 		}
                   2602: 	    }	    
                   2603: 	    if ($submitter && 
1.259     banghart 2604: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2605: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2606: 	    }
1.259     banghart 2607: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2608: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2609: 	}
1.259     banghart 2610: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2611: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2612: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2613: 	        $dropMenu eq 'reset status')
                   2614: 	   {
1.342     banghart 2615: 	    push (@version_parts,$new_part);
1.259     banghart 2616: 	}
1.41      ng       2617:     }
1.301     albertel 2618:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2619:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2620: 
1.344     albertel 2621:     if (%newrecord) {
                   2622:         if (@version_parts) {
1.364     banghart 2623:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2624:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2625: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2626: 	    foreach my $new_part (@version_parts) {
                   2627: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2628: 				$new_part,\%newrecord);
                   2629: 	    }
1.259     banghart 2630:         }
1.44      ng       2631: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2632: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2633: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2634: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2635:     }
1.269     raeburn  2636:     if ($aggregateflag) {
                   2637:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2638: 			      $cdom,$cnum);
1.269     raeburn  2639:     }
1.301     albertel 2640:     return ('',$pts,$wgt);
1.36      ng       2641: }
1.322     albertel 2642: 
1.380     albertel 2643: sub check_and_remove_from_queue {
                   2644:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2645:     my @ungraded_parts;
                   2646:     foreach my $part (@{$parts}) {
                   2647: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2648: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2649: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2650: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2651: 		) {
                   2652: 	    push(@ungraded_parts, $part);
                   2653: 	}
                   2654:     }
                   2655:     if ( !@ungraded_parts ) {
                   2656: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2657: 					       $cnum,$domain,$stuname);
                   2658:     }
                   2659: }
                   2660: 
1.337     banghart 2661: sub handback_files {
                   2662:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2663:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2664:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2665: 
                   2666:     my @part_response_id = &flatten_responseType($responseType);
                   2667:     foreach my $part_response_id (@part_response_id) {
                   2668:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2669: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2670:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2671:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2672:                 my $file_counter = 1;
1.367     albertel 2673: 		my $file_msg;
1.337     banghart 2674:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2675:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2676:                     my ($directory,$answer_file) = 
                   2677:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2678:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2679: 		        &file_name_version_ext($answer_file);
1.355     banghart 2680: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2681: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2682: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2683:                     # fix file name
                   2684:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2685:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2686:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2687:             	                                $save_file_name);
1.337     banghart 2688:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2689:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2690:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2691:                     } else {
1.360     banghart 2692:                         # mark the file as read only
                   2693:                         my @files = ($save_file_name);
1.372     albertel 2694:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2695:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2696: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2697: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2698: 			}
                   2699:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2700: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2701: 
1.337     banghart 2702:                     }
                   2703:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2704:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2705:                     $file_counter++;
                   2706:                 }
1.367     albertel 2707: 		my $subject = "File Handed Back by Instructor ";
                   2708: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2709: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2710: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2711: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2712: 		my ($feedurl,$showsymb) = 
                   2713: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2714:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2715: 		my $msgstatus = 
                   2716:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2717: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2718:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2719:             }
                   2720:         }
1.338     banghart 2721:     return;
1.337     banghart 2722: }
                   2723: 
1.418     albertel 2724: sub get_feedurl_and_symb {
                   2725:     my ($symb,$uname,$udom) = @_;
                   2726:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2727:     $url = &Apache::lonnet::clutter($url);
                   2728:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2729: 					$symb,$udom,$uname);
                   2730:     if ($encrypturl =~ /^yes$/i) {
                   2731: 	&Apache::lonenc::encrypted(\$url,1);
                   2732: 	&Apache::lonenc::encrypted(\$symb,1);
                   2733:     }
                   2734:     return ($url,$symb);
                   2735: }
                   2736: 
1.313     banghart 2737: sub get_submitted_files {
                   2738:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2739:     my @files;
                   2740:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2741:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2742:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2743:     	    push(@files,$file_url.$file);
                   2744:         }
                   2745:     }
                   2746:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2747:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2748:     }
                   2749:     return (\@files);
                   2750: }
1.322     albertel 2751: 
1.269     raeburn  2752: # ----------- Provides number of tries since last reset.
                   2753: sub get_num_tries {
                   2754:     my ($record,$last_reset,$part) = @_;
                   2755:     my $timestamp = '';
                   2756:     my $num_tries = 0;
                   2757:     if ($$record{'version'}) {
                   2758:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2759:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2760:                 $timestamp = $$record{$version.':timestamp'};
                   2761:                 if ($timestamp > $last_reset) {
                   2762:                     $num_tries ++;
                   2763:                 } else {
                   2764:                     last;
                   2765:                 }
                   2766:             }
                   2767:         }
                   2768:     }
                   2769:     return $num_tries;
                   2770: }
                   2771: 
                   2772: # ----------- Determine decrements required in aggregate totals 
                   2773: sub decrement_aggs {
                   2774:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2775:     my %decrement = (
                   2776:                         attempts => 0,
                   2777:                         users => 0,
                   2778:                         correct => 0
                   2779:                     );
                   2780:     $decrement{'attempts'} = $aggtries;
                   2781:     if ($solvedstatus =~ /^correct/) {
                   2782:         $decrement{'correct'} = 1;
                   2783:     }
                   2784:     if ($aggtries == $totaltries) {
                   2785:         $decrement{'users'} = 1;
                   2786:     }
                   2787:     foreach my $type (keys (%decrement)) {
                   2788:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2789:     }
                   2790:     return;
                   2791: }
                   2792: 
                   2793: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2794: sub get_last_resets {
1.270     albertel 2795:     my ($symb,$courseid,$partids) =@_;
                   2796:     my %last_resets;
1.269     raeburn  2797:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2798:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2799:     my @keys;
                   2800:     foreach my $part (@{$partids}) {
                   2801: 	push(@keys,"$symb\0$part\0resettime");
                   2802:     }
                   2803:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2804: 				     $cdom,$cname);
                   2805:     foreach my $part (@{$partids}) {
                   2806: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2807:     }
1.270     albertel 2808:     return %last_resets;
1.269     raeburn  2809: }
                   2810: 
1.251     banghart 2811: # ----------- Handles creating versions for portfolio files as answers
                   2812: sub version_portfiles {
1.343     banghart 2813:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2814:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2815:     my @returned_keys;
1.255     banghart 2816:     my $parts = join('|', @$parts_graded);
1.359     www      2817:     my $portfolio_root = &propath($domain,$stu_name).
                   2818: 	'/userfiles/portfolio';
1.277     albertel 2819:     foreach my $key (keys(%$record)) {
1.259     banghart 2820:         my $new_portfiles;
1.263     banghart 2821:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2822:             my @versioned_portfiles;
1.367     albertel 2823:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2824:             foreach my $file (@portfiles) {
1.306     banghart 2825:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2826:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2827: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2828: 		    &file_name_version_ext($answer_file);
1.306     banghart 2829:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2830:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2831:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2832:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2833:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2834:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2835:                         [$directory.$new_answer],
1.306     banghart 2836:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2837:                 }
1.252     banghart 2838:             }
1.343     banghart 2839:             $$record{$key} = join(',',@versioned_portfiles);
                   2840:             push(@returned_keys,$key);
1.251     banghart 2841:         }
                   2842:     } 
1.343     banghart 2843:     return (@returned_keys);   
1.305     banghart 2844: }
                   2845: 
1.307     banghart 2846: sub get_next_version {
1.341     banghart 2847:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2848:     my $version;
                   2849:     foreach my $row (@$dir_list) {
                   2850:         my ($file) = split(/\&/,$row,2);
                   2851:         my ($file_name,$file_version,$file_ext) =
                   2852: 	    &file_name_version_ext($file);
                   2853:         if (($file_name eq $answer_name) && 
                   2854: 	    ($file_ext eq $answer_ext)) {
                   2855:                 # gets here if filename and extension match, regardless of version
                   2856:                 if ($file_version ne '') {
                   2857:                 # a versioned file is found  so save it for later
                   2858:                 if ($file_version > $version) {
                   2859: 		    $version = $file_version;
                   2860: 	        }
                   2861:             }
                   2862:         }
                   2863:     } 
                   2864:     $version ++;
                   2865:     return($version);
                   2866: }
                   2867: 
1.305     banghart 2868: sub version_selected_portfile {
1.306     banghart 2869:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2870:     my ($answer_name,$answer_ver,$answer_ext) =
                   2871:         &file_name_version_ext($file_name);
                   2872:     my $new_answer;
                   2873:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2874:     if($env{'form.copy'} eq '-1') {
                   2875:         $new_answer = 'problem getting file';
                   2876:     } else {
                   2877:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2878:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2879:                             $stu_name,$domain,'copy',
                   2880: 		        '/portfolio'.$directory.$new_answer);
                   2881:     }    
                   2882:     return ($new_answer);
1.251     banghart 2883: }
                   2884: 
1.304     albertel 2885: sub file_name_version_ext {
                   2886:     my ($file)=@_;
                   2887:     my @file_parts = split(/\./, $file);
                   2888:     my ($name,$version,$ext);
                   2889:     if (@file_parts > 1) {
                   2890: 	$ext=pop(@file_parts);
                   2891: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2892: 	    $version=pop(@file_parts);
                   2893: 	}
                   2894: 	$name=join('.',@file_parts);
                   2895:     } else {
                   2896: 	$name=join('.',@file_parts);
                   2897:     }
                   2898:     return($name,$version,$ext);
                   2899: }
                   2900: 
1.44      ng       2901: #--------------------------------------------------------------------------------------
                   2902: #
                   2903: #-------------------------- Next few routines handles grading by section or whole class
                   2904: #
                   2905: #--- Javascript to handle grading by section or whole class
1.42      ng       2906: sub viewgrades_js {
                   2907:     my ($request) = shift;
                   2908: 
1.41      ng       2909:     $request->print(<<VIEWJAVASCRIPT);
                   2910: <script type="text/javascript" language="javascript">
1.45      ng       2911:    function writePoint(partid,weight,point) {
1.125     ng       2912: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2913: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2914: 	if (point == "textval") {
1.125     ng       2915: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2916: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2917: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2918: 		var resetbox = false;
                   2919: 		for (var i=0; i<radioButton.length; i++) {
                   2920: 		    if (radioButton[i].checked) {
                   2921: 			textbox.value = i;
                   2922: 			resetbox = true;
                   2923: 		    }
                   2924: 		}
                   2925: 		if (!resetbox) {
                   2926: 		    textbox.value = "";
                   2927: 		}
                   2928: 		return;
                   2929: 	    }
1.109     matthew  2930: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2931: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2932: 				   ") greater than the weight for the part. Accept?");
                   2933: 		if (resp == false) {
                   2934: 		    textbox.value = "";
                   2935: 		    return;
                   2936: 		}
                   2937: 	    }
1.42      ng       2938: 	    for (var i=0; i<radioButton.length; i++) {
                   2939: 		radioButton[i].checked=false;
1.109     matthew  2940: 		if (parseFloat(point) == i) {
1.42      ng       2941: 		    radioButton[i].checked=true;
                   2942: 		}
                   2943: 	    }
1.41      ng       2944: 
1.42      ng       2945: 	} else {
1.125     ng       2946: 	    textbox.value = parseFloat(point);
1.42      ng       2947: 	}
1.41      ng       2948: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2949: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2950: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2951: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2952: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2953: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2954: 	    if (saveval != "correct") {
                   2955: 		scorename.value = point;
1.43      ng       2956: 		if (selname[0].selected != true) {
                   2957: 		    selname[0].selected = true;
                   2958: 		}
1.42      ng       2959: 	    }
                   2960: 	}
1.125     ng       2961: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2962:     }
                   2963: 
                   2964:     function writeRadText(partid,weight) {
1.125     ng       2965: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2966: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2967:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2968: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2969: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2970: 	    for (var i=0; i<radioButton.length; i++) {
                   2971: 		radioButton[i].checked=false;
                   2972: 
                   2973: 	    }
                   2974: 	    textbox.value = "";
                   2975: 
                   2976: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2977: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2978: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2979: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2980: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2981: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2982: 		if ((saveval != "correct") || override) {
1.42      ng       2983: 		    scorename.value = "";
1.125     ng       2984: 		    if (selval[1].selected) {
                   2985: 			selname[1].selected = true;
                   2986: 		    } else {
                   2987: 			selname[2].selected = true;
                   2988: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2989: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2990: 		    }
1.42      ng       2991: 		}
                   2992: 	    }
1.43      ng       2993: 	} else {
                   2994: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2995: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2996: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2997: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2998: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2999: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3000: 		if ((saveval != "correct") || override) {
1.125     ng       3001: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3002: 		    selname[0].selected = true;
                   3003: 		}
                   3004: 	    }
                   3005: 	}	    
1.42      ng       3006:     }
                   3007: 
                   3008:     function changeSelect(partid,user) {
1.125     ng       3009: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3010: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3011: 	var point  = textbox.value;
1.125     ng       3012: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3013: 
1.109     matthew  3014: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3015: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3016: 	    textbox.value = "";
                   3017: 	    return;
                   3018: 	}
1.109     matthew  3019: 	if (parseFloat(point) > parseFloat(weight)) {
                   3020: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3021: 			       ") greater than the weight of the part. Accept?");
                   3022: 	    if (resp == false) {
                   3023: 		textbox.value = "";
                   3024: 		return;
                   3025: 	    }
                   3026: 	}
1.42      ng       3027: 	selval[0].selected = true;
                   3028:     }
                   3029: 
                   3030:     function changeOneScore(partid,user) {
1.125     ng       3031: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3032: 	if (selval[1].selected || selval[2].selected) {
                   3033: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3034: 	    if (selval[2].selected) {
                   3035: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3036: 	    }
1.269     raeburn  3037:         }
1.42      ng       3038:     }
                   3039: 
                   3040:     function resetEntry(numpart) {
                   3041: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3042: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3043: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3044: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3045: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3046: 	    for (var i=0; i<radioButton.length; i++) {
                   3047: 		radioButton[i].checked=false;
                   3048: 
                   3049: 	    }
                   3050: 	    textbox.value = "";
                   3051: 	    selval[0].selected = true;
                   3052: 
                   3053: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3054: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3055: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3056: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3057: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3058: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3059: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3060: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3061: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3062: 		if (saveselval == "excused") {
1.43      ng       3063: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3064: 		} else {
1.43      ng       3065: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3066: 		}
                   3067: 	    }
1.41      ng       3068: 	}
1.42      ng       3069:     }
                   3070: 
1.41      ng       3071: </script>
                   3072: VIEWJAVASCRIPT
1.42      ng       3073: }
                   3074: 
1.44      ng       3075: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3076: sub viewgrades {
                   3077:     my ($request) = shift;
                   3078:     &viewgrades_js($request);
1.41      ng       3079: 
1.324     albertel 3080:     my ($symb) = &get_symb($request);
1.168     albertel 3081:     #need to make sure we have the correct data for later EXT calls, 
                   3082:     #thus invalidate the cache
                   3083:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3084:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3085:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3086:     &Apache::lonnet::clear_EXT_cache_status();
                   3087: 
1.398     albertel 3088:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3089:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3090: 
                   3091:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3092:     $result.=&jscriptNform($symb);
1.41      ng       3093: 
1.44      ng       3094:     #beginning of class grading form
1.442     banghart 3095:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3096:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3097: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3098: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3099: 	&build_section_inputs().
1.257     albertel 3100: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3101: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3102: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3103: 
1.126     ng       3104:     my $sectionClass;
1.430     banghart 3105:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3106:     if ($env{'form.section'} eq 'all') {
1.126     ng       3107: 	$sectionClass='Class </h3>';
1.257     albertel 3108:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3109: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3110:     } else {
1.431     banghart 3111: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3112:     }
1.431     banghart 3113:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3114:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3115: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3116:     #radio buttons/text box for assigning points for a section or class.
                   3117:     #handles different parts of a problem
1.375     albertel 3118:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3119:     my %weight = ();
                   3120:     my $ctsparts = 0;
1.41      ng       3121:     $result.='<table border="0">';
1.45      ng       3122:     my %seen = ();
1.375     albertel 3123:     my @part_response_id = &flatten_responseType($responseType);
                   3124:     foreach my $part_response_id (@part_response_id) {
                   3125:     	my ($partid,$respid) = @{ $part_response_id };
                   3126: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3127: 	next if $seen{$partid};
                   3128: 	$seen{$partid}++;
1.375     albertel 3129: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3130: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3131: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3132: 
1.44      ng       3133: 	$result.='<input type="hidden" name="partid_'.
                   3134: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3135: 	$result.='<input type="hidden" name="weight_'.
                   3136: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3137: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3138: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3139: 	$result.='<table border="0"><tr>';  
1.41      ng       3140: 	my $ctr = 0;
1.42      ng       3141: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3142: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3143: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3144: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3145: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3146: 	    $ctr++;
                   3147: 	}
                   3148: 	$result.='</tr></table>';
1.44      ng       3149: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3150: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3151: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3152: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3153: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3154: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3155: 		$weight{$partid}.')"> '.
1.401     albertel 3156: 	    '<option selected="selected"> </option>'.
1.125     ng       3157: 	    '<option>excused</option>'.
1.265     www      3158: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3159:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3160: 	$ctsparts++;
1.41      ng       3161:     }
1.52      albertel 3162:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3163: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3164:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3165: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3166: 
1.44      ng       3167:     #table listing all the students in a section/class
                   3168:     #header of table
1.126     ng       3169:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3170:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3171: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3172: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3173:     my (@parts) = sort(&getpartlist($symb));
                   3174:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3175:     my @partids = ();
1.41      ng       3176:     foreach my $part (@parts) {
                   3177: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3178: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3179: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3180: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3181:         push(@partids, $partid);
1.324     albertel 3182: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3183: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3184: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3185: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3186: 	    next;
1.207     albertel 3187: 	} else {
                   3188: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3189: 	}
1.53      albertel 3190: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3191: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3192:     }
                   3193:     $result.='</tr>';
1.44      ng       3194: 
1.270     albertel 3195:     my %last_resets = 
                   3196: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3197: 
1.41      ng       3198:     #get info for each student
1.44      ng       3199:     #list all the students - with points and grade status
1.257     albertel 3200:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3201:     my $ctr = 0;
1.294     albertel 3202:     foreach (sort 
                   3203: 	     {
                   3204: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3205: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3206: 		 }
                   3207: 		 return $a cmp $b;
                   3208: 	     } (keys(%$fullname))) {
1.126     ng       3209: 	$ctr++;
1.324     albertel 3210: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3211: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3212:     }
                   3213:     $result.='</table></td></tr></table>';
                   3214:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3215:     $result.='<input type="button" value="Save" '.
1.417     albertel 3216: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3217:     if (scalar(%$fullname) eq 0) {
                   3218: 	my $colspan=3+scalar(@parts);
1.433     banghart 3219: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3220:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3221: 	$result='<span class="LC_warning">'.
                   3222: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3223: 	        $section_display, $stu_status).
1.433     banghart 3224: 	    '</span>';
1.96      albertel 3225:     }
1.324     albertel 3226:     $result.=&show_grading_menu_form($symb);
1.41      ng       3227:     return $result;
                   3228: }
                   3229: 
1.44      ng       3230: #--- call by previous routine to display each student
1.41      ng       3231: sub viewstudentgrade {
1.324     albertel 3232:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3233:     my ($uname,$udom) = split(/:/,$student);
                   3234:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3235:     my %aggregates = (); 
1.233     albertel 3236:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3237: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3238: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3239: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3240: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3241: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3242:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3243:     foreach my $apart (@$parts) {
                   3244: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3245: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3246:         $result.='<td align="center">';
1.269     raeburn  3247:         my ($aggtries,$totaltries);
                   3248:         unless (exists($aggregates{$part})) {
1.270     albertel 3249: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3250: 
                   3251: 	    $aggtries = $totaltries;
1.269     raeburn  3252:             if ($$last_resets{$part}) {  
1.270     albertel 3253:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3254: 					   $part);
                   3255:             }
1.269     raeburn  3256:             $result.='<input type="hidden" name="'.
                   3257:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3258:             $result.='<input type="hidden" name="'.
                   3259:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3260:             $aggregates{$part} = 1;
                   3261:         }
1.41      ng       3262: 	if ($type eq 'awarded') {
1.320     albertel 3263: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3264: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3265: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3266: 	    $result.='<input type="text" name="'.
1.89      albertel 3267: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3268: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3269: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3270: 	} elsif ($type eq 'solved') {
                   3271: 	    my ($status,$foo)=split(/_/,$score,2);
                   3272: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3273: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3274: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3275: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3276: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3277: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3278: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3279: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3280: 	    $result.='<option>reset status</option>';
1.126     ng       3281: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3282: 	} else {
                   3283: 	    $result.='<input type="hidden" name="'.
                   3284: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3285: 		    "\n";
1.233     albertel 3286: 	    $result.='<input type="text" name="'.
1.122     ng       3287: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3288: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3289: 	}
                   3290:     }
                   3291:     $result.='</tr>';
                   3292:     return $result;
1.38      ng       3293: }
                   3294: 
1.44      ng       3295: #--- change scores for all the students in a section/class
                   3296: #    record does not get update if unchanged
1.38      ng       3297: sub editgrades {
1.41      ng       3298:     my ($request) = @_;
                   3299: 
1.324     albertel 3300:     my $symb=&get_symb($request);
1.433     banghart 3301:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3302:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3303:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3304:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3305: 
1.44      ng       3306:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3307:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3308: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3309: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3310: 
                   3311:     my %scoreptr = (
                   3312: 		    'correct'  =>'correct_by_override',
                   3313: 		    'incorrect'=>'incorrect_by_override',
                   3314: 		    'excused'  =>'excused',
                   3315: 		    'ungraded' =>'ungraded_attempted',
                   3316: 		    'nothing'  => '',
                   3317: 		    );
1.257     albertel 3318:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3319: 
1.44      ng       3320:     my (@partid);
                   3321:     my %weight = ();
1.54      albertel 3322:     my %columns = ();
1.44      ng       3323:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3324: 
1.324     albertel 3325:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3326:     my $header;
1.257     albertel 3327:     while ($ctr < $env{'form.totalparts'}) {
                   3328: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3329: 	push @partid,$partid;
1.257     albertel 3330: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3331: 	$ctr++;
1.54      albertel 3332:     }
1.324     albertel 3333:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3334:     foreach my $partid (@partid) {
                   3335: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3336: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3337: 	$columns{$partid}=2;
                   3338: 	foreach my $stores (@parts) {
                   3339: 	    my ($part,$type) = &split_part_type($stores);
                   3340: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3341: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3342: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3343: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3344: 	    $display =~ s/Number of Attempts/Tries/;
                   3345: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3346: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3347: 	    $columns{$partid}+=2;
                   3348: 	}
                   3349:     }
                   3350:     foreach my $partid (@partid) {
1.324     albertel 3351: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3352: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3353: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3354: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3355: 
1.44      ng       3356:     }
                   3357:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3358:     $result .= $header;
1.44      ng       3359:     $result .= '</tr>'."\n";
1.93      albertel 3360:     my $noupdate;
1.126     ng       3361:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3362:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3363: 	my $line;
1.257     albertel 3364: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3365: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3366: 	my %newrecord;
                   3367: 	my $updateflag = 0;
1.281     albertel 3368: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3369: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3370: 	if (!&canmodify($usec)) {
1.126     ng       3371: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3372: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3373: 	    next;
                   3374: 	}
1.269     raeburn  3375:         my %aggregate = ();
                   3376:         my $aggregateflag = 0;
1.281     albertel 3377: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3378: 	foreach (@partid) {
1.257     albertel 3379: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3380: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3381: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3382: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3383: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3384: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3385: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3386: 	    my $score;
                   3387: 	    if ($partial eq '') {
1.257     albertel 3388: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3389: 	    } elsif ($partial > 0) {
                   3390: 		$score = 'correct_by_override';
                   3391: 	    } elsif ($partial == 0) {
                   3392: 		$score = 'incorrect_by_override';
                   3393: 	    }
1.257     albertel 3394: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3395: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3396: 
1.292     albertel 3397: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3398: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3399: 	    if ($dropMenu eq 'reset status' &&
                   3400: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3401: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3402: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3403: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3404: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3405: 		$updateflag = 1;
1.269     raeburn  3406:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3407:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3408:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3409:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3410:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3411:                     $aggregateflag = 1;
                   3412:                 }
1.139     albertel 3413: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3414: 		$updateflag = 1;
                   3415: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3416: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3417: 		$rec_update++;
1.125     ng       3418: 	    }
                   3419: 
1.93      albertel 3420: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3421: 		'<td align="center">'.$awarded.
                   3422: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3423: 
1.54      albertel 3424: 
                   3425: 	    my $partid=$_;
                   3426: 	    foreach my $stores (@parts) {
                   3427: 		my ($part,$type) = &split_part_type($stores);
                   3428: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3429: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3430: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3431: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3432: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3433: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3434: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3435: 		    $updateflag=1;
                   3436: 		}
1.93      albertel 3437: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3438: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3439: 	    }
1.44      ng       3440: 	}
1.93      albertel 3441: 	$line.='</tr>'."\n";
1.301     albertel 3442: 
                   3443: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3444: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3445: 
1.44      ng       3446: 	if ($updateflag) {
                   3447: 	    $count++;
1.257     albertel 3448: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3449: 				    $udom,$uname);
1.301     albertel 3450: 
                   3451: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3452: 					      $cnum,$udom,$uname)) {
                   3453: 		# need to figure out if should be in queue.
                   3454: 		my %record =  
                   3455: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3456: 					     $udom,$uname);
                   3457: 		my $all_graded = 1;
                   3458: 		my $none_graded = 1;
                   3459: 		foreach my $part (@parts) {
                   3460: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3461: 			$all_graded = 0;
                   3462: 		    } else {
                   3463: 			$none_graded = 0;
                   3464: 		    }
                   3465: 		}
                   3466: 
                   3467: 		if ($all_graded || $none_graded) {
                   3468: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3469: 							   $symb,$cdom,$cnum,
                   3470: 							   $udom,$uname);
                   3471: 		}
                   3472: 	    }
                   3473: 
1.126     ng       3474: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3475: 	    $updateCtr++;
1.93      albertel 3476: 	} else {
1.126     ng       3477: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3478: 	    $noupdateCtr++;
1.44      ng       3479: 	}
1.269     raeburn  3480:         if ($aggregateflag) {
                   3481:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3482: 				  $cdom,$cnum);
1.269     raeburn  3483:         }
1.93      albertel 3484:     }
                   3485:     if ($noupdate) {
1.126     ng       3486: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3487: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3488: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
1.44      ng       3489:     }
1.72      ng       3490:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3491: 	&show_grading_menu_form ($symb);
1.125     ng       3492:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3493: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3494: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3495:     return $title.$msg.$result;
1.5       albertel 3496: }
1.54      albertel 3497: 
                   3498: sub split_part_type {
                   3499:     my ($partstr) = @_;
                   3500:     my ($temp,@allparts)=split(/_/,$partstr);
                   3501:     my $type=pop(@allparts);
1.439     albertel 3502:     my $part=join('_',@allparts);
1.54      albertel 3503:     return ($part,$type);
                   3504: }
                   3505: 
1.44      ng       3506: #------------- end of section for handling grading by section/class ---------
                   3507: #
                   3508: #----------------------------------------------------------------------------
                   3509: 
1.5       albertel 3510: 
1.44      ng       3511: #----------------------------------------------------------------------------
                   3512: #
                   3513: #-------------------------- Next few routines handles grading by csv upload
                   3514: #
                   3515: #--- Javascript to handle csv upload
1.27      albertel 3516: sub csvupload_javascript_reverse_associate {
1.246     albertel 3517:     my $error1=&mt('You need to specify the username or ID');
                   3518:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3519:   return(<<ENDPICK);
                   3520:   function verify(vf) {
                   3521:     var foundsomething=0;
                   3522:     var founduname=0;
1.243     albertel 3523:     var foundID=0;
1.27      albertel 3524:     for (i=0;i<=vf.nfields.value;i++) {
                   3525:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3526:       if (i==0 && tw!=0) { foundID=1; }
                   3527:       if (i==1 && tw!=0) { founduname=1; }
                   3528:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3529:     }
1.246     albertel 3530:     if (founduname==0 && foundID==0) {
                   3531: 	alert('$error1');
                   3532: 	return;
1.27      albertel 3533:     }
                   3534:     if (foundsomething==0) {
1.246     albertel 3535: 	alert('$error2');
                   3536: 	return;
1.27      albertel 3537:     }
                   3538:     vf.submit();
                   3539:   }
                   3540:   function flip(vf,tf) {
                   3541:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3542:     var i;
                   3543:     for (i=0;i<=vf.nfields.value;i++) {
                   3544:       //can not pick the same destination field for both name and domain
                   3545:       if (((i ==0)||(i ==1)) && 
                   3546:           ((tf==0)||(tf==1)) && 
                   3547:           (i!=tf) &&
                   3548:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3549:         eval('vf.f'+i+'.selectedIndex=0;')
                   3550:       }
                   3551:     }
                   3552:   }
                   3553: ENDPICK
                   3554: }
                   3555: 
                   3556: sub csvupload_javascript_forward_associate {
1.246     albertel 3557:     my $error1=&mt('You need to specify the username or ID');
                   3558:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3559:   return(<<ENDPICK);
                   3560:   function verify(vf) {
                   3561:     var foundsomething=0;
                   3562:     var founduname=0;
1.243     albertel 3563:     var foundID=0;
1.27      albertel 3564:     for (i=0;i<=vf.nfields.value;i++) {
                   3565:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3566:       if (tw==1) { foundID=1; }
                   3567:       if (tw==2) { founduname=1; }
                   3568:       if (tw>3) { foundsomething=1; }
1.27      albertel 3569:     }
1.246     albertel 3570:     if (founduname==0 && foundID==0) {
                   3571: 	alert('$error1');
                   3572: 	return;
1.27      albertel 3573:     }
                   3574:     if (foundsomething==0) {
1.246     albertel 3575: 	alert('$error2');
                   3576: 	return;
1.27      albertel 3577:     }
                   3578:     vf.submit();
                   3579:   }
                   3580:   function flip(vf,tf) {
                   3581:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3582:     var i;
                   3583:     //can not pick the same destination field twice
                   3584:     for (i=0;i<=vf.nfields.value;i++) {
                   3585:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3586:         eval('vf.f'+i+'.selectedIndex=0;')
                   3587:       }
                   3588:     }
                   3589:   }
                   3590: ENDPICK
                   3591: }
                   3592: 
1.26      albertel 3593: sub csvuploadmap_header {
1.324     albertel 3594:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3595:     my $javascript;
1.257     albertel 3596:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3597: 	$javascript=&csvupload_javascript_reverse_associate();
                   3598:     } else {
                   3599: 	$javascript=&csvupload_javascript_forward_associate();
                   3600:     }
1.45      ng       3601: 
1.324     albertel 3602:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3603:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3604:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3605:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3606:     $request->print(<<ENDPICK);
1.26      albertel 3607: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3608: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3609: $result
1.326     albertel 3610: <hr />
1.26      albertel 3611: <h3>Identify fields</h3>
                   3612: Total number of records found in file: $distotal <hr />
                   3613: Enter as many fields as you can. The system will inform you and bring you back
                   3614: to this page if the data selected is insufficient to run your class.<hr />
                   3615: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3616: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3617: <input type="hidden" name="associate"  value="" />
                   3618: <input type="hidden" name="phase"      value="three" />
                   3619: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3620: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3621: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3622: <input type="hidden" name="upfile_associate" 
1.257     albertel 3623:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3624: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3625: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3626: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3627: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3628: <hr />
                   3629: <script type="text/javascript" language="Javascript">
                   3630: $javascript
                   3631: </script>
                   3632: ENDPICK
1.118     ng       3633:     return '';
1.26      albertel 3634: 
                   3635: }
                   3636: 
                   3637: sub csvupload_fields {
1.324     albertel 3638:     my ($symb) = @_;
                   3639:     my (@parts) = &getpartlist($symb);
1.243     albertel 3640:     my @fields=(['ID','Student ID'],
                   3641: 		['username','Student Username'],
                   3642: 		['domain','Student Domain']);
1.324     albertel 3643:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3644:     foreach my $part (sort(@parts)) {
                   3645: 	my @datum;
                   3646: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3647: 	my $name=$part;
                   3648: 	if  (!$display) { $display = $name; }
                   3649: 	@datum=($name,$display);
1.244     albertel 3650: 	if ($name=~/^stores_(.*)_awarded/) {
                   3651: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3652: 	}
1.41      ng       3653: 	push(@fields,\@datum);
                   3654:     }
                   3655:     return (@fields);
1.26      albertel 3656: }
                   3657: 
                   3658: sub csvuploadmap_footer {
1.41      ng       3659:     my ($request,$i,$keyfields) =@_;
                   3660:     $request->print(<<ENDPICK);
1.26      albertel 3661: </table>
                   3662: <input type="hidden" name="nfields" value="$i" />
                   3663: <input type="hidden" name="keyfields" value="$keyfields" />
                   3664: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3665: </form>
                   3666: ENDPICK
                   3667: }
                   3668: 
1.283     albertel 3669: sub checkforfile_js {
1.86      ng       3670:     my $result =<<CSVFORMJS;
                   3671: <script type="text/javascript" language="javascript">
                   3672:     function checkUpload(formname) {
                   3673: 	if (formname.upfile.value == "") {
                   3674: 	    alert("Please use the browse button to select a file from your local directory.");
                   3675: 	    return false;
                   3676: 	}
                   3677: 	formname.submit();
                   3678:     }
                   3679:     </script>
                   3680: CSVFORMJS
1.283     albertel 3681:     return $result;
                   3682: }
                   3683: 
                   3684: sub upcsvScores_form {
                   3685:     my ($request) = shift;
1.324     albertel 3686:     my ($symb)=&get_symb($request);
1.283     albertel 3687:     if (!$symb) {return '';}
                   3688:     my $result=&checkforfile_js();
1.257     albertel 3689:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3690:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3691:     $result.=$table;
1.326     albertel 3692:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3693:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3694:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3695: 	'.</b></td></tr>'."\n";
                   3696:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3697:     my $upload=&mt("Upload Scores");
1.86      ng       3698:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3699:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3700:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3701:     $result.=<<ENDUPFORM;
1.106     albertel 3702: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3703: <input type="hidden" name="symb" value="$symb" />
                   3704: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3705: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3706: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3707: $upfile_select
1.370     www      3708: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3709: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3710: </form>
                   3711: ENDUPFORM
1.370     www      3712:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3713:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3714:     .'</td></tr></table>'."\n";
1.86      ng       3715:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3716:     $result.=&show_grading_menu_form($symb);
1.86      ng       3717:     return $result;
                   3718: }
                   3719: 
                   3720: 
1.26      albertel 3721: sub csvuploadmap {
1.41      ng       3722:     my ($request)= @_;
1.324     albertel 3723:     my ($symb)=&get_symb($request);
1.41      ng       3724:     if (!$symb) {return '';}
1.72      ng       3725: 
1.41      ng       3726:     my $datatoken;
1.257     albertel 3727:     if (!$env{'form.datatoken'}) {
1.41      ng       3728: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3729:     } else {
1.257     albertel 3730: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3731: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3732:     }
1.41      ng       3733:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3734:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3735:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3736:     my ($i,$keyfields);
                   3737:     if (@records) {
1.324     albertel 3738: 	my @fields=&csvupload_fields($symb);
1.45      ng       3739: 
1.257     albertel 3740: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3741: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3742: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3743: 							  \@fields);
                   3744: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3745: 	    chop($keyfields);
                   3746: 	} else {
                   3747: 	    unshift(@fields,['none','']);
                   3748: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3749: 							    \@fields);
1.311     banghart 3750:             foreach my $rec (@records) {
                   3751:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3752:                 if (%temp) {
                   3753:                     $keyfields=join(',',sort(keys(%temp)));
                   3754:                     last;
                   3755:                 }
                   3756:             }
1.41      ng       3757: 	}
                   3758:     }
                   3759:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3760:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3761: 
1.41      ng       3762:     return '';
1.27      albertel 3763: }
                   3764: 
1.246     albertel 3765: sub csvuploadoptions {
1.41      ng       3766:     my ($request)= @_;
1.324     albertel 3767:     my ($symb)=&get_symb($request);
1.257     albertel 3768:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3769:     my $ignore=&mt('Ignore First Line');
                   3770:     $request->print(<<ENDPICK);
                   3771: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3772: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3773: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3774: <!--
1.246     albertel 3775: <p>
                   3776: <label>
                   3777:    <input type="checkbox" name="show_full_results" />
                   3778:    Show a table of all changes
                   3779: </label>
                   3780: </p>
1.302     albertel 3781: -->
1.246     albertel 3782: <p>
                   3783: <label>
                   3784:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3785:    Overwrite any existing score
                   3786: </label>
                   3787: </p>
                   3788: ENDPICK
                   3789:     my %fields=&get_fields();
                   3790:     if (!defined($fields{'domain'})) {
1.257     albertel 3791: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3792: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3793:     }
1.257     albertel 3794:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3795: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3796: 	my $cleankey=$1;
                   3797: 	if ($cleankey eq 'command') { next; }
                   3798: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3799: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3800:     }
                   3801:     # FIXME do a check for any duplicated user ids...
                   3802:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3803:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3804: <hr /></form>'."\n");
1.324     albertel 3805:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3806:     return '';
                   3807: }
                   3808: 
                   3809: sub get_fields {
                   3810:     my %fields;
1.257     albertel 3811:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3812:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3813: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3814: 	    if ($env{'form.f'.$i} ne 'none') {
                   3815: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3816: 	    }
                   3817: 	} else {
1.257     albertel 3818: 	    if ($env{'form.f'.$i} ne 'none') {
                   3819: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3820: 	    }
                   3821: 	}
1.27      albertel 3822:     }
1.246     albertel 3823:     return %fields;
                   3824: }
                   3825: 
                   3826: sub csvuploadassign {
                   3827:     my ($request)= @_;
1.324     albertel 3828:     my ($symb)=&get_symb($request);
1.246     albertel 3829:     if (!$symb) {return '';}
1.345     bowersj2 3830:     my $error_msg = '';
1.246     albertel 3831:     &Apache::loncommon::load_tmp_file($request);
                   3832:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3833:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3834:     my %fields=&get_fields();
1.41      ng       3835:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3836:     my $courseid=$env{'request.course.id'};
1.97      albertel 3837:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3838:     my @notallowed;
1.41      ng       3839:     my @skipped;
                   3840:     my $countdone=0;
                   3841:     foreach my $grade (@gradedata) {
                   3842: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3843: 	my $domain;
                   3844: 	if ($entries{$fields{'domain'}}) {
                   3845: 	    $domain=$entries{$fields{'domain'}};
                   3846: 	} else {
1.257     albertel 3847: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3848: 	}
1.243     albertel 3849: 	$domain=~s/\s//g;
1.41      ng       3850: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3851: 	$username=~s/\s//g;
1.243     albertel 3852: 	if (!$username) {
                   3853: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3854: 	    $id=~s/\s//g;
1.243     albertel 3855: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3856: 	    $username=$ids{$id};
                   3857: 	}
1.41      ng       3858: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3859: 	    my $id=$entries{$fields{'ID'}};
                   3860: 	    $id=~s/\s//g;
                   3861: 	    if ($id) {
                   3862: 		push(@skipped,"$id:$domain");
                   3863: 	    } else {
                   3864: 		push(@skipped,"$username:$domain");
                   3865: 	    }
1.41      ng       3866: 	    next;
                   3867: 	}
1.108     albertel 3868: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3869: 	if (!&canmodify($usec)) {
                   3870: 	    push(@notallowed,"$username:$domain");
                   3871: 	    next;
                   3872: 	}
1.244     albertel 3873: 	my %points;
1.41      ng       3874: 	my %grades;
                   3875: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3876: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3877: 		$dest eq 'domain') { next; }
                   3878: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3879: 	    if ($dest=~/stores_(.*)_points/) {
                   3880: 		my $part=$1;
                   3881: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3882: 					      $symb,$domain,$username);
1.345     bowersj2 3883:                 if ($wgt) {
                   3884:                     $entries{$fields{$dest}}=~s/\s//g;
                   3885:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3886:                     my $award='correct_by_override';
                   3887:                     $grades{"resource.$part.awarded"}=$pcr;
                   3888:                     $grades{"resource.$part.solved"}=$award;
                   3889:                     $points{$part}=1;
                   3890:                 } else {
                   3891:                     $error_msg = "<br />" .
                   3892:                         &mt("Some point values were assigned"
                   3893:                             ." for problems with a weight "
                   3894:                             ."of zero. These values were "
                   3895:                             ."ignored.");
                   3896:                 }
1.244     albertel 3897: 	    } else {
                   3898: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3899: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3900: 		my $store_key=$dest;
                   3901: 		$store_key=~s/^stores/resource/;
                   3902: 		$store_key=~s/_/\./g;
                   3903: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3904: 	    }
1.41      ng       3905: 	}
1.398     albertel 3906: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3907: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3908: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3909: 					   $env{'request.course.id'},
                   3910: 					   $domain,$username);
                   3911: 	if ($result eq 'ok') {
                   3912: 	    $request->print('.');
                   3913: 	} else {
                   3914: 	    $request->print("<p>
1.398     albertel 3915:                               <span class=\"LC_error\">
                   3916:                                  Failed to save student $username:$domain.
                   3917:                                  Message when trying to save was ($result)
                   3918:                               </span>
1.302     albertel 3919:                              </p>" );
                   3920: 	}
1.41      ng       3921: 	$request->rflush();
                   3922: 	$countdone++;
                   3923:     }
1.398     albertel 3924:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3925:     if (@skipped) {
1.398     albertel 3926: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3927: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3928:     }
                   3929:     if (@notallowed) {
1.398     albertel 3930: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3931: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3932:     }
1.106     albertel 3933:     $request->print("<br />\n");
1.324     albertel 3934:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3935:     return $error_msg;
1.26      albertel 3936: }
1.44      ng       3937: #------------- end of section for handling csv file upload ---------
                   3938: #
                   3939: #-------------------------------------------------------------------
                   3940: #
1.122     ng       3941: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3942: #
                   3943: #--- Select a page/sequence and a student to grade
1.68      ng       3944: sub pickStudentPage {
                   3945:     my ($request) = shift;
                   3946: 
                   3947:     $request->print(<<LISTJAVASCRIPT);
                   3948: <script type="text/javascript" language="javascript">
                   3949: 
                   3950: function checkPickOne(formname) {
1.76      ng       3951:     if (radioSelection(formname.student) == null) {
1.68      ng       3952: 	alert("Please select the student you wish to grade.");
                   3953: 	return;
                   3954:     }
1.125     ng       3955:     ptr = pullDownSelection(formname.selectpage);
                   3956:     formname.page.value = formname["page"+ptr].value;
                   3957:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3958:     formname.submit();
                   3959: }
                   3960: 
                   3961: </script>
                   3962: LISTJAVASCRIPT
1.118     ng       3963:     &commonJSfunctions($request);
1.324     albertel 3964:     my ($symb) = &get_symb($request);
1.257     albertel 3965:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3966:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3967:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3968: 
1.398     albertel 3969:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3970: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3971: 
1.80      ng       3972:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3973:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3974:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3975:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3976: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3977: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3978:     my $ctr=0;
1.68      ng       3979:     foreach (@$titles) {
                   3980: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3981: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3982: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3983: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3984: 	$ctr++;
1.68      ng       3985:     }
1.326     albertel 3986:     $result.= '</select>'."<br />\n";
1.70      ng       3987:     $ctr=0;
                   3988:     foreach (@$titles) {
                   3989: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3990: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3991: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3992: 	$ctr++;
                   3993:     }
1.72      ng       3994:     $result.='<input type="hidden" name="page" />'."\n".
                   3995: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3996: 
1.401     albertel 3997:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3998: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3999: 
1.71      ng       4000:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4001: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4002: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4003: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4004:     
                   4005:     $result.=&build_section_inputs();
1.442     banghart 4006:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4007:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4008: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4009: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4010: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4011: 
1.382     albertel 4012:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4013: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4014: 
1.80      ng       4015:     $result.='&nbsp;<input type="button" '.
1.126     ng       4016: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4017: 
1.68      ng       4018:     $request->print($result);
                   4019: 
1.326     albertel 4020:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4021: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4022: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4023: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4024: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4025: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4026: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4027:  
1.76      ng       4028:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4029:     my $ptr = 1;
1.294     albertel 4030:     foreach my $student (sort 
                   4031: 			 {
                   4032: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4033: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4034: 			     }
                   4035: 			     return $a cmp $b;
                   4036: 			 } (keys(%$fullname))) {
1.68      ng       4037: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4038: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4039: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4040: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4041: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4042: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4043: 	$ptr++;
                   4044:     }
1.381     albertel 4045:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4046:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4047:     $studentTable.='<input type="button" '.
                   4048: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4049: 
1.324     albertel 4050:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4051:     $request->print($studentTable);
                   4052: 
                   4053:     return '';
                   4054: }
                   4055: 
                   4056: sub getSymbMap {
1.132     bowersj2 4057:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4058: 
                   4059:     my %symbx = ();
                   4060:     my @titles = ();
1.117     bowersj2 4061:     my $minder = 0;
                   4062: 
                   4063:     # Gather every sequence that has problems.
1.240     albertel 4064:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4065: 					       1,0,1);
1.117     bowersj2 4066:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4067: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4068: 	    my $title = $minder.'.'.
                   4069: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4070: 	    push(@titles, $title); # minder in case two titles are identical
                   4071: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4072: 	    $minder++;
1.241     albertel 4073: 	}
1.68      ng       4074:     }
                   4075:     return \@titles,\%symbx;
                   4076: }
                   4077: 
1.72      ng       4078: #
                   4079: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4080: sub displayPage {
                   4081:     my ($request) = shift;
                   4082: 
1.324     albertel 4083:     my ($symb) = &get_symb($request);
1.257     albertel 4084:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4085:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4086:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4087:     my $pageTitle = $env{'form.page'};
1.103     albertel 4088:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4089:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4090:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4091: 
                   4092:     #need to make sure we have the correct data for later EXT calls, 
                   4093:     #thus invalidate the cache
                   4094:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4095:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4096:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4097:     &Apache::lonnet::clear_EXT_cache_status();
                   4098: 
1.103     albertel 4099:     if (!&canview($usec)) {
1.398     albertel 4100: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4101: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4102: 	return;
                   4103:     }
1.398     albertel 4104:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4105:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4106: 	'</h3>'."\n";
1.382     albertel 4107:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4108: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4109:     } else {
                   4110: 	delete($env{'form.CODE'});
                   4111:     }
1.71      ng       4112:     &sub_page_js($request);
                   4113:     $request->print($result);
                   4114: 
1.132     bowersj2 4115:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4116:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4117:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4118:     if (!$map) {
1.398     albertel 4119: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4120: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4121: 	return; 
                   4122:     }
1.68      ng       4123:     my $iterator = $navmap->getIterator($map->map_start(),
                   4124: 					$map->map_finish());
                   4125: 
1.71      ng       4126:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4127: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4128: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4129: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4130: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4131: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4132: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4133: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4134: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4135: 
1.382     albertel 4136:     if (defined($env{'form.CODE'})) {
                   4137: 	$studentTable.=
                   4138: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4139:     }
1.381     albertel 4140:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4141: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4142: 	'/check.gif" height="16" border="0" />';
                   4143: 
1.118     ng       4144:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4145: 	' symbol.'."\n".
1.71      ng       4146: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4147: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4148: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4149: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4150: 
1.329     albertel 4151:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4152:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4153:     $iterator->next(); # skip the first BEGIN_MAP
                   4154:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4155:     while ($depth > 0) {
1.68      ng       4156:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4157:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4158: 
1.385     albertel 4159:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4160: 	    my $parts = $curRes->parts();
1.68      ng       4161:             my $title = $curRes->compTitle();
1.71      ng       4162: 	    my $symbx = $curRes->symb();
1.196     albertel 4163: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4164: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4165: 	    $studentTable.='<td valign="top">';
1.382     albertel 4166: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4167: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4168: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4169: 					     undef,'both',\%form);
1.71      ng       4170: 	    } else {
1.382     albertel 4171: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4172: 		$companswer =~ s|<form(.*?)>||g;
                   4173: 		$companswer =~ s|</form>||g;
1.71      ng       4174: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4175: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4176: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4177: #		}
1.116     ng       4178: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4179: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4180: 	    }
                   4181: 
1.257     albertel 4182: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4183: 
1.257     albertel 4184: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4185: 		if ($record{'version'} eq '') {
1.398     albertel 4186: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4187: 		} else {
1.116     ng       4188: 		    my %responseType = ();
                   4189: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4190: 			my @responseIds =$curRes->responseIds($partid);
                   4191: 			my @responseType =$curRes->responseType($partid);
                   4192: 			my %responseIds;
                   4193: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4194: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4195: 			}
                   4196: 			$responseType{$partid} = \%responseIds;
1.116     ng       4197: 		    }
1.148     albertel 4198: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4199: 
1.71      ng       4200: 		}
1.257     albertel 4201: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4202: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4203: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4204: 									$env{'request.course.id'},
1.71      ng       4205: 									'','.submission');
                   4206:  
                   4207: 	    }
1.103     albertel 4208: 	    if (&canmodify($usec)) {
                   4209: 		foreach my $partid (@{$parts}) {
                   4210: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4211: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4212: 		    $question++;
                   4213: 		}
1.196     albertel 4214: 		$prob++;
1.71      ng       4215: 	    }
                   4216: 	    $studentTable.='</td></tr>';
1.68      ng       4217: 
1.103     albertel 4218: 	}
1.68      ng       4219:         $curRes = $iterator->next();
                   4220:     }
                   4221: 
1.381     albertel 4222:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4223: 	'<input type="button" value="Save" '.
1.381     albertel 4224: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4225: 	'</form>'."\n";
1.324     albertel 4226:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4227:     $request->print($studentTable);
                   4228: 
                   4229:     return '';
1.119     ng       4230: }
                   4231: 
                   4232: sub displaySubByDates {
1.148     albertel 4233:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4234:     my $isCODE=0;
1.335     albertel 4235:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4236:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4237:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4238: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4239: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4240: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4241: 	'<td><b>Submission</b></td>'.
                   4242: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4243:     my ($version);
                   4244:     my %mark;
1.148     albertel 4245:     my %orders;
1.119     ng       4246:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4247:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4248: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4249:     }
1.335     albertel 4250: 
                   4251:     my $interaction;
1.119     ng       4252:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4253: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4254: 	if (exists($$record{$version.':resource.0.version'})) {
                   4255: 	    $interaction = $$record{$version.':resource.0.version'};
                   4256: 	}
                   4257: 
                   4258: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4259: 		             : "$version:resource");
1.119     ng       4260: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4261: 	if ($isCODE) {
                   4262: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4263: 	}
1.119     ng       4264: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4265: 	my @displaySub = ();
                   4266: 	foreach my $partid (@{$parts}) {
1.335     albertel 4267: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4268: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4269: 	    
                   4270: 
1.122     ng       4271: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4272: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4273: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4274: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4275: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4276: 
                   4277: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4278: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4279: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4280: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4281: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4282: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4283: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4284: 		    } else {
                   4285: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4286: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4287: 		    }
1.335     albertel 4288: 		    my $responseType=($isTask ? 'Task'
                   4289:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4290: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4291: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4292: 			$orders{$partid}->{$responseId}=
                   4293: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4294: 		    }
1.147     albertel 4295: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4296: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4297: 		}
                   4298: 	    }
1.335     albertel 4299: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4300: 		$displaySub[1].='Checked in by '.
                   4301: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4302: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4303: 		    '<br />';
                   4304: 	    }
                   4305: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4306: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4307: 		    lc($$record{"$where.$partid.award"}).' '.
                   4308: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4309: 		    '<br />';
                   4310: 	    }
1.335     albertel 4311: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4312: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4313: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4314: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4315: 		$displaySub[2].=
                   4316: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4317: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4318: 	    }
                   4319: 	}
                   4320: 	# needed because old essay regrader has not parts info
                   4321: 	if (exists $$record{"$version:resource.regrader"}) {
                   4322: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4323: 	}
                   4324: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4325: 	if ($displaySub[2]) {
                   4326: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4327: 	}
1.382     albertel 4328: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4329:     
1.119     ng       4330:     }
                   4331:     $studentTable.='</table></td></tr></table>';
                   4332:     return $studentTable;
1.71      ng       4333: }
                   4334: 
                   4335: sub updateGradeByPage {
                   4336:     my ($request) = shift;
                   4337: 
1.257     albertel 4338:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4339:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4340:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4341:     my $pageTitle = $env{'form.page'};
1.103     albertel 4342:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4343:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4344:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4345:     if (!&canmodify($usec)) {
1.398     albertel 4346: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4347: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4348: 	return;
                   4349:     }
1.398     albertel 4350:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4351:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4352: 	'</h3>'."\n";
1.70      ng       4353: 
1.68      ng       4354:     $request->print($result);
                   4355: 
1.132     bowersj2 4356:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4357:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4358:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4359:     if (!$map) {
1.398     albertel 4360: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4361: 	my ($symb)=&get_symb($request);
                   4362: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4363: 	return; 
                   4364:     }
1.71      ng       4365:     my $iterator = $navmap->getIterator($map->map_start(),
                   4366: 					$map->map_finish());
1.70      ng       4367: 
1.71      ng       4368:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4369: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4370: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4371: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4372: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4373: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4374: 
                   4375:     $iterator->next(); # skip the first BEGIN_MAP
                   4376:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4377:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4378:     while ($depth > 0) {
1.71      ng       4379:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4380:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4381: 
1.385     albertel 4382:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4383: 	    my $parts = $curRes->parts();
1.71      ng       4384:             my $title = $curRes->compTitle();
                   4385: 	    my $symbx = $curRes->symb();
1.196     albertel 4386: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4387: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4388: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4389: 
                   4390: 	    my %newrecord=();
                   4391: 	    my @displayPts=();
1.269     raeburn  4392:             my %aggregate = ();
                   4393:             my $aggregateflag = 0;
1.71      ng       4394: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4395: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4396: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4397: 
1.257     albertel 4398: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4399: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4400: 		my $partial = $newpts/$wgt;
                   4401: 		my $score;
                   4402: 		if ($partial > 0) {
                   4403: 		    $score = 'correct_by_override';
1.125     ng       4404: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4405: 		    $score = 'incorrect_by_override';
                   4406: 		}
1.257     albertel 4407: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4408: 		if ($dropMenu eq 'excused') {
1.71      ng       4409: 		    $partial = '';
                   4410: 		    $score = 'excused';
1.125     ng       4411: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4412: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4413: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4414: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4415: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4416: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4417: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4418: 		    $changeflag++;
                   4419: 		    $newpts = '';
1.269     raeburn  4420:                     
                   4421:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4422:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4423:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4424:                     if ($aggtries > 0) {
                   4425:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4426:                         $aggregateflag = 1;
                   4427:                     }
1.71      ng       4428: 		}
1.324     albertel 4429: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4430: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4431: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4432: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4433: 		    '&nbsp;<br />';
1.207     albertel 4434: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4435: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4436: 		    '&nbsp;<br />';
1.71      ng       4437: 		$question++;
1.380     albertel 4438: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4439: 
1.71      ng       4440: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4441: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4442: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4443: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4444: 
                   4445: 		$changeflag++;
                   4446: 	    }
                   4447: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4448: 		my %record = 
                   4449: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4450: 					     $udom,$uname);
                   4451: 
                   4452: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4453: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4454: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4455: 		    $newrecord{'resource.CODE'} = '';
                   4456: 		}
1.257     albertel 4457: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4458: 					$udom,$uname);
1.382     albertel 4459: 		%record = &Apache::lonnet::restore($symbx,
                   4460: 						   $env{'request.course.id'},
                   4461: 						   $udom,$uname);
1.380     albertel 4462: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4463: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4464: 	    }
1.380     albertel 4465: 	    
1.269     raeburn  4466:             if ($aggregateflag) {
                   4467:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4468:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4469:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4470:             }
1.125     ng       4471: 
1.71      ng       4472: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4473: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4474: 		'</tr>';
1.68      ng       4475: 
1.196     albertel 4476: 	    $prob++;
1.68      ng       4477: 	}
1.71      ng       4478:         $curRes = $iterator->next();
1.68      ng       4479:     }
1.98      albertel 4480: 
1.71      ng       4481:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4482:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4483:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4484: 		  'The scores were changed for '.
                   4485: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4486:     $request->print($grademsg.$studentTable);
1.68      ng       4487: 
1.70      ng       4488:     return '';
                   4489: }
                   4490: 
1.72      ng       4491: #-------- end of section for handling grading by page/sequence ---------
                   4492: #
                   4493: #-------------------------------------------------------------------
                   4494: 
1.75      albertel 4495: #--------------------Scantron Grading-----------------------------------
                   4496: #
                   4497: #------ start of section for handling grading by page/sequence ---------
                   4498: 
1.423     albertel 4499: =pod
                   4500: 
                   4501: =head1 Bubble sheet grading routines
                   4502: 
1.424     albertel 4503:   For this documentation:
                   4504: 
                   4505:    'scanline' refers to the full line of characters
                   4506:    from the file that we are parsing that represents one entire sheet
                   4507: 
                   4508:    'bubble line' refers to the data
                   4509:    representing the line of bubbles that are on the physical bubble sheet
                   4510: 
                   4511: 
                   4512: The overall process is that a scanned in bubble sheet data is uploaded
                   4513: into a course. When a user wants to grade, they select a
                   4514: sequence/folder of resources, a file of bubble sheet info, and pick
                   4515: one of the predefined configurations for what each scanline looks
                   4516: like.
                   4517: 
                   4518: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4519: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4520: because too light bubbling), 'double bubble' (each bubble line should
                   4521: have no more that one letter picked), invalid or duplicated CODE,
                   4522: invalid student ID
                   4523: 
                   4524: If the CODE option is used that determines the randomization of the
                   4525: homework problems, either way the student ID is looked up into a
                   4526: username:domain.
                   4527: 
                   4528: During the validation phase the instructor can choose to skip scanlines. 
                   4529: 
1.435     foxr     4530: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4531: 
                   4532:   scantron_original_filename (unmodified original file)
                   4533:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4534:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4535: 
                   4536: Also there is a separate hash nohist_scantrondata that contains extra
                   4537: correction information that isn't representable in the bubble sheet
                   4538: file (see &scantron_getfile() for more information)
                   4539: 
                   4540: After all scanlines are either valid, marked as valid or skipped, then
                   4541: foreach line foreach problem in the picked sequence, an ssi request is
                   4542: made that simulates a user submitting their selected letter(s) against
                   4543: the homework problem.
1.423     albertel 4544: 
                   4545: =over 4
                   4546: 
                   4547: 
                   4548: 
                   4549: =item defaultFormData
                   4550: 
                   4551:   Returns html hidden inputs used to hold context/default values.
                   4552: 
                   4553:  Arguments:
                   4554:   $symb - $symb of the current resource 
                   4555: 
                   4556: =cut
1.422     foxr     4557: 
1.81      albertel 4558: sub defaultFormData {
1.324     albertel 4559:     my ($symb)=@_;
1.447     foxr     4560:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4561:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4562:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4563: }
                   4564: 
1.447     foxr     4565: 
1.423     albertel 4566: =pod 
                   4567: 
                   4568: =item getSequenceDropDown
                   4569: 
                   4570:    Return html dropdown of possible sequences to grade
                   4571:  
                   4572:  Arguments:
                   4573:    $symb - $symb of the current resource 
                   4574: 
                   4575: =cut
1.422     foxr     4576: 
1.75      albertel 4577: sub getSequenceDropDown {
1.423     albertel 4578:     my ($symb)=@_;
1.75      albertel 4579:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4580:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4581:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4582:     my $ctr=0;
                   4583:     foreach (@$titles) {
                   4584: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4585: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4586: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4587: 	    '>'.$showtitle.'</option>'."\n";
                   4588: 	$ctr++;
                   4589:     }
                   4590:     $result.= '</select>';
                   4591:     return $result;
                   4592: }
                   4593: 
1.423     albertel 4594: 
                   4595: =pod 
                   4596: 
                   4597: =item scantron_filenames
                   4598: 
                   4599:    Returns a list of the scantron files in the current course 
                   4600: 
                   4601: =cut
1.422     foxr     4602: 
1.202     albertel 4603: sub scantron_filenames {
1.257     albertel 4604:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4605:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4606:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4607: 				    &propath($cdom,$cname));
1.202     albertel 4608:     my @possiblenames;
1.201     albertel 4609:     foreach my $filename (sort(@files)) {
1.157     albertel 4610: 	($filename)=split(/&/,$filename);
                   4611: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4612: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4613: 	push(@possiblenames,$filename);
                   4614:     }
                   4615:     return @possiblenames;
                   4616: }
                   4617: 
1.423     albertel 4618: =pod 
                   4619: 
                   4620: =item scantron_uploads
                   4621: 
                   4622:    Returns  html drop-down list of scantron files in current course.
                   4623: 
                   4624:  Arguments:
                   4625:    $file2grade - filename to set as selected in the dropdown
                   4626: 
                   4627: =cut
1.422     foxr     4628: 
1.202     albertel 4629: sub scantron_uploads {
1.209     ng       4630:     my ($file2grade) = @_;
1.202     albertel 4631:     my $result=	'<select name="scantron_selectfile">';
                   4632:     $result.="<option></option>";
                   4633:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4634: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4635:     }
                   4636:     $result.="</select>";
                   4637:     return $result;
                   4638: }
                   4639: 
1.423     albertel 4640: =pod 
                   4641: 
                   4642: =item scantron_scantab
                   4643: 
                   4644:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4645:   file.
                   4646: 
                   4647: =cut
1.422     foxr     4648: 
1.82      albertel 4649: sub scantron_scantab {
                   4650:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4651:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4652:     $result.='<option></option>'."\n";
1.82      albertel 4653:     foreach my $line (<$fh>) {
                   4654: 	my ($name,$descrip)=split(/:/,$line);
                   4655: 	if ($name =~ /^\#/) { next; }
                   4656: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4657:     }
                   4658:     $result.='</select>'."\n";
                   4659: 
                   4660:     return $result;
                   4661: }
                   4662: 
1.423     albertel 4663: =pod 
                   4664: 
                   4665: =item scantron_CODElist
                   4666: 
                   4667:   Returns html drop down of the saved CODE lists from current course,
                   4668:   generated from earlier printings.
                   4669: 
                   4670: =cut
1.422     foxr     4671: 
1.186     albertel 4672: sub scantron_CODElist {
1.257     albertel 4673:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4674:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4675:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4676:     my $namechoice='<option></option>';
1.225     albertel 4677:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4678: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4679: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4680: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4681:     }
                   4682:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4683:     return $namechoice;
                   4684: }
                   4685: 
1.423     albertel 4686: =pod 
                   4687: 
                   4688: =item scantron_CODEunique
                   4689: 
                   4690:   Returns the html for "Each CODE to be used once" radio.
                   4691: 
                   4692: =cut
1.422     foxr     4693: 
1.186     albertel 4694: sub scantron_CODEunique {
1.381     albertel 4695:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4696:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4697:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4698:                 </span>
                   4699:                 <span style="white-space: nowrap;">
1.272     albertel 4700:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4701:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4702:                 </span>';
1.186     albertel 4703:     return $result;
                   4704: }
1.423     albertel 4705: 
                   4706: =pod 
                   4707: 
                   4708: =item scantron_selectphase
                   4709: 
                   4710:   Generates the initial screen to start the bubble sheet process.
                   4711:   Allows for - starting a grading run.
1.424     albertel 4712:              - downloading existing scan data (original, corrected
1.423     albertel 4713:                                                 or skipped info)
                   4714: 
                   4715:              - uploading new scan data
                   4716: 
                   4717:  Arguments:
                   4718:   $r          - The Apache request object
                   4719:   $file2grade - name of the file that contain the scanned data to score
                   4720: 
                   4721: =cut
1.186     albertel 4722: 
1.75      albertel 4723: sub scantron_selectphase {
1.209     ng       4724:     my ($r,$file2grade) = @_;
1.324     albertel 4725:     my ($symb)=&get_symb($r);
1.75      albertel 4726:     if (!$symb) {return '';}
1.423     albertel 4727:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4728:     my $default_form_data=&defaultFormData($symb);
                   4729:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4730:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4731:     my $format_selector=&scantron_scantab();
1.186     albertel 4732:     my $CODE_selector=&scantron_CODElist();
                   4733:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4734:     my $result;
1.422     foxr     4735: 
                   4736:     # Chunk of form to prompt for a file to grade and how:
                   4737: 
1.75      albertel 4738:     $result.= <<SCANTRONFORM;
1.162     albertel 4739:     <table width="100%" border="0">
1.75      albertel 4740:     <tr>
1.226     albertel 4741:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4742:       <td bgcolor="#777777">
1.203     albertel 4743:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4744:         $default_form_data
1.75      albertel 4745:         <table width="100%" border="0">
                   4746:           <tr bgcolor="#e6ffff">
1.174     albertel 4747:             <td colspan="2">
                   4748:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4749:             </td>
                   4750:           </tr>
                   4751:           <tr bgcolor="#ffffe6">
1.174     albertel 4752:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4753:           </tr>
                   4754:           <tr bgcolor="#ffffe6">
1.174     albertel 4755:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4756:           </tr>
1.82      albertel 4757:           <tr bgcolor="#ffffe6">
1.174     albertel 4758:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4759:           </tr>
1.157     albertel 4760:           <tr bgcolor="#ffffe6">
1.186     albertel 4761:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4762:           </tr>
                   4763:           <tr bgcolor="#ffffe6">
                   4764:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4765:           </tr>
                   4766:           <tr bgcolor="#ffffe6">
1.187     albertel 4767: 	    <td> Options: </td>
                   4768:             <td>
1.272     albertel 4769: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4770:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4771:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4772: 	    </td>
                   4773:           </tr>
                   4774:           <tr bgcolor="#ffffe6">
1.174     albertel 4775:             <td colspan="2">
1.265     www      4776:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4777:             </td>
                   4778:           </tr>
                   4779:         </table>
1.226     albertel 4780:        </td>
                   4781:      </form>
1.162     albertel 4782:     </tr>
                   4783: SCANTRONFORM
                   4784:    
                   4785:     $r->print($result);
                   4786: 
1.257     albertel 4787:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4788:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4789: 
1.422     foxr     4790: 	# Chunk of form to prompt for a scantron file upload.
                   4791: 
1.162     albertel 4792:         $r->print(<<SCANTRONFORM);
                   4793:     <tr>
                   4794:       <td bgcolor="#777777">
                   4795:         <table width="100%" border="0">
                   4796:           <tr bgcolor="#e6ffff">
                   4797:             <td>
1.174     albertel 4798:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4799:             </td>
                   4800:           </tr>
                   4801:           <tr bgcolor="#ffffe6">
                   4802:             <td>
                   4803: SCANTRONFORM
1.324     albertel 4804:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4805:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4806:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4807:     $r->print(<<UPLOAD);
                   4808:               <script type="text/javascript" language="javascript">
                   4809:     function checkUpload(formname) {
                   4810: 	if (formname.upfile.value == "") {
                   4811: 	    alert("Please use the browse button to select a file from your local directory.");
                   4812: 	    return false;
                   4813: 	}
                   4814: 	formname.submit();
                   4815:     }
                   4816:               </script>
                   4817: 
                   4818:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4819:                 $default_form_data
                   4820:                 <input name='courseid' type='hidden' value='$cnum' />
                   4821:                 <input name='domainid' type='hidden' value='$cdom' />
                   4822:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4823:                 File to upload:<input type="file" name="upfile" size="50" />
                   4824:                 <br />
                   4825:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4826:               </form>
                   4827: UPLOAD
1.162     albertel 4828: 
                   4829:         $r->print(<<SCANTRONFORM);
                   4830:             </td>
                   4831:           </tr>
1.75      albertel 4832:         </table>
                   4833:       </td>
                   4834:     </tr>
1.162     albertel 4835: SCANTRONFORM
                   4836:     }
1.422     foxr     4837: 
                   4838:     # Chunk of the form that prompts to view a scoring office file,
                   4839:     # corrected file, skipped records in a file.
                   4840: 
1.187     albertel 4841:     $r->print(<<SCANTRONFORM);
                   4842:     <tr>
1.226     albertel 4843:       <form action='/adm/grades' name='scantron_download'>
                   4844:         <td bgcolor="#777777">
1.379     albertel 4845: 	  $default_form_data
1.187     albertel 4846:           <input type="hidden" name="command" value="scantron_download" />
                   4847:           <table width="100%" border="0">
                   4848:             <tr bgcolor="#e6ffff">
                   4849:               <td colspan="2">
                   4850:                 &nbsp;<b>Download a scoring office file</b>
                   4851:               </td>
                   4852:             </tr>
                   4853:             <tr bgcolor="#ffffe6">
                   4854:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4855:             </tr>
                   4856:             <tr bgcolor="#ffffe6">
                   4857:               <td colspan="2">
1.293     www      4858:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4859:               </td>
                   4860:             </tr>
                   4861:           </table>
1.226     albertel 4862:         </td>
                   4863:       </form>
1.187     albertel 4864:     </tr>
                   4865: SCANTRONFORM
1.162     albertel 4866: 
                   4867:     $r->print(<<SCANTRONFORM);
1.75      albertel 4868:   </table>
1.81      albertel 4869: $grading_menu_button
1.75      albertel 4870: SCANTRONFORM
                   4871: 
1.162     albertel 4872:     return
1.75      albertel 4873: }
                   4874: 
1.423     albertel 4875: =pod
                   4876: 
                   4877: =item get_scantron_config
                   4878: 
                   4879:    Parse and return the scantron configuration line selected as a
                   4880:    hash of configuration file fields.
                   4881: 
                   4882:  Arguments:
                   4883:     which - the name of the configuration to parse from the file.
                   4884: 
                   4885: 
                   4886:  Returns:
                   4887:             If the named configuration is not in the file, an empty
                   4888:             hash is returned.
                   4889:     a hash with the fields
                   4890:       name         - internal name for the this configuration setup
                   4891:       description  - text to display to operator that describes this config
                   4892:       CODElocation - if 0 or the string 'none'
                   4893:                           - no CODE exists for this config
                   4894:                      if -1 || the string 'letter'
                   4895:                           - a CODE exists for this config and is
                   4896:                             a string of letters
                   4897:                      Unsupported value (but planned for future support)
                   4898:                           if a positive integer
                   4899:                                - The CODE exists as the first n items from
                   4900:                                  the question section of the form
                   4901:                           if the string 'number'
                   4902:                                - The CODE exists for this config and is
                   4903:                                  a string of numbers
                   4904:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4905:                      the CODE starts
                   4906:       CODElength  - length of the CODE
                   4907:       IDstart     - column where the student ID number starts
                   4908:       IDlength    - length of the student ID info
                   4909:       Qstart      - column where the information from the bubbled
                   4910:                     'questions' start
                   4911:       Qlength     - number of columns comprising a single bubble line from
                   4912:                     the sheet. (usually either 1 or 10)
1.424     albertel 4913:       Qon         - either a single character representing the character used
1.423     albertel 4914:                     to signal a bubble was chosen in the positional setup, or
                   4915:                     the string 'letter' if the letter of the chosen bubble is
                   4916:                     in the final, or 'number' if a number representing the
                   4917:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4918:       Qoff        - the character used to represent that a bubble was
                   4919:                     left blank
1.423     albertel 4920:       PaperID     - if the scanning process generates a unique number for each
                   4921:                     sheet scanned the column that this ID number starts in
                   4922:       PaperIDlength - number of columns that comprise the unique ID number
                   4923:                       for the sheet of paper
1.424     albertel 4924:       FirstName   - column that the first name starts in
1.423     albertel 4925:       FirstNameLength - number of columns that the first name spans
                   4926:  
                   4927:       LastName    - column that the last name starts in
                   4928:       LastNameLength - number of columns that the last name spans
                   4929: 
                   4930: =cut
1.422     foxr     4931: 
1.82      albertel 4932: sub get_scantron_config {
                   4933:     my ($which) = @_;
                   4934:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4935:     my %config;
1.157     albertel 4936:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4937:     foreach my $line (<$fh>) {
                   4938: 	my ($name,$descrip)=split(/:/,$line);
                   4939: 	if ($name ne $which ) { next; }
                   4940: 	chomp($line);
                   4941: 	my @config=split(/:/,$line);
                   4942: 	$config{'name'}=$config[0];
                   4943: 	$config{'description'}=$config[1];
                   4944: 	$config{'CODElocation'}=$config[2];
                   4945: 	$config{'CODEstart'}=$config[3];
                   4946: 	$config{'CODElength'}=$config[4];
                   4947: 	$config{'IDstart'}=$config[5];
                   4948: 	$config{'IDlength'}=$config[6];
                   4949: 	$config{'Qstart'}=$config[7];
                   4950: 	$config{'Qlength'}=$config[8];
                   4951: 	$config{'Qoff'}=$config[9];
                   4952: 	$config{'Qon'}=$config[10];
1.157     albertel 4953: 	$config{'PaperID'}=$config[11];
                   4954: 	$config{'PaperIDlength'}=$config[12];
                   4955: 	$config{'FirstName'}=$config[13];
                   4956: 	$config{'FirstNamelength'}=$config[14];
                   4957: 	$config{'LastName'}=$config[15];
                   4958: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4959: 	last;
                   4960:     }
                   4961:     return %config;
                   4962: }
                   4963: 
1.423     albertel 4964: =pod 
                   4965: 
                   4966: =item username_to_idmap
                   4967: 
                   4968:     creates a hash keyed by student id with values of the corresponding
                   4969:     student username:domain.
                   4970: 
                   4971:   Arguments:
                   4972: 
                   4973:     $classlist - reference to the class list hash. This is a hash
                   4974:                  keyed by student name:domain  whose elements are references
1.424     albertel 4975:                  to arrays containing various chunks of information
1.423     albertel 4976:                  about the student. (See loncoursedata for more info).
                   4977: 
                   4978:   Returns
                   4979:     %idmap - the constructed hash
                   4980: 
                   4981: =cut
                   4982: 
1.82      albertel 4983: sub username_to_idmap {
                   4984:     my ($classlist)= @_;
                   4985:     my %idmap;
                   4986:     foreach my $student (keys(%$classlist)) {
                   4987: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4988: 	    $student;
                   4989:     }
                   4990:     return %idmap;
                   4991: }
1.423     albertel 4992: 
                   4993: =pod
                   4994: 
1.424     albertel 4995: =item scantron_fixup_scanline
1.423     albertel 4996: 
                   4997:    Process a requested correction to a scanline.
                   4998: 
                   4999:   Arguments:
                   5000:     $scantron_config   - hash from &get_scantron_config()
                   5001:     $scan_data         - hash of correction information 
                   5002:                           (see &scantron_getfile())
                   5003:     $line              - existing scanline
                   5004:     $whichline         - line number of the passed in scanline
                   5005:     $field             - type of change to process 
                   5006:                          (either 
                   5007:                           'ID'     -> correct the student ID number
                   5008:                           'CODE'   -> correct the CODE
                   5009:                           'answer' -> fixup the submitted answers)
                   5010:     
                   5011:    $args               - hash of additional info,
                   5012:                           - 'ID' 
                   5013:                                'newid' -> studentID to use in replacement
1.424     albertel 5014:                                           of existing one
1.423     albertel 5015:                           - 'CODE' 
                   5016:                                'CODE_ignore_dup' - set to true if duplicates
                   5017:                                                    should be ignored.
                   5018: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5019:                                         if the existing unfound code should
1.423     albertel 5020:                                         be used as is
                   5021:                           - 'answer'
                   5022:                                'response' - new answer or 'none' if blank
                   5023:                                'question' - the bubble line to change
                   5024: 
                   5025:   Returns:
                   5026:     $line - the modified scanline
                   5027: 
                   5028:   Side effects: 
                   5029:     $scan_data - may be updated
                   5030: 
                   5031: =cut
                   5032: 
1.82      albertel 5033: 
1.157     albertel 5034: sub scantron_fixup_scanline {
                   5035:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5036: 
1.157     albertel 5037:     if ($field eq 'ID') {
                   5038: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5039: 	    return ($line,1,'New value too large');
1.157     albertel 5040: 	}
                   5041: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5042: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5043: 				     $args->{'newid'});
                   5044: 	}
                   5045: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5046: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5047: 	if ($args->{'newid'}=~/^\s*$/) {
                   5048: 	    &scan_data($scan_data,"$whichline.user",
                   5049: 		       $args->{'username'}.':'.$args->{'domain'});
                   5050: 	}
1.186     albertel 5051:     } elsif ($field eq 'CODE') {
1.192     albertel 5052: 	if ($args->{'CODE_ignore_dup'}) {
                   5053: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5054: 	}
                   5055: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5056: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5057: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5058: 		return ($line,1,'New CODE value too large');
                   5059: 	    }
                   5060: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5061: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5062: 	    }
                   5063: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5064: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5065: 	}
1.157     albertel 5066:     } elsif ($field eq 'answer') {
                   5067: 	my $length=$scantron_config->{'Qlength'};
                   5068: 	my $off=$scantron_config->{'Qoff'};
                   5069: 	my $on=$scantron_config->{'Qon'};
                   5070: 	my $answer=${off}x$length;
                   5071: 	if ($args->{'response'} eq 'none') {
                   5072: 	    &scan_data($scan_data,
                   5073: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5074: 	} else {
1.274     albertel 5075: 	    if ($on eq 'letter') {
                   5076: 		my @alphabet=('A'..'Z');
                   5077: 		$answer=$alphabet[$args->{'response'}];
                   5078: 	    } elsif ($on eq 'number') {
                   5079: 		$answer=$args->{'response'}+1;
1.389     albertel 5080: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5081: 	    } else {
                   5082: 		substr($answer,$args->{'response'},1)=$on;
                   5083: 	    }
1.157     albertel 5084: 	    &scan_data($scan_data,
                   5085: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5086: 	}
                   5087: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5088: 	substr($line,$where-1,$length)=$answer;
                   5089:     }
                   5090:     return $line;
                   5091: }
1.423     albertel 5092: 
                   5093: =pod
                   5094: 
                   5095: =item scan_data
                   5096: 
                   5097:     Edit or look up  an item in the scan_data hash.
                   5098: 
                   5099:   Arguments:
                   5100:     $scan_data  - The hash (see scantron_getfile)
                   5101:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5102:                   scantronfilename_key).
1.423     albertel 5103:     $data        - New value of the hash entry.
                   5104:     $delete      - If true, the entry is removed from the hash.
                   5105: 
                   5106:   Returns:
                   5107:     The new value of the hash table field (undefined if deleted).
                   5108: 
                   5109: =cut
                   5110: 
                   5111: 
1.157     albertel 5112: sub scan_data {
                   5113:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5114:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5115:     if (defined($value)) {
                   5116: 	$scan_data->{$filename.'_'.$key} = $value;
                   5117:     }
                   5118:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5119:     return $scan_data->{$filename.'_'.$key};
                   5120: }
1.423     albertel 5121: 
                   5122: =pod 
                   5123: 
                   5124: =item scantron_parse_scanline
                   5125: 
                   5126:   Decodes a scanline from the selected scantron file
                   5127: 
                   5128:  Arguments:
                   5129:     line             - The text of the scantron file line to process
                   5130:     whichline        - Line number
                   5131:     scantron_config  - Hash describing the format of the scantron lines.
                   5132:     scan_data        - Hash of extra information about the scanline
                   5133:                        (see scantron_getfile for more information)
                   5134:     just_header      - True if should not process question answers but only
                   5135:                        the stuff to the left of the answers.
                   5136:  Returns:
                   5137:    Hash containing the result of parsing the scanline
                   5138: 
                   5139:    Keys are all proceeded by the string 'scantron.'
                   5140: 
                   5141:        CODE    - the CODE in use for this scanline
                   5142:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5143:                  by the operator
                   5144:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5145:                             CODEs were selected, but the usage has been
                   5146:                             forced by the operator
                   5147:        ID  - student ID
                   5148:        PaperID - if used, the ID number printed on the sheet when the 
                   5149:                  paper was scanned
                   5150:        FirstName - first name from the sheet
                   5151:        LastName  - last name from the sheet
                   5152: 
                   5153:      if just_header was not true these key may also exist
                   5154: 
1.447     foxr     5155:        missingerror - a list of bubble ranges that are considered to be answers
                   5156:                       to a single question that don't have any bubbles filled in.
                   5157:                       Of the form questionnumber:firstbubblenumber:count.
                   5158:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5159:                       to a single question that have more than one bubble filled in.
                   5160:                       Of the form questionnumber::firstbubblenumber:count
                   5161:    
                   5162:                 In the above, count is the number of bubble responses in the
                   5163:                 input line needed to represent the possible answers to the question.
                   5164:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5165:                 per line would have count = 2.
                   5166: 
1.423     albertel 5167:        maxquest     - the number of the last bubble line that was parsed
                   5168: 
                   5169:        (<number> starts at 1)
                   5170:        <number>.answer - zero or more letters representing the selected
                   5171:                          letters from the scanline for the bubble line 
                   5172:                          <number>.
                   5173:                          if blank there was either no bubble or there where
                   5174:                          multiple bubbles, (consult the keys missingerror and
                   5175:                          doubleerror if this is an error condition)
                   5176: 
                   5177: =cut
                   5178: 
1.82      albertel 5179: sub scantron_parse_scanline {
1.423     albertel 5180:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5181:     my %record;
1.422     foxr     5182:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5183:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5184:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5185: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5186: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5187: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5188: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5189: 	    $record{'scantron.CODE'}=substr($data,
                   5190: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5191: 					    $$scantron_config{'CODElength'});
1.191     albertel 5192: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5193: 		$record{'scantron.useCODE'}=1;
                   5194: 	    }
1.192     albertel 5195: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5196: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5197: 	    }
1.82      albertel 5198: 	} else {
                   5199: 	    #FIXME interpret first N questions
                   5200: 	}
                   5201:     }
1.83      albertel 5202:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5203: 				  $$scantron_config{'IDlength'});
1.157     albertel 5204:     $record{'scantron.PaperID'}=
                   5205: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5206: 	       $$scantron_config{'PaperIDlength'});
                   5207:     $record{'scantron.FirstName'}=
                   5208: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5209: 	       $$scantron_config{'FirstNamelength'});
                   5210:     $record{'scantron.LastName'}=
                   5211: 	substr($data,$$scantron_config{'LastName'}-1,
                   5212: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5213:     if ($just_header) { return \%record; }
1.194     albertel 5214: 
1.82      albertel 5215:     my @alphabet=('A'..'Z');
                   5216:     my $questnum=0;
1.447     foxr     5217:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5218: 
1.82      albertel 5219:     while ($questions) {
1.447     foxr     5220: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5221: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5222: 
                   5223: 
                   5224: 
1.82      albertel 5225: 	$questnum++;
1.447     foxr     5226: 	my $currentquest = substr($questions,0,$answer_length);
                   5227: 	$questions       = substr($questions,0,$answer_length)='';
                   5228: 	if (length($currentquest) < $answer_length) { next; }
                   5229: 
                   5230: 	# Qon letter implies for each slot in currentquest we have:
                   5231: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5232:         #    about anything else (esp. a value of Qoff for missing
                   5233: 	#    bubbles.
                   5234: 
                   5235: 
1.239     albertel 5236: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5237: 
                   5238: 	    if ($currentquest =~ /\?/
                   5239: 		|| $currentquest =~ /\*/
                   5240: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5241: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5242: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5243: 		    $record{"scantron.$ansnum.answer"}='';
                   5244: 		    $ansnum++;
                   5245: 		}
                   5246: 
1.389     albertel 5247: 	    } elsif (!defined($currentquest)
1.447     foxr     5248: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5249: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5250: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5251: 		    $record{"scantron.$ansnum.answer"}='';
                   5252: 		    $ansnum++;
                   5253: 
                   5254: 		}
1.239     albertel 5255: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5256: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5257: 		    $ansnum += $answers_needed;
1.239     albertel 5258: 		}
1.447     foxr     5259: 
1.239     albertel 5260: 	    } else {
1.447     foxr     5261: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5262: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5263: 		    $ansnum++;
                   5264: 		}
1.239     albertel 5265: 	    }
1.447     foxr     5266: 
                   5267: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5268: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5269:         #    and *? for double bubbles on a line.
                   5270: 	#    these answers are also stored as letters.
                   5271: 
1.239     albertel 5272: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5273: 	    if ($currentquest =~ /\?/
                   5274: 		|| $currentquest =~ /\*/
                   5275: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5276: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5277: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5278: 		    $record{"scantron.$ansnum.answer"}='';
                   5279: 		    $ansnum++;
                   5280: 		}
                   5281: 
1.389     albertel 5282: 	    } elsif (!defined($currentquest)
1.447     foxr     5283: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5284: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5285: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5286: 		    $record{"scantron.$ansnum.answer"}='';
                   5287: 		    $ansnum++;
                   5288: 
                   5289: 		}
1.239     albertel 5290: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5291: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5292: 		    $ansnum += $answers_needed;
1.239     albertel 5293: 		}
1.447     foxr     5294: 
1.239     albertel 5295: 	    } else {
1.447     foxr     5296: 		$currentquest = &digits_to_letters($currentquest);
                   5297: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5298: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5299: 		    $ansnum++;
1.371     albertel 5300: 		}
1.239     albertel 5301: 	    }
1.82      albertel 5302: 	} else {
1.447     foxr     5303: 
                   5304: 	    # Otherwise there's a positional notation;
                   5305: 	    # each bubble line requires Qlength items, and there are filled in
                   5306: 	    # bubbles for each case where there 'Qon' characters.
                   5307: 	    #
                   5308: 
1.239     albertel 5309: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5310: 
                   5311: 	    # If the split only  giveas us one element.. the full length of the
                   5312: 	    # answser string, no bubbles are filled in:
                   5313: 
                   5314: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5315: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5316: 		    $record{"scantron.$ansnum.answer"}='';
                   5317: 		    $ansnum++;
                   5318: 
                   5319: 		}
1.239     albertel 5320: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5321: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5322: 		}
1.447     foxr     5323: 	    } elsif (scalar(@array) lt 2) {
                   5324: 
                   5325: 		my $location      = [length($array[0])];
                   5326: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5327: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5328: 
                   5329: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5330: 		    if ($ans eq $line_num) {
                   5331: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5332: 		    } else {
                   5333: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5334: 		    }
                   5335: 		    $ansnum++;
                   5336: 		}
1.239     albertel 5337: 	    }
1.447     foxr     5338: 	    #  If there's more than one instance of a bubble character
                   5339: 	    #  That's a double bubble; with positional notation we can
                   5340: 	    #  record all the bubbles filled in as well as the 
                   5341: 	    #  fact this response consists of multiple bubbles.
                   5342: 	    #
                   5343: 	    else {
1.239     albertel 5344: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5345: 
                   5346: 		my $first_answer = $ansnum;
                   5347: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5348: 		    $record{"scantron.$ansnum.answer"} = '';
                   5349: 		    $ans++;
                   5350: 		}
                   5351: 
1.239     albertel 5352: 		my @ans=@array;
                   5353: 		my $i=length($ans[0]);shift(@ans);
                   5354: 		while ($#ans) {
                   5355: 		    $i+=length($ans[0])+1;
1.447     foxr     5356: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5357: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5358: 
                   5359: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5360: 		    shift(@ans);
                   5361: 		}
                   5362: 	    }
1.82      albertel 5363: 	}
                   5364:     }
1.83      albertel 5365:     $record{'scantron.maxquest'}=$questnum;
                   5366:     return \%record;
1.82      albertel 5367: }
                   5368: 
1.423     albertel 5369: =pod
                   5370: 
                   5371: =item scantron_add_delay
                   5372: 
                   5373:    Adds an error message that occurred during the grading phase to a
                   5374:    queue of messages to be shown after grading pass is complete
                   5375: 
                   5376:  Arguments:
1.424     albertel 5377:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5378:    $scanline    - the scanline that caused the error
                   5379:    $errormesage - the error message
                   5380:    $errorcode   - a numeric code for the error
                   5381: 
                   5382:  Side Effects:
1.424     albertel 5383:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5384: 
                   5385: =cut
                   5386: 
1.82      albertel 5387: sub scantron_add_delay {
1.140     albertel 5388:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5389:     push(@$delayqueue,
                   5390: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5391: 	  'ecode' => $errorcode }
                   5392: 	 );
1.82      albertel 5393: }
                   5394: 
1.423     albertel 5395: =pod
                   5396: 
                   5397: =item scantron_find_student
                   5398: 
1.424     albertel 5399:    Finds the username for the current scanline
                   5400: 
                   5401:   Arguments:
                   5402:    $scantron_record - hash result from scantron_parse_scanline
                   5403:    $scan_data       - hash of correction information 
                   5404:                       (see &scantron_getfile() form more information)
                   5405:    $idmap           - hash from &username_to_idmap()
                   5406:    $line            - number of current scanline
                   5407:  
                   5408:   Returns:
                   5409:    Either 'username:domain' or undef if unknown
                   5410: 
1.423     albertel 5411: =cut
                   5412: 
1.82      albertel 5413: sub scantron_find_student {
1.157     albertel 5414:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5415:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5416:     if ($scanID =~ /^\s*$/) {
                   5417:  	return &scan_data($scan_data,"$line.user");
                   5418:     }
1.83      albertel 5419:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5420:  	if (lc($id) eq lc($scanID)) {
                   5421:  	    return $$idmap{$id};
                   5422:  	}
1.83      albertel 5423:     }
                   5424:     return undef;
                   5425: }
                   5426: 
1.423     albertel 5427: =pod
                   5428: 
                   5429: =item scantron_filter
                   5430: 
1.424     albertel 5431:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5432:    hidden resources was selected
                   5433: 
1.423     albertel 5434: =cut
                   5435: 
1.83      albertel 5436: sub scantron_filter {
                   5437:     my ($curres)=@_;
1.331     albertel 5438: 
                   5439:     if (ref($curres) && $curres->is_problem()) {
                   5440: 	# if the user has asked to not have either hidden
                   5441: 	# or 'randomout' controlled resources to be graded
                   5442: 	# don't include them
                   5443: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5444: 	    && $curres->randomout) {
                   5445: 	    return 0;
                   5446: 	}
1.83      albertel 5447: 	return 1;
                   5448:     }
                   5449:     return 0;
1.82      albertel 5450: }
                   5451: 
1.423     albertel 5452: =pod
                   5453: 
                   5454: =item scantron_process_corrections
                   5455: 
1.424     albertel 5456:    Gets correction information out of submitted form data and corrects
                   5457:    the scanline
                   5458: 
1.423     albertel 5459: =cut
                   5460: 
1.157     albertel 5461: sub scantron_process_corrections {
                   5462:     my ($r) = @_;
1.257     albertel 5463:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5464:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5465:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5466:     my $which=$env{'form.scantron_line'};
1.200     albertel 5467:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5468:     my ($skip,$err,$errmsg);
1.257     albertel 5469:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5470: 	$skip=1;
1.257     albertel 5471:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5472: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5473: 	    $env{'form.scantron_domain'};
1.157     albertel 5474: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5475: 	($line,$err,$errmsg)=
                   5476: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5477: 				     'ID',{'newid'=>$newid,
1.257     albertel 5478: 				    'username'=>$env{'form.scantron_username'},
                   5479: 				    'domain'=>$env{'form.scantron_domain'}});
                   5480:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5481: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5482: 	my $newCODE;
1.192     albertel 5483: 	my %args;
1.190     albertel 5484: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5485: 	    $newCODE='use_unfound';
1.190     albertel 5486: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5487: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5488: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5489: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5490: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5491: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5492: 	}
1.257     albertel 5493: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5494: 	    $args{'CODE_ignore_dup'}=1;
                   5495: 	}
                   5496: 	$args{'CODE'}=$newCODE;
1.186     albertel 5497: 	($line,$err,$errmsg)=
                   5498: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5499: 				     'CODE',\%args);
1.257     albertel 5500:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5501: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5502: 	    ($line,$err,$errmsg)=
                   5503: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5504: 					 $which,'answer',
                   5505: 					 { 'question'=>$question,
1.257     albertel 5506: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5507: 	    if ($err) { last; }
                   5508: 	}
                   5509:     }
                   5510:     if ($err) {
1.398     albertel 5511: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5512:     } else {
1.200     albertel 5513: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5514: 	&scantron_putfile($scanlines,$scan_data);
                   5515:     }
                   5516: }
                   5517: 
1.423     albertel 5518: =pod
                   5519: 
                   5520: =item reset_skipping_status
                   5521: 
1.424     albertel 5522:    Forgets the current set of remember skipped scanlines (and thus
                   5523:    reverts back to considering all lines in the
                   5524:    scantron_skipped_<filename> file)
                   5525: 
1.423     albertel 5526: =cut
                   5527: 
1.200     albertel 5528: sub reset_skipping_status {
                   5529:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5530:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5531:     &scantron_putfile(undef,$scan_data);
                   5532: }
                   5533: 
1.423     albertel 5534: =pod
                   5535: 
                   5536: =item start_skipping
                   5537: 
1.424     albertel 5538:    Marks a scanline to be skipped. 
                   5539: 
1.423     albertel 5540: =cut
                   5541: 
1.376     albertel 5542: sub start_skipping {
1.200     albertel 5543:     my ($scan_data,$i)=@_;
                   5544:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5545:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5546: 	$remembered{$i}=2;
                   5547:     } else {
                   5548: 	$remembered{$i}=1;
                   5549:     }
1.200     albertel 5550:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5551: }
                   5552: 
1.423     albertel 5553: =pod
                   5554: 
                   5555: =item should_be_skipped
                   5556: 
1.424     albertel 5557:    Checks whether a scanline should be skipped.
                   5558: 
1.423     albertel 5559: =cut
                   5560: 
1.200     albertel 5561: sub should_be_skipped {
1.376     albertel 5562:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5563:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5564: 	# not redoing old skips
1.376     albertel 5565: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5566: 	return 0;
                   5567:     }
                   5568:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5569: 
                   5570:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5571: 	return 0;
                   5572:     }
1.200     albertel 5573:     return 1;
                   5574: }
                   5575: 
1.423     albertel 5576: =pod
                   5577: 
                   5578: =item remember_current_skipped
                   5579: 
1.424     albertel 5580:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5581:    file and remembers them into scan_data for later use.
                   5582: 
1.423     albertel 5583: =cut
                   5584: 
1.200     albertel 5585: sub remember_current_skipped {
                   5586:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5587:     my %to_remember;
                   5588:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5589: 	if ($scanlines->{'skipped'}[$i]) {
                   5590: 	    $to_remember{$i}=1;
                   5591: 	}
                   5592:     }
1.376     albertel 5593: 
1.200     albertel 5594:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5595:     &scantron_putfile(undef,$scan_data);
                   5596: }
                   5597: 
1.423     albertel 5598: =pod
                   5599: 
                   5600: =item check_for_error
                   5601: 
1.424     albertel 5602:     Checks if there was an error when attempting to remove a specific
                   5603:     scantron_.. bubble sheet data file. Prints out an error if
                   5604:     something went wrong.
                   5605: 
1.423     albertel 5606: =cut
                   5607: 
1.200     albertel 5608: sub check_for_error {
                   5609:     my ($r,$result)=@_;
                   5610:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5611: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5612:     }
                   5613: }
1.157     albertel 5614: 
1.423     albertel 5615: =pod
                   5616: 
                   5617: =item scantron_warning_screen
                   5618: 
1.424     albertel 5619:    Interstitial screen to make sure the operator has selected the
                   5620:    correct options before we start the validation phase.
                   5621: 
1.423     albertel 5622: =cut
                   5623: 
1.203     albertel 5624: sub scantron_warning_screen {
                   5625:     my ($button_text)=@_;
1.257     albertel 5626:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5627:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5628:     my $CODElist;
1.284     albertel 5629:     if ($scantron_config{'CODElocation'} &&
                   5630: 	$scantron_config{'CODEstart'} &&
                   5631: 	$scantron_config{'CODElength'}) {
                   5632: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5633: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5634: 	$CODElist=
                   5635: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5636: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5637:     }
1.203     albertel 5638:     return (<<STUFF);
                   5639: <p>
1.398     albertel 5640: <span class="LC_warning">Please double check the information
                   5641:                  below before clicking on '$button_text'</span>
1.203     albertel 5642: </p>
                   5643: <table>
1.284     albertel 5644: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5645: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5646: $CODElist
1.203     albertel 5647: </table>
                   5648: <br />
                   5649: <p> If this information is correct, please click on '$button_text'.</p>
                   5650: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5651: 
                   5652: <br />
                   5653: STUFF
                   5654: }
                   5655: 
1.423     albertel 5656: =pod
                   5657: 
                   5658: =item scantron_do_warning
                   5659: 
1.424     albertel 5660:    Check if the operator has picked something for all required
                   5661:    fields. Error out if something is missing.
                   5662: 
1.423     albertel 5663: =cut
                   5664: 
1.203     albertel 5665: sub scantron_do_warning {
                   5666:     my ($r)=@_;
1.324     albertel 5667:     my ($symb)=&get_symb($r);
1.203     albertel 5668:     if (!$symb) {return '';}
1.324     albertel 5669:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5670:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5671:     if ( $env{'form.selectpage'} eq '' ||
                   5672: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5673: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5674: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5675: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5676: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5677: 	} 
1.257     albertel 5678: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5679: 	    $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 5680: 	} 
1.257     albertel 5681: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5682: 	    $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 5683: 	} 
                   5684:     } else {
1.265     www      5685: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5686: 	$r->print(<<STUFF);
1.203     albertel 5687: $warning
1.265     www      5688: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5689: <input type="hidden" name="command" value="scantron_validate" />
                   5690: STUFF
1.237     albertel 5691:     }
1.352     albertel 5692:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5693:     return '';
                   5694: }
                   5695: 
1.423     albertel 5696: =pod
                   5697: 
                   5698: =item scantron_form_start
                   5699: 
1.424     albertel 5700:     html hidden input for remembering all selected grading options
                   5701: 
1.423     albertel 5702: =cut
                   5703: 
1.203     albertel 5704: sub scantron_form_start {
                   5705:     my ($max_bubble)=@_;
                   5706:     my $result= <<SCANTRONFORM;
                   5707: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5708:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5709:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5710:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5711:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5712:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5713:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5714:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5715:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5716:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5717: SCANTRONFORM
1.447     foxr     5718: 
                   5719:   my $line = 0;
                   5720:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448     foxr     5721: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5722:        my $chunk =
                   5723: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5724:        $chunk .=
                   5725: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5726:        $result .= $chunk;
                   5727:        $line++;
                   5728:    }
1.203     albertel 5729:     return $result;
                   5730: }
                   5731: 
1.423     albertel 5732: =pod
                   5733: 
                   5734: =item scantron_validate_file
                   5735: 
1.424     albertel 5736:     Dispatch routine for doing validation of a bubble sheet data file.
                   5737: 
                   5738:     Also processes any necessary information resets that need to
                   5739:     occur before validation begins (ignore previous corrections,
                   5740:     restarting the skipped records processing)
                   5741: 
1.423     albertel 5742: =cut
                   5743: 
1.157     albertel 5744: sub scantron_validate_file {
                   5745:     my ($r) = @_;
1.324     albertel 5746:     my ($symb)=&get_symb($r);
1.157     albertel 5747:     if (!$symb) {return '';}
1.324     albertel 5748:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5749:     
                   5750:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5751:     # them when doing the corrections reset
1.257     albertel 5752:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5753: 	&reset_skipping_status();
                   5754:     }
1.257     albertel 5755:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5756: 	&remember_current_skipped();
1.257     albertel 5757: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5758:     }
                   5759: 
1.257     albertel 5760:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5761: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5762: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5763: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5764: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5765:     }
1.200     albertel 5766: 
1.257     albertel 5767:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5768: 	&scantron_process_corrections($r);
                   5769:     }
1.424     albertel 5770:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5771:     #get the student pick code ready
                   5772:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5773:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5774:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5775:     $r->print($result);
                   5776:     
1.334     albertel 5777:     my @validate_phases=( 'sequence',
                   5778: 			  'ID',
1.157     albertel 5779: 			  'CODE',
                   5780: 			  'doublebubble',
                   5781: 			  'missingbubbles');
1.257     albertel 5782:     if (!$env{'form.validatepass'}) {
                   5783: 	$env{'form.validatepass'} = 0;
1.157     albertel 5784:     }
1.257     albertel 5785:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5786: 
1.448     foxr     5787:     &Apache::lonnet::logthis("Phase: $currentphase");
                   5788: 
1.157     albertel 5789:     my $stop=0;
                   5790:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5791: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5792: 	$r->rflush();
                   5793: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5794: 	{
                   5795: 	    no strict 'refs';
                   5796: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5797: 	}
                   5798:     }
                   5799:     if (!$stop) {
1.203     albertel 5800: 	my $warning=&scantron_warning_screen('Start Grading');
                   5801: 	$r->print(<<STUFF);
                   5802: Validation process complete.<br />
                   5803: $warning
                   5804: <input type="submit" name="submit" value="Start Grading" />
                   5805: <input type="hidden" name="command" value="scantron_process" />
                   5806: STUFF
                   5807: 
1.157     albertel 5808:     } else {
                   5809: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5810: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5811:     }
                   5812:     if ($stop) {
1.334     albertel 5813: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5814: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5815: 	    $r->print(' this error <br />');
                   5816: 
                   5817: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5818: 	} else {
                   5819: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5820: 	    $r->print(' using corrected info <br />');
                   5821: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5822: 	    $r->print(" this scanline saving it for later.");
                   5823: 	}
1.157     albertel 5824:     }
1.352     albertel 5825:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5826:     return '';
                   5827: }
                   5828: 
1.423     albertel 5829: 
                   5830: =pod
                   5831: 
                   5832: =item scantron_remove_file
                   5833: 
1.424     albertel 5834:    Removes the requested bubble sheet data file, makes sure that
                   5835:    scantron_original_<filename> is never removed
                   5836: 
                   5837: 
1.423     albertel 5838: =cut
                   5839: 
1.200     albertel 5840: sub scantron_remove_file {
1.192     albertel 5841:     my ($which)=@_;
1.257     albertel 5842:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5843:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5844:     my $file='scantron_';
1.200     albertel 5845:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5846: 	$file.=$which.'_';
1.192     albertel 5847:     } else {
                   5848: 	return 'refused';
                   5849:     }
1.257     albertel 5850:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5851:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5852: }
                   5853: 
1.423     albertel 5854: 
                   5855: =pod
                   5856: 
                   5857: =item scantron_remove_scan_data
                   5858: 
1.424     albertel 5859:    Removes all scan_data correction for the requested bubble sheet
                   5860:    data file.  (In the case that both the are doing skipped records we need
                   5861:    to remember the old skipped lines for the time being so that element
                   5862:    persists for a while.)
                   5863: 
1.423     albertel 5864: =cut
                   5865: 
1.200     albertel 5866: sub scantron_remove_scan_data {
1.257     albertel 5867:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5869:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5870:     my @todelete;
1.257     albertel 5871:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5872:     foreach my $key (@keys) {
                   5873: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5874: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5875: 		$key=~/remember_skipping/) {
                   5876: 		next;
                   5877: 	    }
1.192     albertel 5878: 	    push(@todelete,$key);
                   5879: 	}
                   5880:     }
1.200     albertel 5881:     my $result;
1.192     albertel 5882:     if (@todelete) {
1.200     albertel 5883: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5884:     }
                   5885:     return $result;
                   5886: }
                   5887: 
1.423     albertel 5888: 
                   5889: =pod
                   5890: 
                   5891: =item scantron_getfile
                   5892: 
1.424     albertel 5893:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5894:     the scan_data hash
                   5895:   
                   5896:   Arguments:
                   5897:     None
                   5898: 
                   5899:   Returns:
                   5900:     2 hash references
                   5901: 
                   5902:      - first one has 
                   5903:          orig      -
                   5904:          corrected -
                   5905:          skipped   -  each of which points to an array ref of the specified
                   5906:                       file broken up into individual lines
                   5907:          count     - number of scanlines
                   5908:  
                   5909:      - second is the scan_data hash possible keys are
1.425     albertel 5910:        ($number refers to scanline numbered $number and thus the key affects
                   5911:         only that scanline
                   5912:         $bubline refers to the specific bubble line element and the aspects
                   5913:         refers to that specific bubble line element)
                   5914: 
                   5915:        $number.user - username:domain to use
                   5916:        $number.CODE_ignore_dup 
                   5917:                     - ignore the duplicate CODE error 
                   5918:        $number.useCODE
                   5919:                     - use the CODE in the scanline as is
                   5920:        $number.no_bubble.$bubline
                   5921:                     - it is valid that there is no bubbled in bubble
                   5922:                       at $number $bubline
                   5923:        remember_skipping
                   5924:                     - a frozen hash containing keys of $number and values
                   5925:                       of either 
                   5926:                         1 - we are on a 'do skipped records pass' and plan
                   5927:                             on processing this line
                   5928:                         2 - we are on a 'do skipped records pass' and this
                   5929:                             scanline has been marked to skip yet again
1.424     albertel 5930: 
1.423     albertel 5931: =cut
                   5932: 
1.157     albertel 5933: sub scantron_getfile {
1.200     albertel 5934:     #FIXME really would prefer a scantron directory
1.257     albertel 5935:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5936:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5937:     my $lines;
                   5938:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5939: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5940:     my %scanlines;
                   5941:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5942:     my $temp=$scanlines{'orig'};
                   5943:     $scanlines{'count'}=$#$temp;
                   5944: 
                   5945:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5946: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5947:     if ($lines eq '-1') {
                   5948: 	$scanlines{'corrected'}=[];
                   5949:     } else {
                   5950: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5951:     }
                   5952:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5953: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5954:     if ($lines eq '-1') {
                   5955: 	$scanlines{'skipped'}=[];
                   5956:     } else {
                   5957: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5958:     }
1.175     albertel 5959:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5960:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5961:     my %scan_data = @tmp;
                   5962:     return (\%scanlines,\%scan_data);
                   5963: }
                   5964: 
1.423     albertel 5965: =pod
                   5966: 
                   5967: =item lonnet_putfile
                   5968: 
1.424     albertel 5969:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5970: 
                   5971:  Arguments:
                   5972:    $contents - data to store
                   5973:    $filename - filename to store $contents into
                   5974: 
                   5975:  Returns:
                   5976:    result value from &Apache::lonnet::finishuserfileupload
                   5977: 
1.423     albertel 5978: =cut
                   5979: 
1.157     albertel 5980: sub lonnet_putfile {
                   5981:     my ($contents,$filename)=@_;
1.257     albertel 5982:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5983:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5984:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5985:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5986: 
                   5987: }
                   5988: 
1.423     albertel 5989: =pod
                   5990: 
                   5991: =item scantron_putfile
                   5992: 
1.424     albertel 5993:     Stores the current version of the bubble sheet data files, and the
                   5994:     scan_data hash. (Does not modify the original version only the
                   5995:     corrected and skipped versions.
                   5996: 
                   5997:  Arguments:
                   5998:     $scanlines - hash ref that looks like the first return value from
                   5999:                  &scantron_getfile()
                   6000:     $scan_data - hash ref that looks like the second return value from
                   6001:                  &scantron_getfile()
                   6002: 
1.423     albertel 6003: =cut
                   6004: 
1.157     albertel 6005: sub scantron_putfile {
                   6006:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6007:     #FIXME really would prefer a scantron directory
1.257     albertel 6008:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6009:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6010:     if ($scanlines) {
                   6011: 	my $prefix='scantron_';
1.157     albertel 6012: # no need to update orig, shouldn't change
                   6013: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6014: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6015: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6016: 			$prefix.'corrected_'.
1.257     albertel 6017: 			$env{'form.scantron_selectfile'});
1.200     albertel 6018: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6019: 			$prefix.'skipped_'.
1.257     albertel 6020: 			$env{'form.scantron_selectfile'});
1.200     albertel 6021:     }
1.175     albertel 6022:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6023: }
                   6024: 
1.423     albertel 6025: =pod
                   6026: 
                   6027: =item scantron_get_line
                   6028: 
1.424     albertel 6029:    Returns the correct version of the scanline
                   6030: 
                   6031:  Arguments:
                   6032:     $scanlines - hash ref that looks like the first return value from
                   6033:                  &scantron_getfile()
                   6034:     $scan_data - hash ref that looks like the second return value from
                   6035:                  &scantron_getfile()
                   6036:     $i         - number of the requested line (starts at 0)
                   6037: 
                   6038:  Returns:
                   6039:    A scanline, (either the original or the corrected one if it
                   6040:    exists), or undef if the requested scanline should be
                   6041:    skipped. (Either because it's an skipped scanline, or it's an
                   6042:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6043:    pass.
                   6044: 
1.423     albertel 6045: =cut
                   6046: 
1.157     albertel 6047: sub scantron_get_line {
1.200     albertel 6048:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6049:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6050:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6051:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6052:     return $scanlines->{'orig'}[$i]; 
                   6053: }
                   6054: 
1.423     albertel 6055: =pod
                   6056: 
                   6057: =item scantron_todo_count
                   6058: 
1.424     albertel 6059:     Counts the number of scanlines that need processing.
                   6060: 
                   6061:  Arguments:
                   6062:     $scanlines - hash ref that looks like the first return value from
                   6063:                  &scantron_getfile()
                   6064:     $scan_data - hash ref that looks like the second return value from
                   6065:                  &scantron_getfile()
                   6066: 
                   6067:  Returns:
                   6068:     $count - number of scanlines to process
                   6069: 
1.423     albertel 6070: =cut
                   6071: 
1.200     albertel 6072: sub get_todo_count {
                   6073:     my ($scanlines,$scan_data)=@_;
                   6074:     my $count=0;
                   6075:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6076: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6077: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6078: 	$count++;
                   6079:     }
                   6080:     return $count;
                   6081: }
                   6082: 
1.423     albertel 6083: =pod
                   6084: 
                   6085: =item scantron_put_line
                   6086: 
1.424     albertel 6087:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6088:     data file.
                   6089: 
                   6090:  Arguments:
                   6091:     $scanlines - hash ref that looks like the first return value from
                   6092:                  &scantron_getfile()
                   6093:     $scan_data - hash ref that looks like the second return value from
                   6094:                  &scantron_getfile()
                   6095:     $i         - line number to update
                   6096:     $newline   - contents of the updated scanline
                   6097:     $skip      - if true make the line for skipping and update the
                   6098:                  'skipped' file
                   6099: 
1.423     albertel 6100: =cut
                   6101: 
1.157     albertel 6102: sub scantron_put_line {
1.200     albertel 6103:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6104:     if ($skip) {
                   6105: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6106: 	&start_skipping($scan_data,$i);
1.157     albertel 6107: 	return;
                   6108:     }
                   6109:     $scanlines->{'corrected'}[$i]=$newline;
                   6110: }
                   6111: 
1.423     albertel 6112: =pod
                   6113: 
                   6114: =item scantron_clear_skip
                   6115: 
1.424     albertel 6116:    Remove a line from the 'skipped' file
                   6117: 
                   6118:  Arguments:
                   6119:     $scanlines - hash ref that looks like the first return value from
                   6120:                  &scantron_getfile()
                   6121:     $scan_data - hash ref that looks like the second return value from
                   6122:                  &scantron_getfile()
                   6123:     $i         - line number to update
                   6124: 
1.423     albertel 6125: =cut
                   6126: 
1.376     albertel 6127: sub scantron_clear_skip {
                   6128:     my ($scanlines,$scan_data,$i)=@_;
                   6129:     if (exists($scanlines->{'skipped'}[$i])) {
                   6130: 	undef($scanlines->{'skipped'}[$i]);
                   6131: 	return 1;
                   6132:     }
                   6133:     return 0;
                   6134: }
                   6135: 
1.423     albertel 6136: =pod
                   6137: 
                   6138: =item scantron_filter_not_exam
                   6139: 
1.424     albertel 6140:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6141:    filter out resources that are not marked as 'exam' mode
                   6142: 
1.423     albertel 6143: =cut
                   6144: 
1.334     albertel 6145: sub scantron_filter_not_exam {
                   6146:     my ($curres)=@_;
                   6147:     
                   6148:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6149: 	# if the user has asked to not have either hidden
                   6150: 	# or 'randomout' controlled resources to be graded
                   6151: 	# don't include them
                   6152: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6153: 	    && $curres->randomout) {
                   6154: 	    return 0;
                   6155: 	}
                   6156: 	return 1;
                   6157:     }
                   6158:     return 0;
                   6159: }
                   6160: 
1.423     albertel 6161: =pod
                   6162: 
                   6163: =item scantron_validate_sequence
                   6164: 
1.424     albertel 6165:     Validates the selected sequence, checking for resource that are
                   6166:     not set to exam mode.
                   6167: 
1.423     albertel 6168: =cut
                   6169: 
1.334     albertel 6170: sub scantron_validate_sequence {
                   6171:     my ($r,$currentphase) = @_;
                   6172: 
                   6173:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6174:     my (undef,undef,$sequence)=
                   6175: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6176: 
                   6177:     my $map=$navmap->getResourceByUrl($sequence);
                   6178: 
                   6179:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6180:                                     value="ignore" />');
                   6181:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6182: 	my @resources=
                   6183: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6184: 	if (@resources) {
1.357     banghart 6185: 	    $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 6186: 	    return (1,$currentphase);
                   6187: 	}
                   6188:     }
                   6189: 
                   6190:     return (0,$currentphase+1);
                   6191: }
                   6192: 
1.423     albertel 6193: =pod
                   6194: 
                   6195: =item scantron_validate_ID
                   6196: 
1.424     albertel 6197:    Validates all scanlines in the selected file to not have any
                   6198:    invalid or underspecified student IDs
                   6199: 
1.423     albertel 6200: =cut
                   6201: 
1.157     albertel 6202: sub scantron_validate_ID {
                   6203:     my ($r,$currentphase) = @_;
                   6204:     
                   6205:     #get student info
                   6206:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6207:     my %idmap=&username_to_idmap($classlist);
                   6208: 
                   6209:     #get scantron line setup
1.257     albertel 6210:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6211:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6212:     
                   6213:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6214: 
                   6215:     my %found=('ids'=>{},'usernames'=>{});
                   6216:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6217: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6218: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6219: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6220: 						 $scan_data);
                   6221: 	my $id=$$scan_record{'scantron.ID'};
                   6222: 	my $found;
                   6223: 	foreach my $checkid (keys(%idmap)) {
                   6224: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6225: 	}
                   6226: 	if ($found) {
                   6227: 	    my $username=$idmap{$found};
                   6228: 	    if ($found{'ids'}{$found}) {
                   6229: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6230: 					 $line,'duplicateID',$found);
1.194     albertel 6231: 		return(1,$currentphase);
1.157     albertel 6232: 	    } elsif ($found{'usernames'}{$username}) {
                   6233: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6234: 					 $line,'duplicateID',$username);
1.194     albertel 6235: 		return(1,$currentphase);
1.157     albertel 6236: 	    }
1.186     albertel 6237: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6238: 	    $found{'ids'}{$found}++;
                   6239: 	    $found{'usernames'}{$username}++;
                   6240: 	} else {
                   6241: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6242: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6243: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6244: 		    &scantron_get_correction($r,$i,$scan_record,
                   6245: 					     \%scantron_config,
                   6246: 					     $line,'duplicateID',$username);
1.194     albertel 6247: 		    return(1,$currentphase);
1.157     albertel 6248: 		} elsif (!defined($username)) {
                   6249: 		    &scantron_get_correction($r,$i,$scan_record,
                   6250: 					     \%scantron_config,
                   6251: 					     $line,'incorrectID');
1.194     albertel 6252: 		    return(1,$currentphase);
1.157     albertel 6253: 		}
                   6254: 		$found{'usernames'}{$username}++;
                   6255: 	    } else {
                   6256: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6257: 					 $line,'incorrectID');
1.194     albertel 6258: 		return(1,$currentphase);
1.157     albertel 6259: 	    }
                   6260: 	}
                   6261:     }
                   6262: 
                   6263:     return (0,$currentphase+1);
                   6264: }
                   6265: 
1.423     albertel 6266: =pod
                   6267: 
                   6268: =item scantron_get_correction
                   6269: 
1.424     albertel 6270:    Builds the interface screen to interact with the operator to fix a
                   6271:    specific error condition in a specific scanline
                   6272: 
                   6273:  Arguments:
                   6274:     $r           - Apache request object
                   6275:     $i           - number of the current scanline
                   6276:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6277:     $scan_config - hash ref as returned from &get_scantron_config()
                   6278:     $line        - full contents of the current scanline
                   6279:     $error       - error condition, valid values are
                   6280:                    'incorrectCODE', 'duplicateCODE',
                   6281:                    'doublebubble', 'missingbubble',
                   6282:                    'duplicateID', 'incorrectID'
                   6283:     $arg         - extra information needed
                   6284:        For errors:
                   6285:          - duplicateID   - paper number that this studentID was seen before on
                   6286:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6287:                            seen on before
                   6288:          - incorrectCODE - current incorrect CODE 
                   6289:          - doublebubble  - array ref of the bubble lines that have double
                   6290:                            bubble errors
                   6291:          - missingbubble - array ref of the bubble lines that have missing
                   6292:                            bubble errors
                   6293: 
1.423     albertel 6294: =cut
                   6295: 
1.157     albertel 6296: sub scantron_get_correction {
                   6297:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6298: 
                   6299: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6300: #to show both the current line and the previous one and allow skipping
                   6301: #the previous one or the current one
                   6302: 
1.161     albertel 6303:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6304:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6305: 	$r->print(" for PaperID <tt>".
                   6306: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6307:     } else {
                   6308: 	$r->print(" in scanline $i <pre>".
                   6309: 		  $line."</pre> \n");
                   6310:     }
1.242     albertel 6311:     my $message="<p>The ID on the form is  <tt>".
                   6312: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6313: 	"The name on the paper is ".
                   6314: 	$$scan_record{'scantron.LastName'}.",".
                   6315: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6316: 
1.157     albertel 6317:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6318:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6319:     if ($error =~ /ID$/) {
1.186     albertel 6320: 	if ($error eq 'incorrectID') {
1.157     albertel 6321: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6322: 	} elsif ($error eq 'duplicateID') {
                   6323: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6324: 	}
1.242     albertel 6325: 	$r->print($message);
1.157     albertel 6326: 	$r->print("<p>How should I handle this? <br /> \n");
                   6327: 	$r->print("\n<ul><li> ");
                   6328: 	#FIXME it would be nice if this sent back the user ID and
                   6329: 	#could do partial userID matches
                   6330: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6331: 				       'scantron_username','scantron_domain'));
                   6332: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6333: 	$r->print("\n@".
1.257     albertel 6334: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6335: 
                   6336: 	$r->print('</li>');
1.186     albertel 6337:     } elsif ($error =~ /CODE$/) {
                   6338: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6339: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6340: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6341: 	    $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 6342: 	}
1.224     albertel 6343: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6344: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6345: 	$r->print($message);
1.186     albertel 6346: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6347: 	$r->print("\n<br /> ");
1.194     albertel 6348: 	my $i=0;
1.273     albertel 6349: 	if ($error eq 'incorrectCODE' 
                   6350: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6351: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6352: 	    if ($closest > 0) {
                   6353: 		foreach my $testcode (@{$closest}) {
                   6354: 		    my $checked='';
1.401     albertel 6355: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6356: 		    $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' />");
                   6357: 		    $r->print("\n<br />");
                   6358: 		    $i++;
                   6359: 		}
1.194     albertel 6360: 	    }
                   6361: 	}
1.273     albertel 6362: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6363: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6364: 	    $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>");
                   6365: 	    $r->print("\n<br />");
                   6366: 	}
1.194     albertel 6367: 
1.188     albertel 6368: 	$r->print(<<ENDSCRIPT);
                   6369: <script type="text/javascript">
                   6370: function change_radio(field) {
1.190     albertel 6371:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6372:     var i;
                   6373:     for (i=0;i<slct.length;i++) {
                   6374:         if (slct[i].value==field) { slct[i].checked=true; }
                   6375:     }
                   6376: }
                   6377: </script>
                   6378: ENDSCRIPT
1.187     albertel 6379: 	my $href="/adm/pickcode?".
1.359     www      6380: 	   "form=".&escape("scantronupload").
                   6381: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6382: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6383: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6384: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6385: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6386: 	    $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')\" />");
                   6387: 	    $r->print("\n<br />");
                   6388: 	}
1.272     albertel 6389: 	$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 6390: 	$r->print("\n<br /><br />");
1.157     albertel 6391:     } elsif ($error eq 'doublebubble') {
                   6392: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6393: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6394: 		  join(',',@{$arg}).'" />');
1.242     albertel 6395: 	$r->print($message);
1.157     albertel 6396: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6397: 	foreach my $question (@{$arg}) {
1.447     foxr     6398: 
                   6399: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6400: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6401: 				      split('',$selected));
1.157     albertel 6402: 	}
                   6403:     } elsif ($error eq 'missingbubble') {
                   6404: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6405: 	$r->print($message);
1.157     albertel 6406: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6407: 	$r->print("Some questions have no scanned bubbles\n");
                   6408: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6409: 		  join(',',@{$arg}).'" />');
                   6410: 	foreach my $question (@{$arg}) {
1.448     foxr     6411: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6412: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6413: 	}
                   6414:     } else {
                   6415: 	$r->print("\n<ul>");
                   6416:     }
                   6417:     $r->print("\n</li></ul>");
                   6418: 
                   6419: }
1.423     albertel 6420: 
                   6421: =pod
                   6422: 
                   6423: =item scantron_bubble_selector
                   6424:   
                   6425:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6426:    possibly showing the existing the selected bubbles if known
1.423     albertel 6427: 
                   6428:  Arguments:
                   6429:     $r           - Apache request object
                   6430:     $scan_config - hash from &get_scantron_config()
                   6431:     $quest       - number of the bubble line to make a corrector for
                   6432:     $selected    - array of letters of previously selected bubbles
                   6433: 
                   6434: =cut
                   6435: 
1.157     albertel 6436: sub scantron_bubble_selector {
1.447     foxr     6437:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6438:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6439: 
                   6440:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6441: 
                   6442: 
1.274     albertel 6443:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6444: 
1.448     foxr     6445:     my $response = $quest-1;
                   6446:     my $lines = $bubble_lines_per_response{$response};
                   6447:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6448: 
1.422     foxr     6449:     my $total_lines = $lines*2;
1.157     albertel 6450:     my @alphabet=('A'..'Z');
1.422     foxr     6451:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6452: 
                   6453:     for (my $l = 0; $l < $lines; $l++) {
                   6454: 	if ($l != 0) {
                   6455: 	    $r->print('<tr>');
                   6456: 	}
                   6457: 
                   6458: 	# FIXME:  This loop probably has to be considerably more clever for
                   6459: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6460: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6461: 
                   6462: 	for (my $i=0;$i<$max;$i++) {
                   6463: 	    $r->print("\n".'<td align="center">');
                   6464: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6465: 		$r->print('X'); 
                   6466: 		shift(@selected) ;
                   6467: 	    } else { 
                   6468: 		$r->print('&nbsp;'); 
                   6469: 	    }
                   6470: 	    $r->print('</td>');
                   6471: 	    
                   6472: 	}
                   6473: 
                   6474: 	if ($l == 0) {
                   6475: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6476: 
                   6477: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6478: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6479: 	
                   6480: 	}
                   6481: 
                   6482: 	$r->print('</tr><tr>');
                   6483: 
                   6484: 	# FIXME: This may have to be a bit more clever for
                   6485: 	#        multiline questions (different values e.g..).
                   6486: 
                   6487: 	for (my $i=0;$i<$max;$i++) {
                   6488: 	    $r->print("\n".
                   6489: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6490: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6491: 	}
                   6492: 	$r->print('</tr>');
                   6493: 
                   6494: 	    
1.157     albertel 6495:     }
1.422     foxr     6496:     $r->print('</table>');
1.157     albertel 6497: }
                   6498: 
1.423     albertel 6499: =pod
                   6500: 
                   6501: =item num_matches
                   6502: 
1.424     albertel 6503:    Counts the number of characters that are the same between the two arguments.
                   6504: 
                   6505:  Arguments:
                   6506:    $orig - CODE from the scanline
                   6507:    $code - CODE to match against
                   6508: 
                   6509:  Returns:
                   6510:    $count - integer count of the number of same characters between the
                   6511:             two arguments
                   6512: 
1.423     albertel 6513: =cut
                   6514: 
1.194     albertel 6515: sub num_matches {
                   6516:     my ($orig,$code) = @_;
                   6517:     my @code=split(//,$code);
                   6518:     my @orig=split(//,$orig);
                   6519:     my $same=0;
                   6520:     for (my $i=0;$i<scalar(@code);$i++) {
                   6521: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6522:     }
                   6523:     return $same;
                   6524: }
                   6525: 
1.423     albertel 6526: =pod
                   6527: 
                   6528: =item scantron_get_closely_matching_CODEs
                   6529: 
1.424     albertel 6530:    Cycles through all CODEs and finds the set that has the greatest
                   6531:    number of same characters as the provided CODE
                   6532: 
                   6533:  Arguments:
                   6534:    $allcodes - hash ref returned by &get_codes()
                   6535:    $CODE     - CODE from the current scanline
                   6536: 
                   6537:  Returns:
                   6538:    2 element list
                   6539:     - first elements is number of how closely matching the best fit is 
                   6540:       (5 means best set has 5 matching characters)
                   6541:     - second element is an arrary ref containing the set of valid CODEs
                   6542:       that best fit the passed in CODE
                   6543: 
1.423     albertel 6544: =cut
                   6545: 
1.194     albertel 6546: sub scantron_get_closely_matching_CODEs {
                   6547:     my ($allcodes,$CODE)=@_;
                   6548:     my @CODEs;
                   6549:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6550: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6551:     }
                   6552: 
                   6553:     return ($#CODEs,$CODEs[-1]);
                   6554: }
                   6555: 
1.423     albertel 6556: =pod
                   6557: 
                   6558: =item get_codes
                   6559: 
1.424     albertel 6560:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6561:    set of remembered CODEs.
                   6562: 
                   6563:  Arguments:
                   6564:   $old_name - name of the set of remembered CODEs
                   6565:   $cdom     - domain of the course
                   6566:   $cnum     - internal course name
                   6567: 
                   6568:  Returns:
                   6569:   %allcodes - keys are the valid CODEs, values are all 1
                   6570: 
1.423     albertel 6571: =cut
                   6572: 
1.194     albertel 6573: sub get_codes {
1.280     foxr     6574:     my ($old_name, $cdom, $cnum) = @_;
                   6575:     if (!$old_name) {
                   6576: 	$old_name=$env{'form.scantron_CODElist'};
                   6577:     }
                   6578:     if (!$cdom) {
                   6579: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6580:     }
                   6581:     if (!$cnum) {
                   6582: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6583:     }
1.278     albertel 6584:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6585: 				    $cdom,$cnum);
                   6586:     my %allcodes;
                   6587:     if ($result{"type\0$old_name"} eq 'number') {
                   6588: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6589:     } else {
                   6590: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6591:     }
1.194     albertel 6592:     return %allcodes;
                   6593: }
                   6594: 
1.423     albertel 6595: =pod
                   6596: 
                   6597: =item scantron_validate_CODE
                   6598: 
1.424     albertel 6599:    Validates all scanlines in the selected file to not have any
                   6600:    invalid or underspecified CODEs and that none of the codes are
                   6601:    duplicated if this was requested.
                   6602: 
1.423     albertel 6603: =cut
                   6604: 
1.157     albertel 6605: sub scantron_validate_CODE {
                   6606:     my ($r,$currentphase) = @_;
1.257     albertel 6607:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6608:     if ($scantron_config{'CODElocation'} &&
                   6609: 	$scantron_config{'CODEstart'} &&
                   6610: 	$scantron_config{'CODElength'}) {
1.257     albertel 6611: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6612: 	    &FIXME_blow_up()
                   6613: 	}
                   6614:     } else {
                   6615: 	return (0,$currentphase+1);
                   6616:     }
                   6617:     
                   6618:     my %usedCODEs;
                   6619: 
1.194     albertel 6620:     my %allcodes=&get_codes();
1.186     albertel 6621: 
1.447     foxr     6622:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6623: 
1.186     albertel 6624:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6625:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6626: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6627: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6628: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6629: 						 $scan_data);
                   6630: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6631: 	my $error=0;
1.224     albertel 6632: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6633: 	    &scantron_get_correction($r,$i,$scan_record,
                   6634: 				     \%scantron_config,
                   6635: 				     $line,'incorrectCODE',\%allcodes);
                   6636: 	    return(1,$currentphase);
                   6637: 	}
1.221     albertel 6638: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6639: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6640: 	    &scantron_get_correction($r,$i,$scan_record,
                   6641: 				     \%scantron_config,
1.194     albertel 6642: 				     $line,'incorrectCODE',\%allcodes);
                   6643: 	    return(1,$currentphase);
1.186     albertel 6644: 	}
1.214     albertel 6645: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6646: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6647: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6648: 	    &scantron_get_correction($r,$i,$scan_record,
                   6649: 				     \%scantron_config,
1.194     albertel 6650: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6651: 	    return(1,$currentphase);
1.186     albertel 6652: 	}
1.194     albertel 6653: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6654:     }
1.157     albertel 6655:     return (0,$currentphase+1);
                   6656: }
                   6657: 
1.423     albertel 6658: =pod
                   6659: 
                   6660: =item scantron_validate_doublebubble
                   6661: 
1.424     albertel 6662:    Validates all scanlines in the selected file to not have any
                   6663:    bubble lines with multiple bubbles marked.
                   6664: 
1.423     albertel 6665: =cut
                   6666: 
1.157     albertel 6667: sub scantron_validate_doublebubble {
                   6668:     my ($r,$currentphase) = @_;
                   6669:     #get student info
                   6670:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6671:     my %idmap=&username_to_idmap($classlist);
                   6672: 
                   6673:     #get scantron line setup
1.257     albertel 6674:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6675:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6676: 
                   6677:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6678: 
1.157     albertel 6679:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6680: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6681: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6682: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6683: 						 $scan_data);
                   6684: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6685: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6686: 				 'doublebubble',
                   6687: 				 $$scan_record{'scantron.doubleerror'});
                   6688:     	return (1,$currentphase);
                   6689:     }
                   6690:     return (0,$currentphase+1);
                   6691: }
                   6692: 
1.423     albertel 6693: =pod
                   6694: 
                   6695: =item scantron_get_maxbubble
                   6696: 
1.424     albertel 6697:    Returns the maximum number of bubble lines that are expected to
                   6698:    occur. Does this by walking the selected sequence rendering the
                   6699:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6700:    for what the current value of the problem counter is.
                   6701: 
1.447     foxr     6702:    Caches the results to $env{'form.scantron_maxbubble'},
                   6703:    $env{'form.scantron.bubble_lines.n'} and 
                   6704:    $env{'form.scantron.first_bubble_line.n'}
                   6705:    which are the total number of bubble, lines, the number of bubble
                   6706:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6707: 
1.423     albertel 6708: =cut
                   6709: 
1.330     albertel 6710: sub scantron_get_maxbubble {    
1.448     foxr     6711:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6712:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6713: 	$env{'form.scantron_maxbubble'}) {
1.448     foxr     6714: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6715: 	&restore_bubble_lines();
1.257     albertel 6716: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6717:     }
1.448     foxr     6718:     &Apache::lonnet::logthis("computing");
1.330     albertel 6719: 
1.447     foxr     6720:     my (undef, undef, $sequence) =
1.257     albertel 6721: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6722: 
1.447     foxr     6723:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6724:     my $map=$navmap->getResourceByUrl($sequence);
                   6725:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6726: 
                   6727:     &Apache::lonxml::clear_problem_counter();
                   6728: 
1.435     foxr     6729:     my $uname       = $env{'form.student'};
                   6730:     my $udom        = $env{'form.userdom'};
                   6731:     my $cid         = $env{'request.course.id'};
                   6732:     my $total_lines = 0;
                   6733:     %bubble_lines_per_response = ();
1.447     foxr     6734:     %first_bubble_line         = ();
1.435     foxr     6735: 
1.447     foxr     6736:   
                   6737:     my $response_number = 0;
                   6738:     my $bubble_line     = 0;
1.191     albertel 6739:     foreach my $resource (@resources) {
1.435     foxr     6740: 	my $symb = $resource->symb();
1.447     foxr     6741: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6742: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6743: 					('symb' => $resource->symb()),
                   6744: 					('grade_target' => 'analyze'),
                   6745: 					('grade_courseid' => $cid),
                   6746: 					('grade_domain' => $udom),
                   6747: 					('grade_username' => $uname));
1.436     albertel 6748: 	my (undef, $an) =
1.435     foxr     6749: 	    split(/_HASH_REF__/,$result, 2);
                   6750: 
                   6751: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6752: 
                   6753: 
                   6754: 
                   6755: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6756: 	    my ($trash, $part) = split(/\./, $part_id);
                   6757: 
                   6758: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6759: 
                   6760: 	    # TODO - make this a persistent hash not an array.
                   6761: 
                   6762: 
                   6763: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6764: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6765: 	    $response_number++;
                   6766: 
                   6767: 	    $bubble_line +=  $lines;
                   6768: 	    $total_lines +=  $lines;
1.435     foxr     6769: 	}
                   6770: 
1.191     albertel 6771:     }
                   6772:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6773: 
                   6774:     &save_bubble_lines();
1.330     albertel 6775:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6776: 	$total_lines;
1.257     albertel 6777:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6778: }
                   6779: 
1.423     albertel 6780: =pod
                   6781: 
                   6782: =item scantron_validate_missingbubbles
                   6783: 
1.424     albertel 6784:    Validates all scanlines in the selected file to not have any
1.447     foxr     6785:     answers that don't have bubbles that have not been verified
                   6786:     to be bubble free.
1.424     albertel 6787: 
1.423     albertel 6788: =cut
                   6789: 
1.157     albertel 6790: sub scantron_validate_missingbubbles {
                   6791:     my ($r,$currentphase) = @_;
                   6792:     #get student info
                   6793:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6794:     my %idmap=&username_to_idmap($classlist);
                   6795: 
                   6796:     #get scantron line setup
1.257     albertel 6797:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6798:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6799:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6800:     if (!$max_bubble) { $max_bubble=2**31; }
                   6801:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6802: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6803: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6804: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6805: 						 $scan_data);
                   6806: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6807: 	my @to_correct;
                   6808: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6809: 	    if ($missing > $max_bubble) { next; }
                   6810: 	    push(@to_correct,$missing);
                   6811: 	}
                   6812: 	if (@to_correct) {
                   6813: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6814: 				     $line,'missingbubble',\@to_correct);
                   6815: 	    return (1,$currentphase);
                   6816: 	}
                   6817: 
                   6818:     }
                   6819:     return (0,$currentphase+1);
                   6820: }
                   6821: 
1.423     albertel 6822: =pod
                   6823: 
                   6824: =item scantron_process_students
                   6825: 
                   6826:    Routine that does the actual grading of the bubble sheet information.
                   6827: 
                   6828:    The parsed scanline hash is added to %env 
                   6829: 
                   6830:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6831:    foreach resource , with the form data of
                   6832: 
                   6833: 	'submitted'     =>'scantron' 
                   6834: 	'grade_target'  =>'grade',
                   6835: 	'grade_username'=> username of student
                   6836: 	'grade_domain'  => domain of student
                   6837: 	'grade_courseid'=> of course
                   6838: 	'grade_symb'    => symb of resource to grade
                   6839: 
                   6840:     This triggers a grading pass. The problem grading code takes care
                   6841:     of converting the bubbled letter information (now in %env) into a
                   6842:     valid submission.
                   6843: 
                   6844: =cut
                   6845: 
1.82      albertel 6846: sub scantron_process_students {
1.75      albertel 6847:     my ($r) = @_;
1.257     albertel 6848:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6849:     my ($symb)=&get_symb($r);
1.81      albertel 6850:     if (!$symb) {return '';}
1.324     albertel 6851:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6852: 
1.257     albertel 6853:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6854:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6855:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6856:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6857:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6858:     my $map=$navmap->getResourceByUrl($sequence);
                   6859:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6860: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6861:     my $result= <<SCANTRONFORM;
1.81      albertel 6862: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6863:   <input type="hidden" name="command" value="scantron_configphase" />
                   6864:   $default_form_data
                   6865: SCANTRONFORM
1.82      albertel 6866:     $r->print($result);
                   6867: 
                   6868:     my @delayqueue;
1.140     albertel 6869:     my %completedstudents;
                   6870:     
1.200     albertel 6871:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6872:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6873:  				    'Scantron Progress',$count,
1.195     albertel 6874: 				    'inline',undef,'scantronupload');
1.140     albertel 6875:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6876: 					  'Processing first student');
                   6877:     my $start=&Time::HiRes::time();
1.158     albertel 6878:     my $i=-1;
1.200     albertel 6879:     my ($uname,$udom,$started);
1.447     foxr     6880: 
                   6881:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6882: 
1.157     albertel 6883:     while ($i<$scanlines->{'count'}) {
                   6884:  	($uname,$udom)=('','');
                   6885:  	$i++;
1.200     albertel 6886:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6887:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6888: 	if ($started) {
                   6889: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6890: 						     'last student');
                   6891: 	}
                   6892: 	$started=1;
1.157     albertel 6893:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6894:  						 $scan_data);
                   6895:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6896:  					      \%idmap,$i)) {
                   6897:   	    &scantron_add_delay(\@delayqueue,$line,
                   6898:  				'Unable to find a student that matches',1);
                   6899:  	    next;
                   6900:   	}
                   6901:  	if (exists $completedstudents{$uname}) {
                   6902:  	    &scantron_add_delay(\@delayqueue,$line,
                   6903:  				'Student '.$uname.' has multiple sheets',2);
                   6904:  	    next;
                   6905:  	}
                   6906:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6907: 
                   6908: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6909:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6910: 
                   6911: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6912: 	    &scantron_putfile($scanlines,$scan_data);
                   6913: 	}
1.161     albertel 6914: 	
                   6915: 	my $i=0;
1.83      albertel 6916: 	foreach my $resource (@resources) {
1.85      albertel 6917: 	    $i++;
1.193     albertel 6918: 	    my %form=('submitted'     =>'scantron',
                   6919: 		      'grade_target'  =>'grade',
                   6920: 		      'grade_username'=>$uname,
                   6921: 		      'grade_domain'  =>$udom,
1.257     albertel 6922: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6923: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6924: 	    if (exists($scan_record->{'scantron.CODE'})
                   6925: 		&& 
                   6926: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6927: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6928: 	    } else {
                   6929: 		$form{'CODE'}='';
1.193     albertel 6930: 	    }
                   6931: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6932: 	    if ($result ne '') {
                   6933: 	    }
1.213     albertel 6934: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6935: 	}
1.140     albertel 6936: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6937: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6938:     } continue {
1.330     albertel 6939: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6940: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6941:     }
1.140     albertel 6942:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6943: #    my $lasttime = &Time::HiRes::time()-$start;
                   6944: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6945: 
1.200     albertel 6946:     $r->print("</form>");
1.324     albertel 6947:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6948:     return '';
1.75      albertel 6949: }
1.157     albertel 6950: 
1.423     albertel 6951: =pod
                   6952: 
                   6953: =item scantron_upload_scantron_data
                   6954: 
                   6955:     Creates the screen for adding a new bubble sheet data file to a course.
                   6956: 
                   6957: =cut
                   6958: 
1.157     albertel 6959: sub scantron_upload_scantron_data {
                   6960:     my ($r)=@_;
1.257     albertel 6961:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6962:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6963: 							  'domainid',
                   6964: 							  'coursename');
1.257     albertel 6965:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6966: 						   'domainid');
1.324     albertel 6967:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6968:     $r->print(<<UPLOAD);
                   6969: <script type="text/javascript" language="javascript">
                   6970:     function checkUpload(formname) {
                   6971: 	if (formname.upfile.value == "") {
                   6972: 	    alert("Please use the browse button to select a file from your local directory.");
                   6973: 	    return false;
                   6974: 	}
                   6975: 	formname.submit();
                   6976:     }
                   6977: </script>
                   6978: 
                   6979: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6980: $default_form_data
1.181     albertel 6981: <table>
                   6982: <tr><td>$select_link </td></tr>
                   6983: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6984: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6985: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6986: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6987: </table>
1.157     albertel 6988: <input name='command' value='scantronupload_save' type='hidden' />
                   6989: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6990: </form>
                   6991: UPLOAD
                   6992:     return '';
                   6993: }
                   6994: 
1.423     albertel 6995: =pod
                   6996: 
                   6997: =item scantron_upload_scantron_data_save
                   6998: 
                   6999:    Adds a provided bubble information data file to the course if user
                   7000:    has the correct privileges to do so.  
                   7001: 
                   7002: =cut
                   7003: 
1.157     albertel 7004: sub scantron_upload_scantron_data_save {
                   7005:     my($r)=@_;
1.324     albertel 7006:     my ($symb)=&get_symb($r,1);
1.182     albertel 7007:     my $doanotherupload=
                   7008: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7009: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7010: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7011: 	'</form>'."\n";
1.257     albertel 7012:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7013: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7014: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7015: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7016: 	if ($symb) {
1.324     albertel 7017: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7018: 	} else {
                   7019: 	    $r->print($doanotherupload);
                   7020: 	}
1.162     albertel 7021: 	return '';
                   7022:     }
1.257     albertel 7023:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7024:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7025:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7026:     #FIXME
                   7027:     #copied from lonnet::userfileupload()
                   7028:     #make that function able to target a specified course
                   7029:     # Replace Windows backslashes by forward slashes
                   7030:     $fname=~s/\\/\//g;
                   7031:     # Get rid of everything but the actual filename
                   7032:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7033:     # Replace spaces by underscores
                   7034:     $fname=~s/\s+/\_/g;
                   7035:     # Replace all other weird characters by nothing
                   7036:     $fname=~s/[^\w\.\-]//g;
                   7037:     # See if there is anything left
                   7038:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7039:     my $uploadedfile=$fname;
1.157     albertel 7040:     $fname='scantron_orig_'.$fname;
1.257     albertel 7041:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7042: 	$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 7043:     } else {
1.275     albertel 7044: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7045: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7046: 	    $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 7047: 	} else {
1.398     albertel 7048: 	    $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 7049: 	}
                   7050:     }
1.174     albertel 7051:     if ($symb) {
1.209     ng       7052: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7053:     } else {
1.182     albertel 7054: 	$r->print($doanotherupload);
1.174     albertel 7055:     }
1.157     albertel 7056:     return '';
                   7057: }
                   7058: 
1.423     albertel 7059: =pod
                   7060: 
                   7061: =item valid_file
                   7062: 
1.424     albertel 7063:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7064: 
                   7065: =cut
                   7066: 
1.202     albertel 7067: sub valid_file {
                   7068:     my ($requested_file)=@_;
                   7069:     foreach my $filename (sort(&scantron_filenames())) {
                   7070: 	if ($requested_file eq $filename) { return 1; }
                   7071:     }
                   7072:     return 0;
                   7073: }
                   7074: 
1.423     albertel 7075: =pod
                   7076: 
                   7077: =item scantron_download_scantron_data
                   7078: 
                   7079:    Shows a list of the three internal files (original, corrected,
                   7080:    skipped) for a specific bubble sheet data file that exists in the
                   7081:    course.
                   7082: 
                   7083: =cut
                   7084: 
1.202     albertel 7085: sub scantron_download_scantron_data {
                   7086:     my ($r)=@_;
1.324     albertel 7087:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7088:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7089:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7090:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7091:     if (! &valid_file($file)) {
                   7092: 	$r->print(<<ERROR);
                   7093: 	<p>
                   7094: 	    The requested file name was invalid.
                   7095:         </p>
                   7096: ERROR
1.324     albertel 7097: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7098: 	return;
                   7099:     }
                   7100:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7101:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7102:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7103:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7104:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7105:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7106:     $r->print(<<DOWNLOAD);
                   7107:     <p>
                   7108: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7109:     </p>
                   7110:     <p>
                   7111: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7112:     </p>
                   7113:     <p>
                   7114: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7115:     </p>
                   7116: DOWNLOAD
1.324     albertel 7117:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7118:     return '';
                   7119: }
1.157     albertel 7120: 
1.423     albertel 7121: =pod
                   7122: 
                   7123: =back
                   7124: 
                   7125: =cut
                   7126: 
1.75      albertel 7127: #-------- end of section for handling grading scantron forms -------
                   7128: #
                   7129: #-------------------------------------------------------------------
                   7130: 
1.72      ng       7131: #-------------------------- Menu interface -------------------------
                   7132: #
                   7133: #--- Show a Grading Menu button - Calls the next routine ---
                   7134: sub show_grading_menu_form {
1.324     albertel 7135:     my ($symb)=@_;
1.125     ng       7136:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7137: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7138: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7139: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7140: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7141: 	'</form>'."\n";
                   7142:     return $result;
                   7143: }
                   7144: 
1.77      ng       7145: # -- Retrieve choices for grading form
                   7146: sub savedState {
                   7147:     my %savedState = ();
1.257     albertel 7148:     if ($env{'form.saveState'}) {
                   7149: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7150: 	    my ($key,$value) = split(/=/,$_,2);
                   7151: 	    $savedState{$key} = $value;
                   7152: 	}
                   7153:     }
                   7154:     return \%savedState;
                   7155: }
1.76      ng       7156: 
1.443     banghart 7157: sub grading_menu {
                   7158:     my ($request) = @_;
                   7159:     my ($symb)=&get_symb($request);
                   7160:     if (!$symb) {return '';}
                   7161:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7162:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7163: 
                   7164:     #
                   7165:     # Define menu data
1.444     banghart 7166:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7167:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7168:     $request->print($table);
1.443     banghart 7169:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7170:                   'handgrade'=>$hdgrade,
                   7171:                   'probTitle'=>$probTitle,
                   7172:                   'command'=>'submit_options',
                   7173:                   'saveState'=>"",
                   7174:                   'gradingMenu'=>1,
                   7175:                   'showgrading'=>"yes");
                   7176:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7177:     my @menu = ({ url => $url,
                   7178:                      name => &mt('Manual Grading/View Submissions'),
                   7179:                      short_description => 
                   7180:     &mt('Start the process of hand grading submissions.'),
                   7181:                  });
                   7182:     $fields{'command'} = 'csvform';
                   7183:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7184:     push (@menu, { url => $url,
                   7185:                    name => &mt('Upload Scores'),
                   7186:                    short_description => 
                   7187:             &mt('Specify a file containing the class scores for current resource.')});
                   7188:     $fields{'command'} = 'processclicker';
                   7189:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7190:     push (@menu, { url => $url,
                   7191:                    name => &mt('Process Clicker'),
                   7192:                    short_description => 
                   7193:             &mt('Specify a file containing the clicker information for this resource.')});
                   7194:     $fields{'command'} = 'scantron_selectphase';
                   7195:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7196:     push (@menu, { url => $url,
                   7197:                    name => &mt('Grade Scantron Forms'),
                   7198:                    short_description => 
                   7199:             &mt('')});
                   7200:     $fields{'command'} = 'verify';
                   7201:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7202:     push (@menu, { url => "",
                   7203:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7204:                    name => &mt('Verify Receipt'),
                   7205:                    short_description => 
                   7206:             &mt('')});
                   7207:     $fields{'command'} = 'manage';
                   7208:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7209:     push (@menu, { url => $url,
                   7210:                    name => &mt('Manage Access Times'),
                   7211:                    short_description => 
                   7212:             &mt('')});
                   7213:     $fields{'command'} = 'view';
                   7214:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7215:     push (@menu, { url => $url,
                   7216:                    name => &mt('View Saved CODEs'),
                   7217:                    short_description => 
                   7218:             &mt('')});
                   7219: 
                   7220:     #
                   7221:     # Create the menu
                   7222:     my $Str;
1.444     banghart 7223:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7224:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7225:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7226:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7227: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7228: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7229: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7230: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7231: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7232: 
1.443     banghart 7233:     foreach my $menudata (@menu) {
1.445     banghart 7234:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7235:             $Str .='    <h3><a '.
                   7236:                 $menudata->{'jscript'}.
                   7237:                 ' href="'.
                   7238:                 $menudata->{'url'}.'" >'.
                   7239:                 $menudata->{'name'}."</a></h3>\n";
                   7240:         } else {
                   7241:             $Str .='    <h3><a '.
                   7242:                 $menudata->{'jscript'}.
1.446     banghart 7243:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7244:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7245:             $Str .= ('&nbsp;'x8).
                   7246:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7247:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7248:         }
1.443     banghart 7249:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7250:             "\n";
                   7251:     }
                   7252:     $Str .="</dl>\n";
1.444     banghart 7253:     $Str .="</form>\n";
1.443     banghart 7254:     $request->print(<<GRADINGMENUJS);
                   7255: <script type="text/javascript" language="javascript">
                   7256:     function checkChoice(formname,val,cmdx) {
                   7257: 	if (val <= 2) {
                   7258: 	    var cmd = radioSelection(formname.radioChoice);
                   7259: 	    var cmdsave = cmd;
                   7260: 	} else {
                   7261: 	    cmd = cmdx;
                   7262: 	    cmdsave = 'submission';
                   7263: 	}
                   7264: 	formname.command.value = cmd;
                   7265: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7266: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7267: 	if (val < 5) formname.submit();
                   7268: 	if (val == 5) {
                   7269: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7270: 	    formname.submit();
                   7271: 	}
                   7272: 	if (val < 7) formname.submit();
                   7273:     }
1.445     banghart 7274:     function checkChoice2(formname,val,cmdx) {
                   7275: 	if (val <= 2) {
                   7276: 	    var cmd = radioSelection(formname.radioChoice);
                   7277: 	    var cmdsave = cmd;
                   7278: 	} else {
                   7279: 	    cmd = cmdx;
                   7280: 	    cmdsave = 'submission';
                   7281: 	}
                   7282: 	formname.command.value = cmd;
                   7283: 	if (val < 5) formname.submit();
                   7284: 	if (val == 5) {
                   7285: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7286: 	    formname.submit();
                   7287: 	}
                   7288: 	if (val < 7) formname.submit();
                   7289:     }
1.443     banghart 7290: 
                   7291:     function checkReceiptNo(formname,nospace) {
                   7292: 	var receiptNo = formname.receipt.value;
                   7293: 	var checkOpt = false;
                   7294: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7295: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7296: 	if (checkOpt) {
                   7297: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7298: 	    formname.receipt.value = "";
                   7299: 	    formname.receipt.focus();
                   7300: 	    return false;
                   7301: 	}
                   7302: 	return true;
                   7303:     }
                   7304: </script>
                   7305: GRADINGMENUJS
                   7306:     &commonJSfunctions($request);
                   7307:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7308:     $result.=$table;
                   7309:     my (undef,$sections) = &getclasslist('all','0');
                   7310:     my $savedState = &savedState();
                   7311:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7312:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7313:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7314:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7315: 
                   7316:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7317: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7318: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7319: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7320: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7321: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7322: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7323: 
                   7324:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7325: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7326: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7327: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7328: 
                   7329:     $result.='<table width="100%" border="0">';
                   7330:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7331:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7332: #    $result.='<td>Groups</td>';
                   7333:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7334:     $result.='</tr>';
                   7335:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7336: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7337:     if (ref($sections)) {
                   7338: 	foreach (sort (@$sections)) {
                   7339: 	    $result.='<option value="'.$_.'" '.
                   7340: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7341: 	}
                   7342:     }
                   7343:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7344:     return $Str;    
                   7345: }
                   7346: 
                   7347: 
                   7348: #--- Displays the submissions first page -------
                   7349: sub submit_options {
1.72      ng       7350:     my ($request) = @_;
1.324     albertel 7351:     my ($symb)=&get_symb($request);
1.72      ng       7352:     if (!$symb) {return '';}
1.76      ng       7353:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7354: 
                   7355:     $request->print(<<GRADINGMENUJS);
                   7356: <script type="text/javascript" language="javascript">
1.116     ng       7357:     function checkChoice(formname,val,cmdx) {
                   7358: 	if (val <= 2) {
                   7359: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7360: 	    var cmdsave = cmd;
1.116     ng       7361: 	} else {
                   7362: 	    cmd = cmdx;
1.118     ng       7363: 	    cmdsave = 'submission';
1.116     ng       7364: 	}
                   7365: 	formname.command.value = cmd;
1.118     ng       7366: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7367: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7368: 	if (val < 5) formname.submit();
                   7369: 	if (val == 5) {
1.72      ng       7370: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7371: 	    formname.submit();
                   7372: 	}
1.238     albertel 7373: 	if (val < 7) formname.submit();
1.72      ng       7374:     }
                   7375: 
                   7376:     function checkReceiptNo(formname,nospace) {
                   7377: 	var receiptNo = formname.receipt.value;
                   7378: 	var checkOpt = false;
                   7379: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7380: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7381: 	if (checkOpt) {
                   7382: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7383: 	    formname.receipt.value = "";
                   7384: 	    formname.receipt.focus();
                   7385: 	    return false;
                   7386: 	}
                   7387: 	return true;
                   7388:     }
                   7389: </script>
                   7390: GRADINGMENUJS
1.118     ng       7391:     &commonJSfunctions($request);
1.398     albertel 7392:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7393:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7394:     $result.=$table;
1.76      ng       7395:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7396:     my $savedState = &savedState();
1.118     ng       7397:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7398:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7399:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7400:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7401: 
                   7402:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7403: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7404: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7405: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7406: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7407: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7408: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7409: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7410: 
1.446     banghart 7411:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7412: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7413: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7414: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7415: 
1.326     albertel 7416:     $result.='<table width="100%" border="0">';
1.442     banghart 7417:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7418:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7419:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7420:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7421:     $result.='</tr>';
1.116     ng       7422:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7423: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7424:     if (ref($sections)) {
1.155     albertel 7425: 	foreach (sort (@$sections)) {
                   7426: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7427: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7428: 	}
1.116     ng       7429:     }
1.401     albertel 7430:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7431:     $result.= '</td><td>'."\n";
                   7432:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7433:     $result.='</td><td>'."\n";
                   7434:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7435: 
1.116     ng       7436:     $result.='</td></tr>';
                   7437: 
1.442     banghart 7438:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7439: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7440: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7441: 	'</label> <select name="submitonly">'.
1.145     albertel 7442: 	'<option value="yes" '.
1.401     albertel 7443: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7444: 	'<option value="queued" '.
1.401     albertel 7445: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7446: 	'<option value="graded" '.
1.401     albertel 7447: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7448: 	'<option value="incorrect" '.
1.401     albertel 7449: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7450: 	'<option value="all" '.
1.401     albertel 7451: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7452: 
1.442     banghart 7453:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7454: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7455: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7456: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7457: 
1.442     banghart 7458:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7459: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7460: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7461: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7462: 
1.442     banghart 7463:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7464: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7465: 	'</td></tr></table>'."\n";
                   7466: 
1.446     banghart 7467:     $result.='</td>'; #<td valign="top">';
1.116     ng       7468: 
1.446     banghart 7469: #    $result.='<table width="100%" border="0">';
                   7470: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7471: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7472: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7473: #
                   7474: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7475: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7476: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7477: #
                   7478: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7479: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7480: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7481: #
                   7482: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7483: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7484: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7485: #	    ' '.&mt('receipt').': '.
                   7486: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7487: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7488: #	    '</td></tr>'."\n";
                   7489: #    } 
                   7490: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7491: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7492: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7493: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7494: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7495: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7496: #
                   7497: #    $result.='</table>'."\n".'</td>';
                   7498:     $result.= '</tr></table>'."\n".
1.401     albertel 7499: 	'</td></tr></table></form>'."\n";
1.44      ng       7500:     return $result;
1.2       albertel 7501: }
                   7502: 
1.285     albertel 7503: sub reset_perm {
                   7504:     undef(%perm);
                   7505: }
                   7506: 
                   7507: sub init_perm {
                   7508:     &reset_perm();
1.300     albertel 7509:     foreach my $test_perm ('vgr','mgr','opa') {
                   7510: 
                   7511: 	my $scope = $env{'request.course.id'};
                   7512: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7513: 
                   7514: 	    $scope .= '/'.$env{'request.course.sec'};
                   7515: 	    if ( $perm{$test_perm}=
                   7516: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7517: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7518: 	    } else {
                   7519: 		delete($perm{$test_perm});
                   7520: 	    }
1.285     albertel 7521: 	}
                   7522:     }
                   7523: }
                   7524: 
1.400     www      7525: sub gather_clicker_ids {
1.408     albertel 7526:     my %clicker_ids;
1.400     www      7527: 
                   7528:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7529: 
                   7530:     # Set up a couple variables.
1.407     albertel 7531:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7532:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7533:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7534: 
1.407     albertel 7535:     foreach my $student (keys(%$classlist)) {
1.438     www      7536:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7537:         my $username = $classlist->{$student}->[$username_idx];
                   7538:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7539:         my $clickers =
1.408     albertel 7540: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7541:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7542:             $id=~s/^[\#0]+//;
1.421     www      7543:             $id=~s/[\-\:]//g;
1.407     albertel 7544:             if (exists($clicker_ids{$id})) {
1.408     albertel 7545: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7546:             } else {
1.408     albertel 7547: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7548:             }
                   7549:         }
                   7550:     }
1.407     albertel 7551:     return %clicker_ids;
1.400     www      7552: }
                   7553: 
1.402     www      7554: sub gather_adv_clicker_ids {
1.408     albertel 7555:     my %clicker_ids;
1.402     www      7556:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7557:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7558:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7559:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7560:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7561:             my ($puname,$pudom)=split(/\:/,$person);
                   7562:             my $clickers =
1.408     albertel 7563: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7564:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7565: 		$id=~s/^[\#0]+//;
1.421     www      7566:                 $id=~s/[\-\:]//g;
1.408     albertel 7567: 		if (exists($clicker_ids{$id})) {
                   7568: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7569: 		} else {
                   7570: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7571: 		}
1.405     www      7572:             }
1.402     www      7573:         }
                   7574:     }
1.407     albertel 7575:     return %clicker_ids;
1.402     www      7576: }
                   7577: 
1.413     www      7578: sub clicker_grading_parameters {
                   7579:     return ('gradingmechanism' => 'scalar',
                   7580:             'upfiletype' => 'scalar',
                   7581:             'specificid' => 'scalar',
                   7582:             'pcorrect' => 'scalar',
                   7583:             'pincorrect' => 'scalar');
                   7584: }
                   7585: 
1.400     www      7586: sub process_clicker {
                   7587:     my ($r)=@_;
                   7588:     my ($symb)=&get_symb($r);
                   7589:     if (!$symb) {return '';}
                   7590:     my $result=&checkforfile_js();
                   7591:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7592:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7593:     $result.=$table;
                   7594:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7595:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7596:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7597:         '.</b></td></tr>'."\n";
                   7598:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7599: # Attempt to restore parameters from last session, set defaults if not present
                   7600:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7601:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7602:                                                  \%Saveable_Parameters);
                   7603:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7604:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7605:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7606:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7607: 
                   7608:     my %checked;
                   7609:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7610:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7611:           $checked{$gradingmechanism}="checked='checked'";
                   7612:        }
                   7613:     }
                   7614: 
1.400     www      7615:     my $upload=&mt("Upload File");
                   7616:     my $type=&mt("Type");
1.402     www      7617:     my $attendance=&mt("Award points just for participation");
                   7618:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7619:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7620:     my $pcorrect=&mt("Percentage points for correct solution");
                   7621:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7622:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7623: 						   ('iclicker' => 'i>clicker',
                   7624:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7625:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7626:     $result.=<<ENDUPFORM;
1.402     www      7627: <script type="text/javascript">
                   7628: function sanitycheck() {
                   7629: // Accept only integer percentages
                   7630:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7631:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7632: // Find out grading choice
                   7633:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7634:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7635:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7636:       }
                   7637:    }
                   7638: // By default, new choice equals user selection
                   7639:    newgradingchoice=gradingchoice;
                   7640: // Not good to give more points for false answers than correct ones
                   7641:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7642:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7643:    }
                   7644: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7645:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7646:       document.forms.gradesupload.pcorrect.value=100;
                   7647:       document.forms.gradesupload.pincorrect.value=100;
                   7648:    }
                   7649: // If the values are different, cannot be attendance only
                   7650:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7651:        (gradingchoice=='attendance')) {
                   7652:        newgradingchoice='personnel';
                   7653:    }
                   7654: // Change grading choice to new one
                   7655:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7656:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7657:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7658:       } else {
                   7659:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7660:       }
                   7661:    }
                   7662: // Remember the old state
                   7663:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7664: }
                   7665: </script>
1.400     www      7666: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7667: <input type="hidden" name="symb" value="$symb" />
                   7668: <input type="hidden" name="command" value="processclickerfile" />
                   7669: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7670: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7671: <input type="file" name="upfile" size="50" />
                   7672: <br /><label>$type: $selectform</label>
1.413     www      7673: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7674: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7675: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7676: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7677: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7678: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7679: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7680: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7681: </form>
                   7682: ENDUPFORM
                   7683:     $result.='</td></tr></table>'."\n".
                   7684:              '</td></tr></table><br /><br />'."\n";
                   7685:     $result.=&show_grading_menu_form($symb);
                   7686:     return $result;
                   7687: }
                   7688: 
                   7689: sub process_clicker_file {
                   7690:     my ($r)=@_;
                   7691:     my ($symb)=&get_symb($r);
                   7692:     if (!$symb) {return '';}
1.413     www      7693: 
                   7694:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7695:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7696:                                               \%Saveable_Parameters);
                   7697: 
1.400     www      7698:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7699:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7700: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7701: 	return $result.&show_grading_menu_form($symb);
1.404     www      7702:     }
1.407     albertel 7703:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7704:     my %correct_ids;
1.404     www      7705:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7706: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7707:     }
                   7708:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7709: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7710: 	   $correct_id=~tr/a-z/A-Z/;
                   7711: 	   $correct_id=~s/\s//gs;
                   7712: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7713:            $correct_id=~s/[\-\:]//g;
1.414     www      7714:            if ($correct_id) {
                   7715: 	      $correct_ids{$correct_id}='specified';
                   7716:            }
                   7717:         }
1.400     www      7718:     }
1.404     www      7719:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7720: 	$result.=&mt('Score based on attendance only');
1.404     www      7721:     } else {
1.408     albertel 7722: 	my $number=0;
1.411     www      7723: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7724: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7725: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7726: 	    if ($correct_ids{$id} eq 'specified') {
                   7727: 		$result.=&mt('specified');
                   7728: 	    } else {
                   7729: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7730: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7731: 	    }
                   7732: 	    $number++;
                   7733: 	}
1.411     www      7734:         $result.="</p>\n";
1.408     albertel 7735: 	if ($number==0) {
                   7736: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7737: 	    return $result.&show_grading_menu_form($symb);
                   7738: 	}
1.404     www      7739:     }
1.405     www      7740:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7741:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7742: 		     '<span class="LC_error">',
                   7743: 		     '</span>',
                   7744: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7745:         return $result.&show_grading_menu_form($symb);
                   7746:     }
1.410     www      7747: 
                   7748: # Were able to get all the info needed, now analyze the file
                   7749: 
1.411     www      7750:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7751:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7752:     my $heading=&mt('Scanning clicker file');
                   7753:     $result.=(<<ENDHEADER);
                   7754: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7755: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7756: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7757: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7758: <input type="hidden" name="symb" value="$symb" />
                   7759: <input type="hidden" name="command" value="assignclickergrades" />
                   7760: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7761: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7762: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7763: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7764: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7765: ENDHEADER
1.408     albertel 7766:     my %responses;
                   7767:     my @questiontitles;
1.405     www      7768:     my $errormsg='';
                   7769:     my $number=0;
                   7770:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7771: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7772:     }
1.419     www      7773:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7774:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7775:     }
1.411     www      7776:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7777:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7778:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7779:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7780:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7781:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7782:              '<br />';
1.414     www      7783: # Remember Question Titles
                   7784: # FIXME: Possibly need delimiter other than ":"
                   7785:     for (my $i=0;$i<$number;$i++) {
                   7786:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7787:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7788:     }
1.411     www      7789:     my $correct_count=0;
                   7790:     my $student_count=0;
                   7791:     my $unknown_count=0;
1.414     www      7792: # Match answers with usernames
                   7793: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7794:     foreach my $id (keys(%responses)) {
1.410     www      7795:        if ($correct_ids{$id}) {
1.414     www      7796:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7797:           $correct_count++;
1.410     www      7798:        } elsif ($clicker_ids{$id}) {
1.437     www      7799:           if ($clicker_ids{$id}=~/\,/) {
                   7800: # More than one user with the same clicker!
                   7801:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7802:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7803:                            "<select name='multi".$id."'>";
                   7804:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7805:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7806:              }
                   7807:              $result.='</select>';
                   7808:              $unknown_count++;
                   7809:           } else {
                   7810: # Good: found one and only one user with the right clicker
                   7811:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7812:              $student_count++;
                   7813:           }
1.410     www      7814:        } else {
1.411     www      7815:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7816:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7817:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7818:                    "\n".&mt("Domain").": ".
                   7819:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7820:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7821:           $unknown_count++;
1.410     www      7822:        }
1.405     www      7823:     }
1.412     www      7824:     $result.='<hr />'.
                   7825:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7826:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7827:        if ($correct_count==0) {
                   7828:           $errormsg.="Found no correct answers answers for grading!";
                   7829:        } elsif ($correct_count>1) {
1.414     www      7830:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7831:        }
                   7832:     }
1.428     www      7833:     if ($number<1) {
                   7834:        $errormsg.="Found no questions.";
                   7835:     }
1.412     www      7836:     if ($errormsg) {
                   7837:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7838:     } else {
                   7839:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7840:     }
                   7841:     $result.='</form></td></tr></table>'."\n".
1.410     www      7842:              '</td></tr></table><br /><br />'."\n";
1.404     www      7843:     return $result.&show_grading_menu_form($symb);
1.400     www      7844: }
                   7845: 
1.405     www      7846: sub iclicker_eval {
1.406     www      7847:     my ($questiontitles,$responses)=@_;
1.405     www      7848:     my $number=0;
                   7849:     my $errormsg='';
                   7850:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7851:         my %components=&Apache::loncommon::record_sep($line);
                   7852:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7853: 	if ($entries[0] eq 'Question') {
                   7854: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7855: 		$$questiontitles[$number]=$entries[$i];
                   7856: 		$number++;
                   7857: 	    }
                   7858: 	}
                   7859: 	if ($entries[0]=~/^\#/) {
                   7860: 	    my $id=$entries[0];
                   7861: 	    my @idresponses;
                   7862: 	    $id=~s/^[\#0]+//;
                   7863: 	    for (my $i=0;$i<$number;$i++) {
                   7864: 		my $idx=3+$i*6;
                   7865: 		push(@idresponses,$entries[$idx]);
                   7866: 	    }
                   7867: 	    $$responses{$id}=join(',',@idresponses);
                   7868: 	}
1.405     www      7869:     }
                   7870:     return ($errormsg,$number);
                   7871: }
                   7872: 
1.419     www      7873: sub interwrite_eval {
                   7874:     my ($questiontitles,$responses)=@_;
                   7875:     my $number=0;
                   7876:     my $errormsg='';
1.420     www      7877:     my $skipline=1;
                   7878:     my $questionnumber=0;
                   7879:     my %idresponses=();
1.419     www      7880:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7881:         my %components=&Apache::loncommon::record_sep($line);
                   7882:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7883:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7884:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7885:         next if $skipline;
                   7886:         if ($entries[0]!=$questionnumber) {
                   7887:            $questionnumber=$entries[0];
                   7888:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7889:            $number++;
1.419     www      7890:         }
1.420     www      7891:         my $id=$entries[4];
                   7892:         $id=~s/^[\#0]+//;
1.421     www      7893:         $id=~s/^v\d*\://i;
                   7894:         $id=~s/[\-\:]//g;
1.420     www      7895:         $idresponses{$id}[$number]=$entries[6];
                   7896:     }
                   7897:     foreach my $id (keys %idresponses) {
                   7898:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7899:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7900:     }
                   7901:     return ($errormsg,$number);
                   7902: }
                   7903: 
1.414     www      7904: sub assign_clicker_grades {
                   7905:     my ($r)=@_;
                   7906:     my ($symb)=&get_symb($r);
                   7907:     if (!$symb) {return '';}
1.416     www      7908: # See which part we are saving to
                   7909:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7910: # FIXME: This should probably look for the first handgradeable part
                   7911:     my $part=$$partlist[0];
                   7912: # Start screen output
1.414     www      7913:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7914: 
1.414     www      7915:     my $heading=&mt('Assigning grades based on clicker file');
                   7916:     $result.=(<<ENDHEADER);
                   7917: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7918: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7919: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7920: ENDHEADER
                   7921: # Get correct result
                   7922: # FIXME: Possibly need delimiter other than ":"
                   7923:     my @correct=();
1.415     www      7924:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7925:     my $number=$env{'form.number'};
                   7926:     if ($gradingmechanism ne 'attendance') {
1.414     www      7927:        foreach my $key (keys(%env)) {
                   7928:           if ($key=~/^form\.correct\:/) {
                   7929:              my @input=split(/\,/,$env{$key});
                   7930:              for (my $i=0;$i<=$#input;$i++) {
                   7931:                  if (($correct[$i]) && ($input[$i]) &&
                   7932:                      ($correct[$i] ne $input[$i])) {
                   7933:                     $result.='<br /><span class="LC_warning">'.
                   7934:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7935:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7936:                  } elsif ($input[$i]) {
                   7937:                     $correct[$i]=$input[$i];
                   7938:                  }
                   7939:              }
                   7940:           }
                   7941:        }
1.415     www      7942:        for (my $i=0;$i<$number;$i++) {
1.414     www      7943:           if (!$correct[$i]) {
                   7944:              $result.='<br /><span class="LC_error">'.
                   7945:                       &mt('No correct result given for question "[_1]"!',
                   7946:                           $env{'form.question:'.$i}).'</span>';
                   7947:           }
                   7948:        }
                   7949:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7950:     }
                   7951: # Start grading
1.415     www      7952:     my $pcorrect=$env{'form.pcorrect'};
                   7953:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7954:     my $storecount=0;
1.415     www      7955:     foreach my $key (keys(%env)) {
1.420     www      7956:        my $user='';
1.415     www      7957:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7958:           $user=$1;
                   7959:        }
                   7960:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7961:           my $id=$1;
                   7962:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7963:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7964:           } elsif ($env{'form.multi'.$id}) {
                   7965:              $user=$env{'form.multi'.$id};
1.420     www      7966:           }
                   7967:        }
                   7968:        if ($user) { 
1.415     www      7969:           my @answer=split(/\,/,$env{$key});
                   7970:           my $sum=0;
                   7971:           for (my $i=0;$i<$number;$i++) {
                   7972:              if ($answer[$i]) {
                   7973:                 if ($gradingmechanism eq 'attendance') {
                   7974:                    $sum+=$pcorrect;
                   7975:                 } else {
                   7976:                    if ($answer[$i] eq $correct[$i]) {
                   7977:                       $sum+=$pcorrect;
                   7978:                    } else {
                   7979:                       $sum+=$pincorrect;
                   7980:                    }
                   7981:                 }
                   7982:              }
                   7983:           }
1.416     www      7984:           my $ave=$sum/(100*$number);
                   7985: # Store
                   7986:           my ($username,$domain)=split(/\:/,$user);
                   7987:           my %grades=();
                   7988:           $grades{"resource.$part.solved"}='correct_by_override';
                   7989:           $grades{"resource.$part.awarded"}=$ave;
                   7990:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7991:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7992:                                                  $env{'request.course.id'},
                   7993:                                                  $domain,$username);
                   7994:           if ($returncode ne 'ok') {
                   7995:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7996:           } else {
                   7997:              $storecount++;
                   7998:           }
1.415     www      7999:        }
                   8000:     }
                   8001: # We are done
1.416     www      8002:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8003:              '</td></tr></table>'."\n".
1.414     www      8004:              '</td></tr></table><br /><br />'."\n";
                   8005:     return $result.&show_grading_menu_form($symb);
                   8006: }
                   8007: 
1.1       albertel 8008: sub handler {
1.41      ng       8009:     my $request=$_[0];
1.447     foxr     8010: 
1.434     albertel 8011:     &reset_caches();
1.257     albertel 8012:     if ($env{'browser.mathml'}) {
1.141     www      8013: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8014:     } else {
1.141     www      8015: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8016:     }
                   8017:     $request->send_http_header;
1.44      ng       8018:     return '' if $request->header_only;
1.41      ng       8019:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8020:     my $symb=&get_symb($request,1);
1.160     albertel 8021:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8022:     my $command=$commands[0];
1.447     foxr     8023: 
1.160     albertel 8024:     if ($#commands > 0) {
                   8025: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8026:     }
1.447     foxr     8027: 
                   8028: 
1.353     albertel 8029:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8030:     if ($symb eq '' && $command eq '') {
1.257     albertel 8031: 	if ($env{'user.adv'}) {
                   8032: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8033: 		($env{'form.codethree'})) {
                   8034: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8035: 		    $env{'form.codethree'};
1.41      ng       8036: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8037: 		    &Apache::lonnet::checkin($token);
                   8038: 		if ($tsymb) {
1.137     albertel 8039: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8040: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8041: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8042: 					  ('grade_username' => $tuname,
                   8043: 					   'grade_domain' => $tudom,
                   8044: 					   'grade_courseid' => $tcrsid,
                   8045: 					   'grade_symb' => $tsymb)));
1.41      ng       8046: 		    } else {
1.45      ng       8047: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8048: 		    }
1.41      ng       8049: 		} else {
1.45      ng       8050: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8051: 		}
1.14      www      8052: 	    } else {
1.41      ng       8053: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8054: 	    }
                   8055: 	}
                   8056:     } else {
1.285     albertel 8057: 	&init_perm();
1.104     albertel 8058: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8059: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8060: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8061: 	    &pickStudentPage($request);
1.103     albertel 8062: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8063: 	    &displayPage($request);
1.104     albertel 8064: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8065: 	    &updateGradeByPage($request);
1.104     albertel 8066: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8067: 	    &processGroup($request);
1.104     albertel 8068: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8069: 	    $request->print(&grading_menu($request));
                   8070: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8071: 	    $request->print(&submit_options($request));
1.104     albertel 8072: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8073: 	    $request->print(&viewgrades($request));
1.104     albertel 8074: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8075: 	    $request->print(&processHandGrade($request));
1.106     albertel 8076: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8077: 	    $request->print(&editgrades($request));
1.106     albertel 8078: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8079: 	    $request->print(&verifyreceipt($request));
1.400     www      8080:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8081:             $request->print(&process_clicker($request));
                   8082:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8083:             $request->print(&process_clicker_file($request));
1.414     www      8084:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8085:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8086: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8087: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8088: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8089: 	    $request->print(&csvupload($request));
1.106     albertel 8090: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8091: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8092: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8093: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8094: 		$request->print(&csvuploadoptions($request));
1.41      ng       8095: 	    } else {
1.257     albertel 8096: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8097: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8098: 		} else {
1.257     albertel 8099: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8100: 		}
                   8101: 		$request->print(&csvuploadmap($request));
                   8102: 	    }
1.246     albertel 8103: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8104: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8105: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8106: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8107: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8108:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8109:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8110: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8111: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8112: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8113: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8114:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8115:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8116: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8117:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8118:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8119:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8120: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8121:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8122:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8123: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8124:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8125: 	} elsif ($command) {
1.157     albertel 8126: 	    $request->print("Access Denied ($command)");
1.26      albertel 8127: 	}
1.2       albertel 8128:     }
1.353     albertel 8129:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8130:     &reset_caches();
1.44      ng       8131:     return '';
                   8132: }
                   8133: 
1.1       albertel 8134: 1;
                   8135: 
1.13      albertel 8136: __END__;

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