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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.454   ! banghart    4: # $Id: grades.pm,v 1.453 2007/10/11 21:27:50 banghart 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.450     banghart  480:     my @getgroup;
1.442     banghart  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  482:     if (!ref($getsec)) {
                    483: 	if ($getsec ne '' && $getsec ne 'all') {
                    484: 	    @getsec=($getsec);
                    485: 	}
                    486:     } else {
                    487: 	@getsec=@{$getsec};
                    488:     }
                    489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  490:     if (!ref($getgroup)) {
                    491: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    492: 	    @getgroup=($getgroup);
                    493: 	}
                    494:     } else {
                    495: 	@getgroup=@{$getgroup};
                    496:     }
                    497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  498: 
1.449     banghart  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  500:     # Bail out if we were unable to get the classlist
1.56      matthew   501:     return if (! defined($classlist));
1.449     banghart  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   503:     #
                    504:     my %sections;
                    505:     my %fullnames;
1.205     matthew   506:     foreach my $student (keys(%$classlist)) {
                    507:         my $end      = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    509:         my $start    = 
                    510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    511:         my $id       = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    513:         my $section  = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    515:         my $fullname = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    517:         my $status   = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  519:         my $group   = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        521: 	# filter students according to status selected
1.442     banghart  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    523: 	    if (!($stu_status =~ $status)) {
1.450     banghart  524: 		delete($classlist->{$student});
1.76      ng        525: 		next;
                    526: 	    }
                    527: 	}
1.450     banghart  528: 	# filter students according to groups selected
1.453     banghart  529: 	my @stu_groups = split(/,/,$group);
1.450     banghart  530: 	if (@getgroup) {
                    531: 	    my $exclude = 1;
1.454   ! banghart  532: 	    foreach my $grp (@getgroup) {
        !           533: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  534: 	            if ($stu_group eq $grp) {
                    535: 	                $exclude = 0;
                    536:     	            } 
1.450     banghart  537: 	        }
1.453     banghart  538:     	        if (($grp eq 'none') && !$group) {
                    539:         	        $exclude = 0;
                    540:         	}
1.450     banghart  541: 	    }
                    542: 	    if ($exclude) {
                    543: 	        delete($classlist->{$student});
                    544: 	    }
                    545: 	}
1.205     matthew   546: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  547: 	if (&canview($section)) {
1.291     albertel  548: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  549: 		$sections{$section}++;
1.450     banghart  550: 		if ($classlist->{$student}) {
                    551: 		    $fullnames{$student}=$fullname;
                    552: 		}
1.103     albertel  553: 	    } else {
1.205     matthew   554: 		delete($classlist->{$student});
1.103     albertel  555: 	    }
                    556: 	} else {
1.205     matthew   557: 	    delete($classlist->{$student});
1.103     albertel  558: 	}
1.44      ng        559:     }
                    560:     my %seen = ();
1.56      matthew   561:     my @sections = sort(keys(%sections));
                    562:     return ($classlist,\@sections,\%fullnames);
1.44      ng        563: }
                    564: 
1.103     albertel  565: sub canmodify {
                    566:     my ($sec)=@_;
                    567:     if ($perm{'mgr'}) {
                    568: 	if (!defined($perm{'mgr_section'})) {
                    569: 	    # can modify whole class
                    570: 	    return 1;
                    571: 	} else {
                    572: 	    if ($sec eq $perm{'mgr_section'}) {
                    573: 		#can modify the requested section
                    574: 		return 1;
                    575: 	    } else {
                    576: 		# can't modify the request section
                    577: 		return 0;
                    578: 	    }
                    579: 	}
                    580:     }
                    581:     #can't modify
                    582:     return 0;
                    583: }
                    584: 
                    585: sub canview {
                    586:     my ($sec)=@_;
                    587:     if ($perm{'vgr'}) {
                    588: 	if (!defined($perm{'vgr_section'})) {
                    589: 	    # can modify whole class
                    590: 	    return 1;
                    591: 	} else {
                    592: 	    if ($sec eq $perm{'vgr_section'}) {
                    593: 		#can modify the requested section
                    594: 		return 1;
                    595: 	    } else {
                    596: 		# can't modify the request section
                    597: 		return 0;
                    598: 	    }
                    599: 	}
                    600:     }
                    601:     #can't modify
                    602:     return 0;
                    603: }
                    604: 
1.44      ng        605: #--- Retrieve the grade status of a student for all the parts
                    606: sub student_gradeStatus {
1.324     albertel  607:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  608:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        609:     my %partstatus = ();
                    610:     foreach (@$partlist) {
1.128     ng        611: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        612: 	$status              = 'nothing' if ($status eq '');
                    613: 	$partstatus{$_}      = $status;
                    614: 	my $subkey           = "resource.$_.submitted_by";
                    615: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    616:     }
                    617:     return %partstatus;
                    618: }
                    619: 
1.45      ng        620: # hidden form and javascript that calls the form
                    621: # Use by verifyscript and viewgrades
                    622: # Shows a student's view of problem and submission
                    623: sub jscriptNform {
1.324     albertel  624:     my ($symb) = @_;
1.442     banghart  625:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        626:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    627: 	'    function viewOneStudent(user,domain) {'."\n".
                    628: 	'	document.onestudent.student.value = user;'."\n".
                    629: 	'	document.onestudent.userdom.value = domain;'."\n".
                    630: 	'	document.onestudent.submit();'."\n".
                    631: 	'    }'."\n".
                    632: 	'</script>'."\n";
                    633:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  634: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  635: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    636: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  637: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        638: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    639: 	'<input type="hidden" name="student" value="" />'."\n".
                    640: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    641: 	'</form>'."\n";
                    642:     return $jscript;
                    643: }
1.39      ng        644: 
1.447     foxr      645: 
                    646: 
1.315     bowersj2  647: # Given the score (as a number [0-1] and the weight) what is the final
                    648: # point value? This function will round to the nearest tenth, third,
                    649: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  650: sub compute_points {
1.315     bowersj2  651:     my ($score, $weight) = @_;
                    652:     
                    653:     my $tolerance = .00001;
                    654:     my $points = $score * $weight;
                    655: 
                    656:     # Check for nearness to 1/x.
                    657:     my $check_for_nearness = sub {
                    658:         my ($factor) = @_;
                    659:         my $num = ($points * $factor) + $tolerance;
                    660:         my $floored_num = floor($num);
1.316     albertel  661:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  662:             return $floored_num / $factor;
                    663:         }
                    664:         return $points;
                    665:     };
                    666: 
                    667:     $points = $check_for_nearness->(10);
                    668:     $points = $check_for_nearness->(3);
                    669:     $points = $check_for_nearness->(4);
                    670:     
                    671:     return $points;
                    672: }
                    673: 
1.44      ng        674: #------------------ End of general use routines --------------------
1.87      www       675: 
                    676: #
                    677: # Find most similar essay
                    678: #
                    679: 
                    680: sub most_similar {
1.426     albertel  681:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       682: 
                    683: # ignore spaces and punctuation
                    684: 
                    685:     $uessay=~s/\W+/ /gs;
                    686: 
1.282     www       687: # ignore empty submissions (occuring when only files are sent)
                    688: 
                    689:     unless ($uessay=~/\w+/) { return ''; }
                    690: 
1.87      www       691: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       692:     my $limit=0.6;
1.87      www       693:     my $sname='';
                    694:     my $sdom='';
                    695:     my $scrsid='';
                    696:     my $sessay='';
                    697: # go through all essays ...
1.426     albertel  698:     foreach my $tkey (keys(%$old_essays)) {
                    699: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       700: # ... except the same student
1.426     albertel  701:         next if (($tname eq $uname) && ($tdom eq $udom));
                    702: 	my $tessay=$old_essays->{$tkey};
                    703: 	$tessay=~s/\W+/ /gs;
1.87      www       704: # String similarity gives up if not even limit
1.426     albertel  705: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       706: # Found one
1.426     albertel  707: 	if ($tsimilar>$limit) {
                    708: 	    $limit=$tsimilar;
                    709: 	    $sname=$tname;
                    710: 	    $sdom=$tdom;
                    711: 	    $scrsid=$tcrsid;
                    712: 	    $sessay=$old_essays->{$tkey};
                    713: 	}
1.87      www       714:     }
1.88      www       715:     if ($limit>0.6) {
1.87      www       716:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    717:     } else {
                    718:        return ('','','','',0);
                    719:     }
                    720: }
                    721: 
1.44      ng        722: #-------------------------------------------------------------------
                    723: 
                    724: #------------------------------------ Receipt Verification Routines
1.45      ng        725: #
1.44      ng        726: #--- Check whether a receipt number is valid.---
                    727: sub verifyreceipt {
                    728:     my $request  = shift;
                    729: 
1.257     albertel  730:     my $courseid = $env{'request.course.id'};
1.184     www       731:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  732: 	$env{'form.receipt'};
1.44      ng        733:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  734:     my ($symb)   = &get_symb($request);
1.44      ng        735: 
1.398     albertel  736:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    737: 	$receipt.'</h3></span>'."\n".
                    738: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        739: 
                    740:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   741:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  742:     
                    743:     my $receiptparts=0;
1.390     albertel  744:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    745: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  746:     my $parts=['0'];
1.324     albertel  747:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  748:     foreach (sort 
                    749: 	     {
                    750: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    751: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    752: 		 }
                    753: 		 return $a cmp $b;
                    754: 	     } (keys(%$fullname))) {
1.44      ng        755: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  756: 	foreach my $part (@$parts) {
                    757: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    758: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    759: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  760: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  761: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    762: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    763: 		if ($receiptparts) {
                    764: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    765: 		}
                    766: 		$contents.='</tr>'."\n";
                    767: 		
                    768: 		$matches++;
                    769: 	    }
1.44      ng        770: 	}
                    771:     }
                    772:     if ($matches == 0) {
                    773: 	$string = $title.'No match found for the above receipt.';
                    774:     } else {
1.324     albertel  775: 	$string = &jscriptNform($symb).$title.
1.44      ng        776: 	    'The above receipt matches the following student'.
                    777: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    778: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    779: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    780: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    781: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  782: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    783: 	if ($receiptparts) {
                    784: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    785: 	}
                    786: 	$string.='</tr>'."\n".$contents.
1.44      ng        787: 	    '</table></td></tr></table>'."\n";
                    788:     }
1.324     albertel  789:     return $string.&show_grading_menu_form($symb);
1.44      ng        790: }
                    791: 
                    792: #--- This is called by a number of programs.
                    793: #--- Called from the Grading Menu - View/Grade an individual student
                    794: #--- Also called directly when one clicks on the subm button 
                    795: #    on the problem page.
1.30      ng        796: sub listStudents {
1.41      ng        797:     my ($request) = shift;
1.49      albertel  798: 
1.324     albertel  799:     my ($symb) = &get_symb($request);
1.257     albertel  800:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    801:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    802:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  803:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  804:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    805:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    806:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    807: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  808: 
1.398     albertel  809:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    810: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        811: 
1.324     albertel  812:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  813: 
1.45      ng        814:     $request->print(<<LISTJAVASCRIPT);
                    815: <script type="text/javascript" language="javascript">
1.110     ng        816:     function checkSelect(checkBox) {
                    817: 	var ctr=0;
                    818: 	var sense="";
                    819: 	if (checkBox.length > 1) {
                    820: 	    for (var i=0; i<checkBox.length; i++) {
                    821: 		if (checkBox[i].checked) {
                    822: 		    ctr++;
                    823: 		}
                    824: 	    }
                    825: 	    sense = "a student or group of students";
                    826: 	} else {
                    827: 	    if (checkBox.checked) {
                    828: 		ctr = 1;
                    829: 	    }
                    830: 	    sense = "the student";
                    831: 	}
                    832: 	if (ctr == 0) {
1.126     ng        833: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        834: 	    return false;
                    835: 	}
                    836: 	document.gradesub.submit();
                    837:     }
                    838: 
                    839:     function reLoadList(formname) {
1.112     ng        840: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        841: 	formname.command.value = 'submission';
                    842: 	formname.submit();
                    843:     }
1.45      ng        844: </script>
                    845: LISTJAVASCRIPT
                    846: 
1.118     ng        847:     &commonJSfunctions($request);
1.41      ng        848:     $request->print($result);
1.39      ng        849: 
1.401     albertel  850:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    851:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  852:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    853: 	"\n".$table.
1.401     albertel  854: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  855: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    856: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    857: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    858: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  859: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  860: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  861:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  862: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  863:     }
1.442     banghart  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    865:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  866:     $env{'form.Status'} = $saveStatus;
1.267     albertel  867:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    868: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    869: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  870: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    871:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    872:         '<option value="1">Whole Points</option>'.
                    873:         '<option value=".5">Half Points</option>'.
1.349     albertel  874:         '<option value=".25">Quarter Points</option>'.
                    875:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  876:         '</select>'.
1.432     banghart  877:         &build_section_inputs().
1.45      ng        878: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  879: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    880: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    881: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    882: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  883: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        884: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    885: 
1.257     albertel  886:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  887: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        888:     } else {
                    889: 	$gradeTable.='<b>Student Status:</b> '.
                    890: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    891:     }
1.112     ng        892: 
1.126     ng        893:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    894: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        895: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  896: 
                    897: # checkall buttons
                    898:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        899:     $gradeTable.='<input type="button" '."\n".
1.45      ng        900: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  901: 	'value="Next->" /> <br />'."\n";
                    902:     $gradeTable.=&check_buttons();
1.401     albertel  903:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.450     banghart  904:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.45      ng        905:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        906: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    907:     my $loop = 0;
                    908:     while ($loop < 2) {
1.126     ng        909: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  910: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  911: 	if ($env{'form.showgrading'} eq 'yes' 
                    912: 	    && $submitonly ne 'queued'
                    913: 	    && $submitonly ne 'all') {
1.110     ng        914: 	    foreach (sort(@$partlist)) {
1.324     albertel  915: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  916: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    917: 		    ' Status&nbsp;</b></td>';
1.110     ng        918: 	    }
1.301     albertel  919: 	} elsif ($submitonly eq 'queued') {
                    920: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        921: 	}
                    922: 	$loop++;
1.126     ng        923: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        924:     }
1.45      ng        925:     $gradeTable.='</tr>'."\n";
1.41      ng        926: 
1.45      ng        927:     my $ctr = 0;
1.294     albertel  928:     foreach my $student (sort 
                    929: 			 {
                    930: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    931: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    932: 			     }
                    933: 			     return $a cmp $b;
                    934: 			 }
                    935: 			 (keys(%$fullname))) {
1.41      ng        936: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  937: 
1.110     ng        938: 	my %status = ();
1.301     albertel  939: 
                    940: 	if ($submitonly eq 'queued') {
                    941: 	    my %queue_status = 
                    942: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    943: 							$udom,$uname);
                    944: 	    next if (!defined($queue_status{'gradingqueue'}));
                    945: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    946: 	}
                    947: 
                    948: 	if ($env{'form.showgrading'} eq 'yes' 
                    949: 	    && $submitonly ne 'queued'
                    950: 	    && $submitonly ne 'all') {
1.324     albertel  951: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  952: 	    my $submitted = 0;
1.164     albertel  953: 	    my $graded = 0;
1.248     albertel  954: 	    my $incorrect = 0;
1.110     ng        955: 	    foreach (keys(%status)) {
1.145     albertel  956: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  957: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    958: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    959: 		
1.110     ng        960: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    961: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  962: 		    $submitted = 0;
1.150     albertel  963: 		    my ($part)=split(/\./,$partid);
1.110     ng        964: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  965: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        966: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    967: 		}
1.41      ng        968: 	    }
1.248     albertel  969: 	    
1.156     albertel  970: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    971: 				     $submitonly eq 'incorrect' ||
                    972: 				     $submitonly eq 'graded'));
1.248     albertel  973: 	    next if (!$graded && ($submitonly eq 'graded'));
                    974: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        975: 	}
1.34      ng        976: 
1.45      ng        977: 	$ctr++;
1.249     albertel  978: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart  979:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel  980: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        981: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        982: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  983:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    984:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    985: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    986: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.452     banghart  987: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
1.110     ng        988: 
1.257     albertel  989: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        990: 		foreach (sort keys(%status)) {
                    991: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  992: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        993: 		}
1.41      ng        994: 	    }
1.126     ng        995: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        996: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        997: 	}
                    998:     }
1.110     ng        999:     if ($ctr%2 ==1) {
1.126     ng       1000: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1001: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1002: 		&& $submitonly ne 'queued'
                   1003: 		&& $submitonly ne 'all') {
1.110     ng       1004: 		foreach (@$partlist) {
                   1005: 		    $gradeTable.='<td>&nbsp;</td>';
                   1006: 		}
1.301     albertel 1007: 	    } elsif ($submitonly eq 'queued') {
                   1008: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1009: 	    }
                   1010: 	$gradeTable.='</tr>';
                   1011:     }
                   1012: 
1.249     albertel 1013:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng       1014: 	'<input type="button" '.
                   1015: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1016: 	'value="Next->" /></form>'."\n";
1.45      ng       1017:     if ($ctr == 0) {
1.96      albertel 1018: 	my $num_students=(scalar(keys(%$fullname)));
                   1019: 	if ($num_students eq 0) {
1.398     albertel 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1021: 	} else {
1.171     albertel 1022: 	    my $submissions='submissions';
                   1023: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1024: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1025: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1026: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1027: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1028: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1029: 	}
1.46      ng       1030:     } elsif ($ctr == 1) {
                   1031: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1032:     }
1.324     albertel 1033:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1034:     $request->print($gradeTable);
1.44      ng       1035:     return '';
1.10      ng       1036: }
                   1037: 
1.44      ng       1038: #---- Called from the listStudents routine
1.249     albertel 1039: 
                   1040: sub check_script {
                   1041:     my ($form, $type)=@_;
                   1042:     my $chkallscript='<script type="text/javascript">
                   1043:     function checkall() {
                   1044:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1045:             ele = document.forms.'.$form.'.elements[i];
                   1046:             if (ele.name == "'.$type.'") {
                   1047:             document.forms.'.$form.'.elements[i].checked=true;
                   1048:                                        }
                   1049:         }
                   1050:     }
                   1051: 
                   1052:     function checksec() {
                   1053:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1054:             ele = document.forms.'.$form.'.elements[i];
                   1055:            string = document.forms.'.$form.'.chksec.value;
                   1056:            if
                   1057:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1058:               document.forms.'.$form.'.elements[i].checked=true;
                   1059:             }
                   1060:         }
                   1061:     }
                   1062: 
                   1063: 
                   1064:     function uncheckall() {
                   1065:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1066:             ele = document.forms.'.$form.'.elements[i];
                   1067:             if (ele.name == "'.$type.'") {
                   1068:             document.forms.'.$form.'.elements[i].checked=false;
                   1069:                                        }
                   1070:         }
                   1071:     }
                   1072: 
                   1073: </script>'."\n";
                   1074:     return $chkallscript;
                   1075: }
                   1076: 
                   1077: sub check_buttons {
                   1078:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1079:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1080:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1081:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1082:     return $buttons;
                   1083: }
                   1084: 
1.44      ng       1085: #     Displays the submissions for one student or a group of students
1.34      ng       1086: sub processGroup {
1.41      ng       1087:     my ($request)  = shift;
                   1088:     my $ctr        = 0;
1.155     albertel 1089:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1090:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1091: 
1.396     banghart 1092:     foreach my $student (@stuchecked) {
                   1093: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1094: 	$env{'form.student'}        = $uname;
                   1095: 	$env{'form.userdom'}        = $udom;
                   1096: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1097: 	&submission($request,$ctr,$total);
                   1098: 	$ctr++;
                   1099:     }
                   1100:     return '';
1.35      ng       1101: }
1.34      ng       1102: 
1.44      ng       1103: #------------------------------------------------------------------------------------
                   1104: #
                   1105: #-------------------------- Next few routines handles grading by student, essentially
                   1106: #                           handles essay response type problem/part
                   1107: #
                   1108: #--- Javascript to handle the submission page functionality ---
                   1109: sub sub_page_js {
                   1110:     my $request = shift;
                   1111:     $request->print(<<SUBJAVASCRIPT);
                   1112: <script type="text/javascript" language="javascript">
1.71      ng       1113:     function updateRadio(formname,id,weight) {
1.125     ng       1114: 	var gradeBox = formname["GD_BOX"+id];
                   1115: 	var radioButton = formname["RADVAL"+id];
                   1116: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1117: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1118: 	gradeBox.value = pts;
                   1119: 	var resetbox = false;
                   1120: 	if (isNaN(pts) || pts < 0) {
                   1121: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1122: 	    for (var i=0; i<radioButton.length; i++) {
                   1123: 		if (radioButton[i].checked) {
                   1124: 		    gradeBox.value = i;
                   1125: 		    resetbox = true;
                   1126: 		}
                   1127: 	    }
                   1128: 	    if (!resetbox) {
                   1129: 		formtextbox.value = "";
                   1130: 	    }
                   1131: 	    return;
1.44      ng       1132: 	}
1.71      ng       1133: 
                   1134: 	if (pts > weight) {
                   1135: 	    var resp = confirm("You entered a value ("+pts+
                   1136: 			       ") greater than the weight for the part. Accept?");
                   1137: 	    if (resp == false) {
1.125     ng       1138: 		gradeBox.value = oldpts;
1.71      ng       1139: 		return;
                   1140: 	    }
1.44      ng       1141: 	}
1.13      albertel 1142: 
1.71      ng       1143: 	for (var i=0; i<radioButton.length; i++) {
                   1144: 	    radioButton[i].checked=false;
                   1145: 	    if (pts == i && pts != "") {
                   1146: 		radioButton[i].checked=true;
                   1147: 	    }
                   1148: 	}
                   1149: 	updateSelect(formname,id);
1.125     ng       1150: 	formname["stores"+id].value = "0";
1.41      ng       1151:     }
1.5       albertel 1152: 
1.72      ng       1153:     function writeBox(formname,id,pts) {
1.125     ng       1154: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1155: 	if (checkSolved(formname,id) == 'update') {
                   1156: 	    gradeBox.value = pts;
                   1157: 	} else {
1.125     ng       1158: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1159: 	    gradeBox.value = oldpts;
1.125     ng       1160: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1161: 	    for (var i=0; i<radioButton.length; i++) {
                   1162: 		radioButton[i].checked=false;
1.72      ng       1163: 		if (i == oldpts) {
1.71      ng       1164: 		    radioButton[i].checked=true;
                   1165: 		}
                   1166: 	    }
1.41      ng       1167: 	}
1.125     ng       1168: 	formname["stores"+id].value = "0";
1.71      ng       1169: 	updateSelect(formname,id);
                   1170: 	return;
1.41      ng       1171:     }
1.44      ng       1172: 
1.71      ng       1173:     function clearRadBox(formname,id) {
                   1174: 	if (checkSolved(formname,id) == 'noupdate') {
                   1175: 	    updateSelect(formname,id);
                   1176: 	    return;
                   1177: 	}
1.125     ng       1178: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1179: 	for (var i=0; i<gradeSelect.length; i++) {
                   1180: 	    if (gradeSelect[i].selected) {
                   1181: 		var selectx=i;
                   1182: 	    }
                   1183: 	}
1.125     ng       1184: 	var stores = formname["stores"+id];
1.71      ng       1185: 	if (selectx == stores.value) { return };
1.125     ng       1186: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1187: 	gradeBox.value = "";
1.125     ng       1188: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1189: 	for (var i=0; i<radioButton.length; i++) {
                   1190: 	    radioButton[i].checked=false;
                   1191: 	}
                   1192: 	stores.value = selectx;
                   1193:     }
1.5       albertel 1194: 
1.71      ng       1195:     function checkSolved(formname,id) {
1.125     ng       1196: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1197: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1198: 	    if (!reply) {return "noupdate";}
1.120     ng       1199: 	    formname.overRideScore.value = 'yes';
1.41      ng       1200: 	}
1.71      ng       1201: 	return "update";
1.13      albertel 1202:     }
1.71      ng       1203: 
                   1204:     function updateSelect(formname,id) {
1.125     ng       1205: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1206: 	return;
1.41      ng       1207:     }
1.33      ng       1208: 
1.121     ng       1209: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1210:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1211: 	formname.gradeOpt.value = val;
1.71      ng       1212: 	if (val == "Save & Next") {
                   1213: 	    for (i=0;i<=total;i++) {
                   1214: 		for (j=0;j<parttot;j++) {
1.125     ng       1215: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1216: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1217: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1218: 			if (points == "") {
1.125     ng       1219: 			    var name = formname["name"+i].value;
1.129     ng       1220: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1221: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1222: 					       ", part "+partid+". Continue?");
1.71      ng       1223: 			    if (resp == false) {
1.125     ng       1224: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1225: 				return false;
                   1226: 			    }
                   1227: 			}
                   1228: 		    }
                   1229: 		    
                   1230: 		}
                   1231: 	    }
                   1232: 	    
                   1233: 	}
1.121     ng       1234: 	if (val == "Grade Student") {
                   1235: 	    formname.showgrading.value = "yes";
                   1236: 	    if (formname.Status.value == "") {
                   1237: 		formname.Status.value = "Active";
                   1238: 	    }
                   1239: 	    formname.studentNo.value = total;
                   1240: 	}
1.120     ng       1241: 	formname.submit();
                   1242:     }
                   1243: 
1.71      ng       1244: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1245:     function checkSubmitPage(formname,total) {
                   1246: 	noscore = new Array(100);
                   1247: 	var ptr = 0;
                   1248: 	for (i=1;i<total;i++) {
1.125     ng       1249: 	    var partid = formname["q_"+i].value;
1.127     ng       1250: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1251: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1252: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1253: 		if (points == "" && status != "correct_by_student") {
                   1254: 		    noscore[ptr] = i;
                   1255: 		    ptr++;
                   1256: 		}
                   1257: 	    }
                   1258: 	}
                   1259: 	if (ptr != 0) {
                   1260: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1261: 	    var prolist = "";
                   1262: 	    if (ptr == 1) {
                   1263: 		prolist = noscore[0];
                   1264: 	    } else {
                   1265: 		var i = 0;
                   1266: 		while (i < ptr-1) {
                   1267: 		    prolist += noscore[i]+", ";
                   1268: 		    i++;
                   1269: 		}
                   1270: 		prolist += "and "+noscore[i];
                   1271: 	    }
                   1272: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1273: 	    if (resp == false) {
                   1274: 		return false;
                   1275: 	    }
                   1276: 	}
1.45      ng       1277: 
1.71      ng       1278: 	formname.submit();
                   1279:     }
                   1280: </script>
                   1281: SUBJAVASCRIPT
                   1282: }
1.45      ng       1283: 
1.71      ng       1284: #--- javascript for essay type problem --
                   1285: sub sub_page_kw_js {
                   1286:     my $request = shift;
1.80      ng       1287:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1288:     &commonJSfunctions($request);
1.350     albertel 1289: 
1.351     albertel 1290:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1291:     <script text="text/javascript">
                   1292:     function checkInput() {
                   1293:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1294:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1295:       var usrctr = document.msgcenter.usrctr.value;
                   1296:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1297:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1298: 
                   1299:       var msgchk = "";
                   1300:       if (document.msgcenter.subchk.checked) {
                   1301:          msgchk = "msgsub,";
                   1302:       }
                   1303:       var includemsg = 0;
                   1304:       for (var i=1; i<=nmsg; i++) {
                   1305:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1306:           var frmmsg = document.msgcenter["msg"+i];
                   1307:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1308:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1309:           showflg.value = "1";
                   1310:           var chkbox = document.msgcenter["msgn"+i];
                   1311:           if (chkbox.checked) {
                   1312:              msgchk += "savemsg"+i+",";
                   1313:              includemsg = 1;
                   1314:           }
                   1315:       }
                   1316:       if (document.msgcenter.newmsgchk.checked) {
                   1317:          msgchk += "newmsg"+usrctr;
                   1318:          includemsg = 1;
                   1319:       }
                   1320:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1321:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1322:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1323:       includemsg.value = msgchk;
                   1324: 
                   1325:       self.close()
                   1326: 
                   1327:     }
                   1328:     </script>
                   1329: INNERJS
                   1330: 
1.351     albertel 1331:     my $inner_js_highlight_central=<<INNERJS;
                   1332:  <script type="text/javascript">
                   1333:     function updateChoice(flag) {
                   1334:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1335:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1336:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1337:       opener.document.SCORE.refresh.value = "on";
                   1338:       if (opener.document.SCORE.keywords.value!=""){
                   1339:          opener.document.SCORE.submit();
                   1340:       }
                   1341:       self.close()
                   1342:     }
                   1343: </script>
                   1344: INNERJS
                   1345: 
                   1346:     my $start_page_msg_central = 
                   1347:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1348: 				       {'js_ready'  => 1,
                   1349: 					'only_body' => 1,
                   1350: 					'bgcolor'   =>'#FFFFFF',});
                   1351:     my $end_page_msg_central = 
                   1352: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1353: 
                   1354: 
                   1355:     my $start_page_highlight_central = 
                   1356:         &Apache::loncommon::start_page('Highlight Central',
                   1357: 				       $inner_js_highlight_central,
1.350     albertel 1358: 				       {'js_ready'  => 1,
                   1359: 					'only_body' => 1,
                   1360: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1361:     my $end_page_highlight_central = 
1.350     albertel 1362: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1363: 
1.219     www      1364:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1365:     $docopen=~s/^document\.//;
1.71      ng       1366:     $request->print(<<SUBJAVASCRIPT);
                   1367: <script type="text/javascript" language="javascript">
1.45      ng       1368: 
1.44      ng       1369: //===================== Show list of keywords ====================
1.122     ng       1370:   function keywords(formname) {
                   1371:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1372:     if (nret==null) return;
1.122     ng       1373:     formname.keywords.value = nret;
1.44      ng       1374: 
1.122     ng       1375:     if (formname.keywords.value != "") {
1.128     ng       1376: 	formname.refresh.value = "on";
1.122     ng       1377: 	formname.submit();
1.44      ng       1378:     }
                   1379:     return;
                   1380:   }
                   1381: 
                   1382: //===================== Script to view submitted by ==================
                   1383:   function viewSubmitter(submitter) {
                   1384:     document.SCORE.refresh.value = "on";
                   1385:     document.SCORE.NCT.value = "1";
                   1386:     document.SCORE.unamedom0.value = submitter;
                   1387:     document.SCORE.submit();
                   1388:     return;
                   1389:   }
                   1390: 
                   1391: //===================== Script to add keyword(s) ==================
                   1392:   function getSel() {
                   1393:     if (document.getSelection) txt = document.getSelection();
                   1394:     else if (document.selection) txt = document.selection.createRange().text;
                   1395:     else return;
                   1396:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1397:     if (cleantxt=="") {
1.46      ng       1398: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1399: 	return;
                   1400:     }
                   1401:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1402:     if (nret==null) return;
1.127     ng       1403:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1404:     if (document.SCORE.keywords.value != "") {
1.127     ng       1405: 	document.SCORE.refresh.value = "on";
1.44      ng       1406: 	document.SCORE.submit();
                   1407:     }
                   1408:     return;
                   1409:   }
                   1410: 
                   1411: //====================== Script for composing message ==============
1.80      ng       1412:    // preload images
                   1413:    img1 = new Image();
                   1414:    img1.src = "$iconpath/mailbkgrd.gif";
                   1415:    img2 = new Image();
                   1416:    img2.src = "$iconpath/mailto.gif";
                   1417: 
1.44      ng       1418:   function msgCenter(msgform,usrctr,fullname) {
                   1419:     var Nmsg  = msgform.savemsgN.value;
                   1420:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1421:     var subject = msgform.msgsub.value;
1.127     ng       1422:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1423:     re = /msgsub/;
                   1424:     var shwsel = "";
                   1425:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1426:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1427:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1428:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1429: 	var testmsg = "savemsg"+i+",";
                   1430: 	re = new RegExp(testmsg,"g");
1.44      ng       1431: 	shwsel = "";
                   1432: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1433: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1434: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1435: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1436: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1437:     }
1.125     ng       1438:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1439:     shwsel = "";
                   1440:     re = /newmsg/;
                   1441:     if (re.test(msgchk)) { shwsel = "checked" }
                   1442:     newMsg(newmsg,shwsel);
                   1443:     msgTail(); 
                   1444:     return;
                   1445:   }
                   1446: 
1.123     ng       1447:   function checkEntities(strx) {
                   1448:     if (strx.length == 0) return strx;
                   1449:     var orgStr = ["&", "<", ">", '"']; 
                   1450:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1451:     var counter = 0;
                   1452:     while (counter < 4) {
                   1453: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1454: 	counter++;
                   1455:     }
                   1456:     return strx;
                   1457:   }
                   1458: 
                   1459:   function strReplace(strx, orgStr, newStr) {
                   1460:     return strx.split(orgStr).join(newStr);
                   1461:   }
                   1462: 
1.44      ng       1463:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1464:     var height = 70*Nmsg+250;
1.44      ng       1465:     var scrollbar = "no";
                   1466:     if (height > 600) {
                   1467: 	height = 600;
                   1468: 	scrollbar = "yes";
                   1469:     }
1.118     ng       1470:     var xpos = (screen.width-600)/2;
                   1471:     xpos = (xpos < 0) ? '0' : xpos;
                   1472:     var ypos = (screen.height-height)/2-30;
                   1473:     ypos = (ypos < 0) ? '0' : ypos;
                   1474: 
1.206     albertel 1475:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1476:     pWin.focus();
                   1477:     pDoc = pWin.document;
1.219     www      1478:     pDoc.$docopen;
1.351     albertel 1479:     pDoc.write('$start_page_msg_central');
1.76      ng       1480: 
                   1481:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1482:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1483:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1484: 
                   1485:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1486:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1487:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1488: }
                   1489:     function displaySubject(msg,shwsel) {
1.76      ng       1490:     pDoc = pWin.document;
                   1491:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1492:     pDoc.write("<td>Subject</td>");
                   1493:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1494:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1495: }
                   1496: 
1.72      ng       1497:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1498:     pDoc = pWin.document;
                   1499:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1500:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1501:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1502:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1503: }
                   1504: 
                   1505:   function newMsg(newmsg,shwsel) {
1.76      ng       1506:     pDoc = pWin.document;
                   1507:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1508:     pDoc.write("<td align=\\"center\\">New</td>");
                   1509:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1510:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1511: }
                   1512: 
                   1513:   function msgTail() {
1.76      ng       1514:     pDoc = pWin.document;
                   1515:     pDoc.write("</table>");
                   1516:     pDoc.write("</td></tr></table>&nbsp;");
                   1517:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1518:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1519:     pDoc.write("</form>");
1.351     albertel 1520:     pDoc.write('$end_page_msg_central');
1.128     ng       1521:     pDoc.close();
1.44      ng       1522: }
                   1523: 
                   1524: //====================== Script for keyword highlight options ==============
                   1525:   function kwhighlight() {
                   1526:     var kwclr    = document.SCORE.kwclr.value;
                   1527:     var kwsize   = document.SCORE.kwsize.value;
                   1528:     var kwstyle  = document.SCORE.kwstyle.value;
                   1529:     var redsel = "";
                   1530:     var grnsel = "";
                   1531:     var blusel = "";
                   1532:     if (kwclr=="red")   {var redsel="checked"};
                   1533:     if (kwclr=="green") {var grnsel="checked"};
                   1534:     if (kwclr=="blue")  {var blusel="checked"};
                   1535:     var sznsel = "";
                   1536:     var sz1sel = "";
                   1537:     var sz2sel = "";
                   1538:     if (kwsize=="0")  {var sznsel="checked"};
                   1539:     if (kwsize=="+1") {var sz1sel="checked"};
                   1540:     if (kwsize=="+2") {var sz2sel="checked"};
                   1541:     var synsel = "";
                   1542:     var syisel = "";
                   1543:     var sybsel = "";
                   1544:     if (kwstyle=="")    {var synsel="checked"};
                   1545:     if (kwstyle=="<i>") {var syisel="checked"};
                   1546:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1547:     highlightCentral();
                   1548:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1549:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1550:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1551:     highlightend();
                   1552:     return;
                   1553:   }
                   1554: 
                   1555:   function highlightCentral() {
1.76      ng       1556: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1557:     var xpos = (screen.width-400)/2;
                   1558:     xpos = (xpos < 0) ? '0' : xpos;
                   1559:     var ypos = (screen.height-330)/2-30;
                   1560:     ypos = (ypos < 0) ? '0' : ypos;
                   1561: 
1.206     albertel 1562:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1563:     hwdWin.focus();
                   1564:     var hDoc = hwdWin.document;
1.219     www      1565:     hDoc.$docopen;
1.351     albertel 1566:     hDoc.write('$start_page_highlight_central');
1.76      ng       1567:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1568:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1569: 
                   1570:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1571:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1572:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1573:   }
                   1574: 
                   1575:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1576:     var hDoc = hwdWin.document;
                   1577:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1578:     hDoc.write("<td align=\\"left\\">");
                   1579:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1580:     hDoc.write("<td align=\\"left\\">");
                   1581:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1582:     hDoc.write("<td align=\\"left\\">");
                   1583:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1584:     hDoc.write("</tr>");
1.44      ng       1585:   }
                   1586: 
                   1587:   function highlightend() { 
1.76      ng       1588:     var hDoc = hwdWin.document;
                   1589:     hDoc.write("</table>");
                   1590:     hDoc.write("</td></tr></table>&nbsp;");
                   1591:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1592:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1593:     hDoc.write("</form>");
1.351     albertel 1594:     hDoc.write('$end_page_highlight_central');
1.128     ng       1595:     hDoc.close();
1.44      ng       1596:   }
                   1597: 
                   1598: </script>
                   1599: SUBJAVASCRIPT
                   1600: }
                   1601: 
1.349     albertel 1602: sub get_increment {
1.348     bowersj2 1603:     my $increment = $env{'form.increment'};
                   1604:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1605:         $increment != .1) {
                   1606:         $increment = 1;
                   1607:     }
                   1608:     return $increment;
                   1609: }
                   1610: 
1.71      ng       1611: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1612: sub gradeBox {
1.322     albertel 1613:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1614:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1615: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1616: 	'/check.gif" height="16" border="0" />';
                   1617:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1618:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1619: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1620:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1621:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1622: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1623:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1624:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1625:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1626: 				       [$partid]);
                   1627:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1628:     if ($last_resets{$partid}) {
                   1629:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1630:     }
1.71      ng       1631:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1632: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1633:     my $ctr = 0;
1.348     bowersj2 1634:     my $thisweight = 0;
1.349     albertel 1635:     my $increment = &get_increment();
1.71      ng       1636:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1637:     while ($thisweight<=$wgt) {
1.381     albertel 1638: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1639: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1640: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1641: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1642: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1643:         $thisweight += $increment;
1.71      ng       1644: 	$ctr++;
                   1645:     }
                   1646:     $result.='</tr></table>';
                   1647:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1648:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1649: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1650: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1651: 	$wgt.')" /></td>'."\n";
                   1652:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1653: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1654: 	' </td><td>'."\n";
                   1655:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1656: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1657:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1658: 	$result.='<option></option>'.
1.401     albertel 1659: 	    '<option selected="selected">excused</option>';
1.71      ng       1660:     } else {
1.401     albertel 1661: 	$result.='<option selected="selected"></option>'.
1.125     ng       1662: 	    '<option>excused</option>';
1.71      ng       1663:     }
1.125     ng       1664:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1665:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1666:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1667: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1668: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1669: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1670:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1671:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1672:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1673:         $aggtries.'" />'."\n";
1.71      ng       1674:     $result.='</td></tr></table>'."\n";
1.323     banghart 1675:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1676:     return $result;
                   1677: }
1.322     albertel 1678: 
                   1679: sub handback_box {
1.323     banghart 1680:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1681:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1682:     my (@respids);
1.375     albertel 1683:      my @part_response_id = &flatten_responseType($responseType);
                   1684:     foreach my $part_response_id (@part_response_id) {
                   1685:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1686:         if ($part eq $partid) {
1.375     albertel 1687:             push(@respids,$resp);
1.323     banghart 1688:         }
                   1689:     }
1.318     banghart 1690:     my $result;
1.323     banghart 1691:     foreach my $respid (@respids) {
1.322     albertel 1692: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1693: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1694: 	next if (!@$files);
                   1695: 	my $file_counter = 1;
1.313     banghart 1696: 	foreach my $file (@$files) {
1.368     banghart 1697: 	    if ($file =~ /\/portfolio\//) {
                   1698:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1699:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1700:     	        $file_disp = "$name.$ext";
                   1701:     	        $file = $file_path.$file_disp;
                   1702:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1703:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1704:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1705:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1706:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1707:     	        $file_counter++;
                   1708: 	    }
1.322     albertel 1709: 	}
1.313     banghart 1710:     }
1.318     banghart 1711:     return $result;    
1.71      ng       1712: }
1.44      ng       1713: 
1.58      albertel 1714: sub show_problem {
1.382     albertel 1715:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1716:     my $rendered;
1.382     albertel 1717:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1718:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1719:     if ($mode eq 'both' or $mode eq 'text') {
                   1720: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1721: 						       $env{'request.course.id'},
                   1722: 						       undef,\%form);
1.144     albertel 1723:     }
1.58      albertel 1724:     if ($removeform) {
                   1725: 	$rendered=~s|<form(.*?)>||g;
                   1726: 	$rendered=~s|</form>||g;
1.374     albertel 1727: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1728:     }
1.144     albertel 1729:     my $companswer;
                   1730:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1731: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1732: 	$companswer=
                   1733: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1734: 						    $env{'request.course.id'},
                   1735: 						    %form);
1.144     albertel 1736:     }
1.58      albertel 1737:     if ($removeform) {
                   1738: 	$companswer=~s|<form(.*?)>||g;
                   1739: 	$companswer=~s|</form>||g;
1.144     albertel 1740: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1741:     }
                   1742:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1743:     $result.='<table border="0" width="100%">';
1.144     albertel 1744:     if ($viewon) {
                   1745: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1746: 	if ($mode eq 'both' or $mode eq 'text') {
                   1747: 	    $result.='View of the problem - ';
                   1748: 	} else {
                   1749: 	    $result.='Correct answer: ';
                   1750: 	}
1.257     albertel 1751: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1752:     }
                   1753:     if ($mode eq 'both') {
                   1754: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1755: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1756:     } elsif ($mode eq 'text') {
                   1757: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1758:     } elsif ($mode eq 'answer') {
                   1759: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1760:     }
1.58      albertel 1761:     $result.='</td></tr></table>';
                   1762:     $result.='</td></tr></table><br />';
1.71      ng       1763:     return $result;
1.58      albertel 1764: }
1.397     albertel 1765: 
1.396     banghart 1766: sub files_exist {
                   1767:     my ($r, $symb) = @_;
                   1768:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1769: 
1.396     banghart 1770:     foreach my $student (@students) {
                   1771:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1772:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1773: 					      $udom,$uname);
1.396     banghart 1774:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1775:         foreach my $submission (@$string) {
                   1776:             my ($partid,$respid) =
                   1777: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1778:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1779: 					   \%record);
                   1780:             return 1 if (@$files);
1.396     banghart 1781:         }
                   1782:     }
1.397     albertel 1783:     return 0;
1.396     banghart 1784: }
1.397     albertel 1785: 
1.394     banghart 1786: sub download_all_link {
                   1787:     my ($r,$symb) = @_;
1.395     albertel 1788:     my $all_students = 
                   1789: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1790: 
                   1791:     my $parts =
                   1792: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1793: 
1.394     banghart 1794:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1795:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1796:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1797:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1798:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1799: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1800:     return
                   1801: }
1.395     albertel 1802: 
1.432     banghart 1803: sub build_section_inputs {
                   1804:     my $section_inputs;
                   1805:     if ($env{'form.section'} eq '') {
                   1806:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1807:     } else {
                   1808:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1809:         foreach my $section (@sections) {
1.432     banghart 1810:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1811:         }
                   1812:     }
                   1813:     return $section_inputs;
                   1814: }
                   1815: 
1.44      ng       1816: # --------------------------- show submissions of a student, option to grade 
                   1817: sub submission {
                   1818:     my ($request,$counter,$total) = @_;
1.257     albertel 1819:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1820:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1821:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1822:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1823:     my $symb = &get_symb($request); 
                   1824:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1825: 
                   1826:     if (!&canview($usec)) {
1.398     albertel 1827: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1828: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1829: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1830: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1831: 	return;
                   1832:     }
                   1833: 
1.257     albertel 1834:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1835:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1836:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1837:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1838:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1839: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1840: 	'/check.gif" height="16" border="0" />';
1.41      ng       1841: 
1.426     albertel 1842:     my %old_essays;
1.41      ng       1843:     # header info
                   1844:     if ($counter == 0) {
                   1845: 	&sub_page_js($request);
1.257     albertel 1846: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1847: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1848: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1849: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1850: 	    &download_all_link($request, $symb);
                   1851: 	}
1.398     albertel 1852: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1853: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1854: 
1.257     albertel 1855: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1856: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1857: 		$checkIcon.' symbol.'."\n";
                   1858: 	    $request->print($checkMark);
                   1859: 	}
1.41      ng       1860: 
1.44      ng       1861: 	# option to display problem, only once else it cause problems 
                   1862:         # with the form later since the problem has a form.
1.257     albertel 1863: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1864: 	    my $mode;
1.257     albertel 1865: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1866: 		$mode='both';
1.257     albertel 1867: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1868: 		$mode='text';
1.257     albertel 1869: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1870: 		$mode='answer';
                   1871: 	    }
1.329     albertel 1872: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1873: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1874: 	}
1.441     www      1875: 
1.44      ng       1876: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1877:         # if this subroutine has been called once.
1.41      ng       1878: 	my %keyhash = ();
1.257     albertel 1879: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1880: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1881: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1882: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1883: 
1.257     albertel 1884: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1885: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1886: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1887: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1888: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1889: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1890: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1891: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1892: 	}
1.257     albertel 1893: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1894: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1895: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1896: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1897: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1898: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1899: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1900: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1901: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1902: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1903: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1904: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1905: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1906: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1907: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1908: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1909: 			&build_section_inputs().
1.326     albertel 1910: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1911: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1912: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1913: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1914: 	if ($env{'form.handgrade'} eq 'yes') {
                   1915: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1916: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1917: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1918: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1919: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1920: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1921: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1922: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1923: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1924: 	    }
1.123     ng       1925: 	}
1.41      ng       1926: 	
                   1927: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1928: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1929: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1930: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1931: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1932: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1933: 		'" />'."\n".
                   1934: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1935: 	    $cts++;
                   1936: 	}
                   1937: 	$request->print($prnmsg);
1.32      ng       1938: 
1.257     albertel 1939: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1940: #
                   1941: # Print out the keyword options line
                   1942: #
1.41      ng       1943: 	    $request->print(<<KEYWORDS);
1.38      ng       1944: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1945: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1946: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1947:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1948: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1949: KEYWORDS
1.88      www      1950: #
                   1951: # Load the other essays for similarity check
                   1952: #
1.324     albertel 1953:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1954: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1955: 	    $apath=&escape($apath);
1.88      www      1956: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1957: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1958:         }
                   1959:     }
1.44      ng       1960: 
1.441     www      1961: # This is where output for one specific student would start
                   1962:     my $bgcolor='#DDEEDD';
                   1963:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1964:     $request->print("\n\n".
                   1965:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1966: 
1.257     albertel 1967:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1968: 	my $mode;
1.257     albertel 1969: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1970: 	    $mode='both';
1.257     albertel 1971: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1972: 	    $mode='text';
1.257     albertel 1973: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1974: 	    $mode='answer';
                   1975: 	}
1.329     albertel 1976: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1977: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1978:     }
1.144     albertel 1979: 
1.257     albertel 1980:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1981:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1982: 
1.44      ng       1983:     # Display student info
1.41      ng       1984:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1985:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1986: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1987: 
1.257     albertel 1988:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1989:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1990: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1991: 
1.118     ng       1992:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1993:     my @col_fullnames;
1.56      matthew  1994:     my ($classlist,$fullname);
1.257     albertel 1995:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1996: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1997: 	for (keys (%$handgrade)) {
1.44      ng       1998: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1999: 					    '.maxcollaborators',
                   2000:                                             $symb,$udom,$uname);
                   2001: 	    next if ($ncol <= 0);
                   2002:             s/\_/\./g;
                   2003:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       2004:             my @goodcollaborators = ();
                   2005:             my @badcollaborators  = ();
                   2006: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   2007: 		$_ =~ s/[\$\^\(\)]//g;
                   2008: 		next if ($_ eq '');
1.80      ng       2009: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       2010: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       2011: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       2012: 		# Doing this grep allows 'fuzzy' specification
                   2013: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   2014: 		if (! scalar(@Matches)) {
                   2015: 		    push @badcollaborators,$_;
                   2016: 		} else {
                   2017: 		    push @goodcollaborators, @Matches;
                   2018: 		}
1.80      ng       2019: 	    }
1.86      ng       2020:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  2021:                 $result.='<b>Collaborators: </b>';
1.86      ng       2022:                 foreach (@goodcollaborators) {
                   2023: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   2024: 		    push @col_fullnames, $givenn.' '.$lastname;
                   2025: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   2026: 		}
1.57      matthew  2027:                 $result.='<br />'."\n";
1.150     albertel 2028: 		my ($part)=split(/\./,$_);
1.86      ng       2029: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 2030: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2031: 		    "\n";
1.86      ng       2032: 	    }
                   2033: 	    if (scalar(@badcollaborators) > 0) {
                   2034: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2035: 		$result.='This student has submitted ';
                   2036: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2037: 		$result .= ': '.join(', ',@badcollaborators);
                   2038: 		$result .= '</td></tr></table>';
                   2039: 	    }         
                   2040: 	    if (scalar(@badcollaborators > $ncol)) {
                   2041: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2042: 		$result .= 'This student has submitted too many '.
                   2043: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2044: 		$result .= '</td></tr></table>';
                   2045: 	    }
1.41      ng       2046: 	}
                   2047:     }
1.44      ng       2048:     $request->print($result."\n");
1.33      ng       2049: 
1.44      ng       2050:     # print student answer/submission
                   2051:     # Options are (1) Handgaded submission only
                   2052:     #             (2) Last submission, includes submission that is not handgraded 
                   2053:     #                  (for multi-response type part)
                   2054:     #             (3) Last submission plus the parts info
                   2055:     #             (4) The whole record for this student
1.257     albertel 2056:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2057: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2058: 	my $lastsubonly=''.
                   2059: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2060: 	     $$timestamp)."</td></tr>\n";
                   2061: 	if ($$timestamp eq '') {
                   2062: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2063: 	} else {
                   2064: 	    my %seenparts;
1.375     albertel 2065: 	    my @part_response_id = &flatten_responseType($responseType);
                   2066: 	    foreach my $part (@part_response_id) {
1.393     albertel 2067: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2068: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2069: 
1.375     albertel 2070: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2071: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2072: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2073: 		    if (exists($seenparts{$partid})) { next; }
                   2074: 		    $seenparts{$partid}=1;
1.207     albertel 2075: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2076: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2077: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2078: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2079: 			'\');" target="_self">'.
1.257     albertel 2080: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2081: 		    $request->print($submitby);
                   2082: 		    next;
                   2083: 		}
                   2084: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2085: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2086: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2087: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2088: 			' )</span>&nbsp; &nbsp;'.
                   2089: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2090: 		    next;
                   2091: 		}
                   2092: 		foreach (@$string) {
                   2093: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2094: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2095: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2096: 		    # Similarity check
                   2097: 		    my $similar='';
1.257     albertel 2098: 		    if($env{'form.checkPlag'}){
1.151     albertel 2099: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2100: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2101: 			if ($osim) {
                   2102: 			    $osim=int($osim*100.0);
1.426     albertel 2103: 			    my %old_course_desc = 
                   2104: 				&Apache::lonnet::coursedescription($ocrsid,
                   2105: 								   {'one_time' => 1});
                   2106: 
                   2107: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2108: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2109: 				    $osim,
                   2110: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2111: 				    $oname,$odom,
1.426     albertel 2112: 				    $old_course_desc{'description'},
1.427     albertel 2113: 				    $old_course_desc{'num'},
1.426     albertel 2114: 				    $old_course_desc{'domain'}).
1.398     albertel 2115: 				'</span></h3><blockquote><i>'.
1.151     albertel 2116: 				&keywords_highlight($oessay).
                   2117: 				'</i></blockquote><hr />';
                   2118: 			}
1.150     albertel 2119: 		    }
1.151     albertel 2120: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2121: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2122: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2123: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2124: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2125: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2126: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2127: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2128: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2129: 			if (@$files) {
1.398     albertel 2130: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2131: 			    my $file_counter = 0;
1.313     banghart 2132: 			    foreach my $file (@$files) {
1.303     banghart 2133: 			        $file_counter ++;
1.232     albertel 2134: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2135: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2136: 			    }
1.236     albertel 2137: 			    $lastsubonly.='<br />';
1.41      ng       2138: 			}
1.151     albertel 2139: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2140: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2141: 					 $respid,\%record,$order);
                   2142: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2143: 		    }
                   2144: 		}
                   2145: 	    }
1.151     albertel 2146: 	}
                   2147: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2148: 	$request->print($lastsubonly);
1.257     albertel 2149:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2150: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2151: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2152:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2153: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2154: 								 $env{'request.course.id'},
1.44      ng       2155: 								 $last,'.submission',
                   2156: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2157:     }
1.120     ng       2158: 
1.121     ng       2159:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2160: 	.$udom.'" />'."\n");
1.41      ng       2161:     
1.44      ng       2162:     # return if view submission with no grading option
1.257     albertel 2163:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2164: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2165: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2166: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2167: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2168: 	if (($env{'form.command'} eq 'submission') || 
                   2169: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2170: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2171: 	}
1.180     albertel 2172: 	$request->print($toGrade);
1.41      ng       2173: 	return;
1.180     albertel 2174:     } else {
                   2175: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2176:     }
1.33      ng       2177: 
1.121     ng       2178:     # essay grading message center
1.257     albertel 2179:     if ($env{'form.handgrade'} eq 'yes') {
                   2180: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2181: 	my $msgfor = $givenn.' '.$lastname;
                   2182: 	if (scalar(@col_fullnames) > 0) {
                   2183: 	    my $lastone = pop @col_fullnames;
                   2184: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2185: 	}
                   2186: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2187: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2188: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2189: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2190: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2191: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2192: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2193: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2194: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2195: 	    '<br />&nbsp;('.
                   2196: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2197: 	$request->print($result);
1.118     ng       2198:     }
1.300     albertel 2199:     if ($perm{'vgr'}) {
1.297     www      2200: 	$request->print('<br />'.
1.300     albertel 2201: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2202: 						   $uname,$udom,'check'));
1.297     www      2203:     }
1.300     albertel 2204:     if ($perm{'opa'}) {
1.297     www      2205: 	$request->print('<br />'.
1.300     albertel 2206: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2207: 					 $uname,$udom,$symb,'check'));
1.297     www      2208:     }
1.41      ng       2209: 
                   2210:     my %seen = ();
                   2211:     my @partlist;
1.129     ng       2212:     my @gradePartRespid;
1.375     albertel 2213:     my @part_response_id = &flatten_responseType($responseType);
                   2214:     foreach my $part_response_id (@part_response_id) {
                   2215:     	my ($partid,$respid) = @{ $part_response_id };
                   2216: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2217: 	next if ($seen{$partid} > 0);
1.41      ng       2218: 	$seen{$partid}++;
1.393     albertel 2219: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2220: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2221: 	push @partlist,$partid;
1.129     ng       2222: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2223: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2224:     }
1.45      ng       2225:     $result='<input type="hidden" name="partlist'.$counter.
                   2226: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2227:     $result.='<input type="hidden" name="gradePartRespid'.
                   2228: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2229:     my $ctr = 0;
                   2230:     while ($ctr < scalar(@partlist)) {
                   2231: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2232: 	    $partlist[$ctr].'" />'."\n";
                   2233: 	$ctr++;
                   2234:     }
                   2235:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2236: 
1.441     www      2237: # Done with printing info for one student
                   2238: 
                   2239:     $request->print('</td></tr></table></p>');
                   2240: 
                   2241: 
1.41      ng       2242:     # print end of form
                   2243:     if ($counter == $total) {
1.297     www      2244: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2245: 	$endform.='<input type="button" value="Save & Next" '.
                   2246: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2247: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2248: 	my $ntstu ='<select name="NTSTU">'.
                   2249: 	    '<option>1</option><option>2</option>'.
                   2250: 	    '<option>3</option><option>5</option>'.
                   2251: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2252: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2253: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2254: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2255: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2256: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2257: 	    '<input type="button" value="Next" '.
1.417     albertel 2258: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2259: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2260:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2261:             "' name='increment' />";
1.45      ng       2262: 	$endform.='</td><tr></table></form>';
1.324     albertel 2263: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2264: 	$request->print($endform);
                   2265:     }
                   2266:     return '';
1.38      ng       2267: }
                   2268: 
1.44      ng       2269: #--- Retrieve the last submission for all the parts
1.38      ng       2270: sub get_last_submission {
1.119     ng       2271:     my ($returnhash)=@_;
1.46      ng       2272:     my (@string,$timestamp);
1.119     ng       2273:     if ($$returnhash{'version'}) {
1.46      ng       2274: 	my %lasthash=();
                   2275: 	my ($version);
1.119     ng       2276: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2277: 	    foreach my $key (sort(split(/\:/,
                   2278: 					$$returnhash{$version.':keys'}))) {
                   2279: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2280: 		$timestamp = 
                   2281: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2282: 	    }
                   2283: 	}
1.397     albertel 2284: 	foreach my $key (keys(%lasthash)) {
                   2285: 	    next if ($key !~ /\.submission$/);
                   2286: 
                   2287: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2288: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2289: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2290: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2291: 	}
                   2292:     }
1.397     albertel 2293:     if (!@string) {
                   2294: 	$string[0] =
1.398     albertel 2295: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2296:     }
                   2297:     return (\@string,\$timestamp);
1.38      ng       2298: }
1.35      ng       2299: 
1.44      ng       2300: #--- High light keywords, with style choosen by user.
1.38      ng       2301: sub keywords_highlight {
1.44      ng       2302:     my $string    = shift;
1.257     albertel 2303:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2304:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2305:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2306:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2307:     foreach my $keyword (@keylist) {
                   2308: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2309:     }
                   2310:     return $string;
1.38      ng       2311: }
1.36      ng       2312: 
1.44      ng       2313: #--- Called from submission routine
1.38      ng       2314: sub processHandGrade {
1.41      ng       2315:     my ($request) = shift;
1.324     albertel 2316:     my $symb   = &get_symb($request);
                   2317:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2318:     my $button = $env{'form.gradeOpt'};
                   2319:     my $ngrade = $env{'form.NCT'};
                   2320:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2321:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2322:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2323: 
1.44      ng       2324:     if ($button eq 'Save & Next') {
                   2325: 	my $ctr = 0;
                   2326: 	while ($ctr < $ngrade) {
1.257     albertel 2327: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2328: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2329: 	    if ($errorflag eq 'no_score') {
                   2330: 		$ctr++;
                   2331: 		next;
                   2332: 	    }
1.104     albertel 2333: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2334: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2335: 		$ctr++;
                   2336: 		next;
                   2337: 	    }
1.257     albertel 2338: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2339: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2340: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2341:             my ($feedurl,$showsymb) =
                   2342: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2343: 	    my $messagetail;
1.62      albertel 2344: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2345: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2346: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2347: 		$subject.=' ['.$restitle.']';
1.44      ng       2348: 		my (@msgnum) = split(/,/,$includemsg);
                   2349: 		foreach (@msgnum) {
1.257     albertel 2350: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2351: 		}
1.80      ng       2352: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2353: 		if ($env{'form.withgrades'.$ctr}) {
                   2354: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2355: 		    $messagetail = " for <a href=\"".
1.418     albertel 2356: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2357: 		}
                   2358: 		$msgstatus = 
                   2359:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2360: 						     $message.$messagetail,
1.418     albertel 2361:                                                      undef,$feedurl,undef,
1.386     raeburn  2362:                                                      undef,undef,$showsymb,
                   2363:                                                      $restitle);
                   2364: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2365: 				$msgstatus);
1.44      ng       2366: 	    }
1.257     albertel 2367: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2368: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2369: 		foreach my $collabstr (@collabstrs) {
                   2370: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2371: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2372: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2373: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2374: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2375: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2376: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2377: 			    next;
1.418     albertel 2378: 			} elsif ($message ne '') {
                   2379: 			    my ($baseurl,$showsymb) = 
                   2380: 				&get_feedurl_and_symb($symb,$collaborator,
                   2381: 						      $udom);
                   2382: 			    if ($env{'form.withgrades'.$ctr}) {
                   2383: 				$messagetail = " for <a href=\"".
1.386     raeburn  2384:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2385: 			    }
1.418     albertel 2386: 			    $msgstatus = 
                   2387: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2388: 			}
1.44      ng       2389: 		    }
                   2390: 		}
                   2391: 	    }
                   2392: 	    $ctr++;
                   2393: 	}
                   2394:     }
                   2395: 
1.257     albertel 2396:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2397: 	# Keywords sorted in alphabatical order
1.257     albertel 2398: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2399: 	my %keyhash = ();
1.257     albertel 2400: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2401: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2402: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2403: 	$env{'form.keywords'} = join(' ',@keywords);
                   2404: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2405: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2406: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2407: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2408: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2409: 
                   2410: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2411: 	# New messages are saved in env for the next student.
1.119     ng       2412: 	# All messages are saved in nohist_handgrade.db
                   2413: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2414: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2415: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2416: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2417: 		$idx++;
                   2418: 	    }
                   2419: 	    $ctr++;
1.41      ng       2420: 	}
1.119     ng       2421: 	$ctr = 0;
                   2422: 	while ($ctr < $ngrade) {
1.257     albertel 2423: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2424: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2425: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2426: 		$idx++;
                   2427: 	    }
                   2428: 	    $ctr++;
1.41      ng       2429: 	}
1.257     albertel 2430: 	$env{'form.savemsgN'} = --$idx;
                   2431: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2432: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2433: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2434:     }
1.44      ng       2435:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2436:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2437:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2438: 	my ($ctr,$total) = (0,0);
                   2439: 	while ($ctr < $ngrade) {
1.257     albertel 2440: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2441: 	    $ctr++;
                   2442: 	}
1.257     albertel 2443: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2444: 	$ctr = 0;
                   2445: 	while ($ctr < $total) {
1.257     albertel 2446: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2447: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2448: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2449: 	    &submission($request,$ctr,$total-1);
1.41      ng       2450: 	    $ctr++;
                   2451: 	}
                   2452: 	return '';
                   2453:     }
1.36      ng       2454: 
1.121     ng       2455: # Go directly to grade student - from submission or link from chart page
1.120     ng       2456:     if ($button eq 'Grade Student') {
1.324     albertel 2457: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2458: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2459: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2460: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2461: 	&submission($request,0,0);
                   2462: 	return '';
                   2463:     }
                   2464: 
1.44      ng       2465:     # Get the next/previous one or group of students
1.257     albertel 2466:     my $firststu = $env{'form.unamedom0'};
                   2467:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2468:     my $ctr = 2;
1.41      ng       2469:     while ($laststu eq '') {
1.257     albertel 2470: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2471: 	$ctr++;
                   2472: 	$laststu = $firststu if ($ctr > $ngrade);
                   2473:     }
1.44      ng       2474: 
1.41      ng       2475:     my (@parsedlist,@nextlist);
                   2476:     my ($nextflg) = 0;
1.294     albertel 2477:     foreach (sort 
                   2478: 	     {
                   2479: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2480: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2481: 		 }
                   2482: 		 return $a cmp $b;
                   2483: 	     } (keys(%$fullname))) {
1.41      ng       2484: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2485: 	    push @parsedlist,$_;
                   2486: 	}
                   2487: 	$nextflg = 1 if ($_ eq $laststu);
                   2488: 	if ($button eq 'Previous') {
                   2489: 	    last if ($_ eq $firststu);
                   2490: 	    push @parsedlist,$_;
                   2491: 	}
                   2492:     }
                   2493:     $ctr = 0;
                   2494:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2495:     my ($partlist) = &response_type($symb);
1.41      ng       2496:     foreach my $student (@parsedlist) {
1.257     albertel 2497: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2498: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2499: 	
                   2500: 	if ($submitonly eq 'queued') {
                   2501: 	    my %queue_status = 
                   2502: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2503: 							$udom,$uname);
                   2504: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2505: 	}
                   2506: 
1.156     albertel 2507: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2508: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2509: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2510: 	    my $submitted = 0;
1.248     albertel 2511: 	    my $ungraded = 0;
                   2512: 	    my $incorrect = 0;
1.145     albertel 2513: 	    foreach (keys(%status)) {
                   2514: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2515: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2516: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2517: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2518: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2519: 		    $submitted = 0;
                   2520: 		}
1.41      ng       2521: 	    }
1.156     albertel 2522: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2523: 				     $submitonly eq 'incorrect' ||
                   2524: 				     $submitonly eq 'graded'));
1.248     albertel 2525: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2526: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2527: 	}
                   2528: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2529: 	last if ($ctr == $ntstu);
1.41      ng       2530: 	$ctr++;
                   2531:     }
1.36      ng       2532: 
1.41      ng       2533:     $ctr = 0;
                   2534:     my $total = scalar(@nextlist)-1;
1.39      ng       2535: 
1.41      ng       2536:     foreach (sort @nextlist) {
                   2537: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2538: 	$env{'form.student'}  = $uname;
                   2539: 	$env{'form.userdom'}  = $udom;
                   2540: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2541: 	&submission($request,$ctr,$total);
                   2542: 	$ctr++;
                   2543:     }
                   2544:     if ($total < 0) {
1.398     albertel 2545: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2546: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2547: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2548: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2549: 	$request->print($the_end);
                   2550:     }
                   2551:     return '';
1.38      ng       2552: }
1.36      ng       2553: 
1.44      ng       2554: #---- Save the score and award for each student, if changed
1.38      ng       2555: sub saveHandGrade {
1.324     albertel 2556:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2557:     my @version_parts;
1.104     albertel 2558:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2559: 					   $env{'request.course.id'});
1.104     albertel 2560:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2561:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2562:     my @parts_graded;
1.77      ng       2563:     my %newrecord  = ();
                   2564:     my ($pts,$wgt) = ('','');
1.269     raeburn  2565:     my %aggregate = ();
                   2566:     my $aggregateflag = 0;
1.301     albertel 2567:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2568:     foreach my $new_part (@parts) {
1.337     banghart 2569: 	#collaborator ($submi may vary for different parts
1.259     banghart 2570: 	if ($submitter && $new_part ne $part) { next; }
                   2571: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2572: 	if ($dropMenu eq 'excused') {
1.259     banghart 2573: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2574: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2575: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2576: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2577: 		}
1.364     banghart 2578: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2579: 	    }
1.125     ng       2580: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2581: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2582: 	    foreach my $key (keys (%record)) {
1.259     banghart 2583: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2584: 	    }
1.259     banghart 2585: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2586: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2587:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2588: 
                   2589:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2590: 					       [$new_part]);
                   2591:             my $aggtries =$totaltries;
1.269     raeburn  2592:             if ($last_resets{$new_part}) {
1.270     albertel 2593:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2594: 					   $new_part);
1.269     raeburn  2595:             }
1.270     albertel 2596: 
                   2597:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2598:             if ($aggtries > 0) {
1.327     albertel 2599:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2600:                 $aggregateflag = 1;
                   2601:             }
1.125     ng       2602: 	} elsif ($dropMenu eq '') {
1.259     banghart 2603: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2604: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2605: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2606: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2607: 		next;
                   2608: 	    }
1.259     banghart 2609: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2610: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2611: 	    my $partial= $pts/$wgt;
1.259     banghart 2612: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2613: 		#do not update score for part if not changed.
1.346     banghart 2614:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2615: 		next;
1.251     banghart 2616: 	    } else {
1.259     banghart 2617: 	        push @parts_graded, $new_part;
1.153     albertel 2618: 	    }
1.259     banghart 2619: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2620: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2621: 	    }
1.259     banghart 2622: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2623: 	    if ($partial == 0) {
1.153     albertel 2624: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2625: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2626: 		}
1.41      ng       2627: 	    } else {
1.153     albertel 2628: 		if ($record{$reckey} ne 'correct_by_override') {
                   2629: 		    $newrecord{$reckey} = 'correct_by_override';
                   2630: 		}
                   2631: 	    }	    
                   2632: 	    if ($submitter && 
1.259     banghart 2633: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2634: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2635: 	    }
1.259     banghart 2636: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2637: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2638: 	}
1.259     banghart 2639: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2640: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2641: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2642: 	        $dropMenu eq 'reset status')
                   2643: 	   {
1.342     banghart 2644: 	    push (@version_parts,$new_part);
1.259     banghart 2645: 	}
1.41      ng       2646:     }
1.301     albertel 2647:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2648:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2649: 
1.344     albertel 2650:     if (%newrecord) {
                   2651:         if (@version_parts) {
1.364     banghart 2652:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2653:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2654: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2655: 	    foreach my $new_part (@version_parts) {
                   2656: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2657: 				$new_part,\%newrecord);
                   2658: 	    }
1.259     banghart 2659:         }
1.44      ng       2660: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2661: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2662: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2663: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2664:     }
1.269     raeburn  2665:     if ($aggregateflag) {
                   2666:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2667: 			      $cdom,$cnum);
1.269     raeburn  2668:     }
1.301     albertel 2669:     return ('',$pts,$wgt);
1.36      ng       2670: }
1.322     albertel 2671: 
1.380     albertel 2672: sub check_and_remove_from_queue {
                   2673:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2674:     my @ungraded_parts;
                   2675:     foreach my $part (@{$parts}) {
                   2676: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2677: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2678: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2679: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2680: 		) {
                   2681: 	    push(@ungraded_parts, $part);
                   2682: 	}
                   2683:     }
                   2684:     if ( !@ungraded_parts ) {
                   2685: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2686: 					       $cnum,$domain,$stuname);
                   2687:     }
                   2688: }
                   2689: 
1.337     banghart 2690: sub handback_files {
                   2691:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2692:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2693:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2694: 
                   2695:     my @part_response_id = &flatten_responseType($responseType);
                   2696:     foreach my $part_response_id (@part_response_id) {
                   2697:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2698: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2699:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2700:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2701:                 my $file_counter = 1;
1.367     albertel 2702: 		my $file_msg;
1.337     banghart 2703:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2704:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2705:                     my ($directory,$answer_file) = 
                   2706:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2707:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2708: 		        &file_name_version_ext($answer_file);
1.355     banghart 2709: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2710: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2711: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2712:                     # fix file name
                   2713:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2714:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2715:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2716:             	                                $save_file_name);
1.337     banghart 2717:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2718:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2719:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2720:                     } else {
1.360     banghart 2721:                         # mark the file as read only
                   2722:                         my @files = ($save_file_name);
1.372     albertel 2723:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2724:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2725: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2726: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2727: 			}
                   2728:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2729: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2730: 
1.337     banghart 2731:                     }
                   2732:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2733:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2734:                     $file_counter++;
                   2735:                 }
1.367     albertel 2736: 		my $subject = "File Handed Back by Instructor ";
                   2737: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2738: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2739: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2740: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2741: 		my ($feedurl,$showsymb) = 
                   2742: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2743:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2744: 		my $msgstatus = 
                   2745:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2746: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2747:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2748:             }
                   2749:         }
1.338     banghart 2750:     return;
1.337     banghart 2751: }
                   2752: 
1.418     albertel 2753: sub get_feedurl_and_symb {
                   2754:     my ($symb,$uname,$udom) = @_;
                   2755:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2756:     $url = &Apache::lonnet::clutter($url);
                   2757:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2758: 					$symb,$udom,$uname);
                   2759:     if ($encrypturl =~ /^yes$/i) {
                   2760: 	&Apache::lonenc::encrypted(\$url,1);
                   2761: 	&Apache::lonenc::encrypted(\$symb,1);
                   2762:     }
                   2763:     return ($url,$symb);
                   2764: }
                   2765: 
1.313     banghart 2766: sub get_submitted_files {
                   2767:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2768:     my @files;
                   2769:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2770:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2771:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2772:     	    push(@files,$file_url.$file);
                   2773:         }
                   2774:     }
                   2775:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2776:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2777:     }
                   2778:     return (\@files);
                   2779: }
1.322     albertel 2780: 
1.269     raeburn  2781: # ----------- Provides number of tries since last reset.
                   2782: sub get_num_tries {
                   2783:     my ($record,$last_reset,$part) = @_;
                   2784:     my $timestamp = '';
                   2785:     my $num_tries = 0;
                   2786:     if ($$record{'version'}) {
                   2787:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2788:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2789:                 $timestamp = $$record{$version.':timestamp'};
                   2790:                 if ($timestamp > $last_reset) {
                   2791:                     $num_tries ++;
                   2792:                 } else {
                   2793:                     last;
                   2794:                 }
                   2795:             }
                   2796:         }
                   2797:     }
                   2798:     return $num_tries;
                   2799: }
                   2800: 
                   2801: # ----------- Determine decrements required in aggregate totals 
                   2802: sub decrement_aggs {
                   2803:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2804:     my %decrement = (
                   2805:                         attempts => 0,
                   2806:                         users => 0,
                   2807:                         correct => 0
                   2808:                     );
                   2809:     $decrement{'attempts'} = $aggtries;
                   2810:     if ($solvedstatus =~ /^correct/) {
                   2811:         $decrement{'correct'} = 1;
                   2812:     }
                   2813:     if ($aggtries == $totaltries) {
                   2814:         $decrement{'users'} = 1;
                   2815:     }
                   2816:     foreach my $type (keys (%decrement)) {
                   2817:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2818:     }
                   2819:     return;
                   2820: }
                   2821: 
                   2822: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2823: sub get_last_resets {
1.270     albertel 2824:     my ($symb,$courseid,$partids) =@_;
                   2825:     my %last_resets;
1.269     raeburn  2826:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2827:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2828:     my @keys;
                   2829:     foreach my $part (@{$partids}) {
                   2830: 	push(@keys,"$symb\0$part\0resettime");
                   2831:     }
                   2832:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2833: 				     $cdom,$cname);
                   2834:     foreach my $part (@{$partids}) {
                   2835: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2836:     }
1.270     albertel 2837:     return %last_resets;
1.269     raeburn  2838: }
                   2839: 
1.251     banghart 2840: # ----------- Handles creating versions for portfolio files as answers
                   2841: sub version_portfiles {
1.343     banghart 2842:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2843:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2844:     my @returned_keys;
1.255     banghart 2845:     my $parts = join('|', @$parts_graded);
1.359     www      2846:     my $portfolio_root = &propath($domain,$stu_name).
                   2847: 	'/userfiles/portfolio';
1.277     albertel 2848:     foreach my $key (keys(%$record)) {
1.259     banghart 2849:         my $new_portfiles;
1.263     banghart 2850:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2851:             my @versioned_portfiles;
1.367     albertel 2852:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2853:             foreach my $file (@portfiles) {
1.306     banghart 2854:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2855:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2856: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2857: 		    &file_name_version_ext($answer_file);
1.306     banghart 2858:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2859:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2860:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2861:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2862:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2863:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2864:                         [$directory.$new_answer],
1.306     banghart 2865:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2866:                 }
1.252     banghart 2867:             }
1.343     banghart 2868:             $$record{$key} = join(',',@versioned_portfiles);
                   2869:             push(@returned_keys,$key);
1.251     banghart 2870:         }
                   2871:     } 
1.343     banghart 2872:     return (@returned_keys);   
1.305     banghart 2873: }
                   2874: 
1.307     banghart 2875: sub get_next_version {
1.341     banghart 2876:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2877:     my $version;
                   2878:     foreach my $row (@$dir_list) {
                   2879:         my ($file) = split(/\&/,$row,2);
                   2880:         my ($file_name,$file_version,$file_ext) =
                   2881: 	    &file_name_version_ext($file);
                   2882:         if (($file_name eq $answer_name) && 
                   2883: 	    ($file_ext eq $answer_ext)) {
                   2884:                 # gets here if filename and extension match, regardless of version
                   2885:                 if ($file_version ne '') {
                   2886:                 # a versioned file is found  so save it for later
                   2887:                 if ($file_version > $version) {
                   2888: 		    $version = $file_version;
                   2889: 	        }
                   2890:             }
                   2891:         }
                   2892:     } 
                   2893:     $version ++;
                   2894:     return($version);
                   2895: }
                   2896: 
1.305     banghart 2897: sub version_selected_portfile {
1.306     banghart 2898:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2899:     my ($answer_name,$answer_ver,$answer_ext) =
                   2900:         &file_name_version_ext($file_name);
                   2901:     my $new_answer;
                   2902:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2903:     if($env{'form.copy'} eq '-1') {
                   2904:         $new_answer = 'problem getting file';
                   2905:     } else {
                   2906:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2907:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2908:                             $stu_name,$domain,'copy',
                   2909: 		        '/portfolio'.$directory.$new_answer);
                   2910:     }    
                   2911:     return ($new_answer);
1.251     banghart 2912: }
                   2913: 
1.304     albertel 2914: sub file_name_version_ext {
                   2915:     my ($file)=@_;
                   2916:     my @file_parts = split(/\./, $file);
                   2917:     my ($name,$version,$ext);
                   2918:     if (@file_parts > 1) {
                   2919: 	$ext=pop(@file_parts);
                   2920: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2921: 	    $version=pop(@file_parts);
                   2922: 	}
                   2923: 	$name=join('.',@file_parts);
                   2924:     } else {
                   2925: 	$name=join('.',@file_parts);
                   2926:     }
                   2927:     return($name,$version,$ext);
                   2928: }
                   2929: 
1.44      ng       2930: #--------------------------------------------------------------------------------------
                   2931: #
                   2932: #-------------------------- Next few routines handles grading by section or whole class
                   2933: #
                   2934: #--- Javascript to handle grading by section or whole class
1.42      ng       2935: sub viewgrades_js {
                   2936:     my ($request) = shift;
                   2937: 
1.41      ng       2938:     $request->print(<<VIEWJAVASCRIPT);
                   2939: <script type="text/javascript" language="javascript">
1.45      ng       2940:    function writePoint(partid,weight,point) {
1.125     ng       2941: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2942: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2943: 	if (point == "textval") {
1.125     ng       2944: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2945: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2946: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2947: 		var resetbox = false;
                   2948: 		for (var i=0; i<radioButton.length; i++) {
                   2949: 		    if (radioButton[i].checked) {
                   2950: 			textbox.value = i;
                   2951: 			resetbox = true;
                   2952: 		    }
                   2953: 		}
                   2954: 		if (!resetbox) {
                   2955: 		    textbox.value = "";
                   2956: 		}
                   2957: 		return;
                   2958: 	    }
1.109     matthew  2959: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2960: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2961: 				   ") greater than the weight for the part. Accept?");
                   2962: 		if (resp == false) {
                   2963: 		    textbox.value = "";
                   2964: 		    return;
                   2965: 		}
                   2966: 	    }
1.42      ng       2967: 	    for (var i=0; i<radioButton.length; i++) {
                   2968: 		radioButton[i].checked=false;
1.109     matthew  2969: 		if (parseFloat(point) == i) {
1.42      ng       2970: 		    radioButton[i].checked=true;
                   2971: 		}
                   2972: 	    }
1.41      ng       2973: 
1.42      ng       2974: 	} else {
1.125     ng       2975: 	    textbox.value = parseFloat(point);
1.42      ng       2976: 	}
1.41      ng       2977: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2978: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2979: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2980: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2981: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2982: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2983: 	    if (saveval != "correct") {
                   2984: 		scorename.value = point;
1.43      ng       2985: 		if (selname[0].selected != true) {
                   2986: 		    selname[0].selected = true;
                   2987: 		}
1.42      ng       2988: 	    }
                   2989: 	}
1.125     ng       2990: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2991:     }
                   2992: 
                   2993:     function writeRadText(partid,weight) {
1.125     ng       2994: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2995: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2996:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2997: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2998: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2999: 	    for (var i=0; i<radioButton.length; i++) {
                   3000: 		radioButton[i].checked=false;
                   3001: 
                   3002: 	    }
                   3003: 	    textbox.value = "";
                   3004: 
                   3005: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3006: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3007: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3008: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3009: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3010: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3011: 		if ((saveval != "correct") || override) {
1.42      ng       3012: 		    scorename.value = "";
1.125     ng       3013: 		    if (selval[1].selected) {
                   3014: 			selname[1].selected = true;
                   3015: 		    } else {
                   3016: 			selname[2].selected = true;
                   3017: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3018: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3019: 		    }
1.42      ng       3020: 		}
                   3021: 	    }
1.43      ng       3022: 	} else {
                   3023: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3024: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3025: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3026: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3027: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3028: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3029: 		if ((saveval != "correct") || override) {
1.125     ng       3030: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3031: 		    selname[0].selected = true;
                   3032: 		}
                   3033: 	    }
                   3034: 	}	    
1.42      ng       3035:     }
                   3036: 
                   3037:     function changeSelect(partid,user) {
1.125     ng       3038: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3039: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3040: 	var point  = textbox.value;
1.125     ng       3041: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3042: 
1.109     matthew  3043: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3044: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3045: 	    textbox.value = "";
                   3046: 	    return;
                   3047: 	}
1.109     matthew  3048: 	if (parseFloat(point) > parseFloat(weight)) {
                   3049: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3050: 			       ") greater than the weight of the part. Accept?");
                   3051: 	    if (resp == false) {
                   3052: 		textbox.value = "";
                   3053: 		return;
                   3054: 	    }
                   3055: 	}
1.42      ng       3056: 	selval[0].selected = true;
                   3057:     }
                   3058: 
                   3059:     function changeOneScore(partid,user) {
1.125     ng       3060: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3061: 	if (selval[1].selected || selval[2].selected) {
                   3062: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3063: 	    if (selval[2].selected) {
                   3064: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3065: 	    }
1.269     raeburn  3066:         }
1.42      ng       3067:     }
                   3068: 
                   3069:     function resetEntry(numpart) {
                   3070: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3071: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3072: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3073: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3074: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3075: 	    for (var i=0; i<radioButton.length; i++) {
                   3076: 		radioButton[i].checked=false;
                   3077: 
                   3078: 	    }
                   3079: 	    textbox.value = "";
                   3080: 	    selval[0].selected = true;
                   3081: 
                   3082: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3083: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3084: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3085: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3086: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3087: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3088: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3089: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3090: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3091: 		if (saveselval == "excused") {
1.43      ng       3092: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3093: 		} else {
1.43      ng       3094: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3095: 		}
                   3096: 	    }
1.41      ng       3097: 	}
1.42      ng       3098:     }
                   3099: 
1.41      ng       3100: </script>
                   3101: VIEWJAVASCRIPT
1.42      ng       3102: }
                   3103: 
1.44      ng       3104: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3105: sub viewgrades {
                   3106:     my ($request) = shift;
                   3107:     &viewgrades_js($request);
1.41      ng       3108: 
1.324     albertel 3109:     my ($symb) = &get_symb($request);
1.168     albertel 3110:     #need to make sure we have the correct data for later EXT calls, 
                   3111:     #thus invalidate the cache
                   3112:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3113:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3114:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3115:     &Apache::lonnet::clear_EXT_cache_status();
                   3116: 
1.398     albertel 3117:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3118:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3119: 
                   3120:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3121:     $result.=&jscriptNform($symb);
1.41      ng       3122: 
1.44      ng       3123:     #beginning of class grading form
1.442     banghart 3124:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3125:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3126: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3127: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3128: 	&build_section_inputs().
1.257     albertel 3129: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3130: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3131: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3132: 
1.126     ng       3133:     my $sectionClass;
1.430     banghart 3134:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3135:     if ($env{'form.section'} eq 'all') {
1.126     ng       3136: 	$sectionClass='Class </h3>';
1.257     albertel 3137:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3138: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3139:     } else {
1.431     banghart 3140: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3141:     }
1.431     banghart 3142:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3143:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3144: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3145:     #radio buttons/text box for assigning points for a section or class.
                   3146:     #handles different parts of a problem
1.375     albertel 3147:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3148:     my %weight = ();
                   3149:     my $ctsparts = 0;
1.41      ng       3150:     $result.='<table border="0">';
1.45      ng       3151:     my %seen = ();
1.375     albertel 3152:     my @part_response_id = &flatten_responseType($responseType);
                   3153:     foreach my $part_response_id (@part_response_id) {
                   3154:     	my ($partid,$respid) = @{ $part_response_id };
                   3155: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3156: 	next if $seen{$partid};
                   3157: 	$seen{$partid}++;
1.375     albertel 3158: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3159: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3160: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3161: 
1.44      ng       3162: 	$result.='<input type="hidden" name="partid_'.
                   3163: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3164: 	$result.='<input type="hidden" name="weight_'.
                   3165: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3166: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3167: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3168: 	$result.='<table border="0"><tr>';  
1.41      ng       3169: 	my $ctr = 0;
1.42      ng       3170: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3171: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3172: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3173: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3174: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3175: 	    $ctr++;
                   3176: 	}
                   3177: 	$result.='</tr></table>';
1.44      ng       3178: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3179: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3180: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3181: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3182: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3183: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3184: 		$weight{$partid}.')"> '.
1.401     albertel 3185: 	    '<option selected="selected"> </option>'.
1.125     ng       3186: 	    '<option>excused</option>'.
1.265     www      3187: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3188:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3189: 	$ctsparts++;
1.41      ng       3190:     }
1.52      albertel 3191:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3192: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3193:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3194: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3195: 
1.44      ng       3196:     #table listing all the students in a section/class
                   3197:     #header of table
1.126     ng       3198:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3199:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3200: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3201: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3202:     my (@parts) = sort(&getpartlist($symb));
                   3203:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3204:     my @partids = ();
1.41      ng       3205:     foreach my $part (@parts) {
                   3206: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3207: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3208: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3209: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3210:         push(@partids, $partid);
1.324     albertel 3211: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3212: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3213: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3214: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3215: 	    next;
1.207     albertel 3216: 	} else {
                   3217: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3218: 	}
1.53      albertel 3219: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3220: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3221:     }
                   3222:     $result.='</tr>';
1.44      ng       3223: 
1.270     albertel 3224:     my %last_resets = 
                   3225: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3226: 
1.41      ng       3227:     #get info for each student
1.44      ng       3228:     #list all the students - with points and grade status
1.257     albertel 3229:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3230:     my $ctr = 0;
1.294     albertel 3231:     foreach (sort 
                   3232: 	     {
                   3233: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3234: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3235: 		 }
                   3236: 		 return $a cmp $b;
                   3237: 	     } (keys(%$fullname))) {
1.126     ng       3238: 	$ctr++;
1.324     albertel 3239: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3240: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3241:     }
                   3242:     $result.='</table></td></tr></table>';
                   3243:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3244:     $result.='<input type="button" value="Save" '.
1.417     albertel 3245: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3246:     if (scalar(%$fullname) eq 0) {
                   3247: 	my $colspan=3+scalar(@parts);
1.433     banghart 3248: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3249:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3250: 	$result='<span class="LC_warning">'.
                   3251: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3252: 	        $section_display, $stu_status).
1.433     banghart 3253: 	    '</span>';
1.96      albertel 3254:     }
1.324     albertel 3255:     $result.=&show_grading_menu_form($symb);
1.41      ng       3256:     return $result;
                   3257: }
                   3258: 
1.44      ng       3259: #--- call by previous routine to display each student
1.41      ng       3260: sub viewstudentgrade {
1.324     albertel 3261:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3262:     my ($uname,$udom) = split(/:/,$student);
                   3263:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3264:     my %aggregates = (); 
1.233     albertel 3265:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3266: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3267: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3268: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3269: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3270: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3271:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3272:     foreach my $apart (@$parts) {
                   3273: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3274: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3275:         $result.='<td align="center">';
1.269     raeburn  3276:         my ($aggtries,$totaltries);
                   3277:         unless (exists($aggregates{$part})) {
1.270     albertel 3278: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3279: 
                   3280: 	    $aggtries = $totaltries;
1.269     raeburn  3281:             if ($$last_resets{$part}) {  
1.270     albertel 3282:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3283: 					   $part);
                   3284:             }
1.269     raeburn  3285:             $result.='<input type="hidden" name="'.
                   3286:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3287:             $result.='<input type="hidden" name="'.
                   3288:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3289:             $aggregates{$part} = 1;
                   3290:         }
1.41      ng       3291: 	if ($type eq 'awarded') {
1.320     albertel 3292: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3293: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3294: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3295: 	    $result.='<input type="text" name="'.
1.89      albertel 3296: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3297: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3298: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3299: 	} elsif ($type eq 'solved') {
                   3300: 	    my ($status,$foo)=split(/_/,$score,2);
                   3301: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3302: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3303: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3304: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3305: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3306: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3307: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3308: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3309: 	    $result.='<option>reset status</option>';
1.126     ng       3310: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3311: 	} else {
                   3312: 	    $result.='<input type="hidden" name="'.
                   3313: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3314: 		    "\n";
1.233     albertel 3315: 	    $result.='<input type="text" name="'.
1.122     ng       3316: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3317: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3318: 	}
                   3319:     }
                   3320:     $result.='</tr>';
                   3321:     return $result;
1.38      ng       3322: }
                   3323: 
1.44      ng       3324: #--- change scores for all the students in a section/class
                   3325: #    record does not get update if unchanged
1.38      ng       3326: sub editgrades {
1.41      ng       3327:     my ($request) = @_;
                   3328: 
1.324     albertel 3329:     my $symb=&get_symb($request);
1.433     banghart 3330:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3331:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3332:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3333:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3334: 
1.44      ng       3335:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3336:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3337: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3338: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3339: 
                   3340:     my %scoreptr = (
                   3341: 		    'correct'  =>'correct_by_override',
                   3342: 		    'incorrect'=>'incorrect_by_override',
                   3343: 		    'excused'  =>'excused',
                   3344: 		    'ungraded' =>'ungraded_attempted',
                   3345: 		    'nothing'  => '',
                   3346: 		    );
1.257     albertel 3347:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3348: 
1.44      ng       3349:     my (@partid);
                   3350:     my %weight = ();
1.54      albertel 3351:     my %columns = ();
1.44      ng       3352:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3353: 
1.324     albertel 3354:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3355:     my $header;
1.257     albertel 3356:     while ($ctr < $env{'form.totalparts'}) {
                   3357: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3358: 	push @partid,$partid;
1.257     albertel 3359: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3360: 	$ctr++;
1.54      albertel 3361:     }
1.324     albertel 3362:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3363:     foreach my $partid (@partid) {
                   3364: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3365: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3366: 	$columns{$partid}=2;
                   3367: 	foreach my $stores (@parts) {
                   3368: 	    my ($part,$type) = &split_part_type($stores);
                   3369: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3370: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3371: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3372: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3373: 	    $display =~ s/Number of Attempts/Tries/;
                   3374: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3375: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3376: 	    $columns{$partid}+=2;
                   3377: 	}
                   3378:     }
                   3379:     foreach my $partid (@partid) {
1.324     albertel 3380: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3381: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3382: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3383: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3384: 
1.44      ng       3385:     }
                   3386:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3387:     $result .= $header;
1.44      ng       3388:     $result .= '</tr>'."\n";
1.93      albertel 3389:     my $noupdate;
1.126     ng       3390:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3391:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3392: 	my $line;
1.257     albertel 3393: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3394: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3395: 	my %newrecord;
                   3396: 	my $updateflag = 0;
1.281     albertel 3397: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3398: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3399: 	if (!&canmodify($usec)) {
1.126     ng       3400: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3401: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3402: 	    next;
                   3403: 	}
1.269     raeburn  3404:         my %aggregate = ();
                   3405:         my $aggregateflag = 0;
1.281     albertel 3406: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3407: 	foreach (@partid) {
1.257     albertel 3408: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3409: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3410: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3411: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3412: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3413: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3414: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3415: 	    my $score;
                   3416: 	    if ($partial eq '') {
1.257     albertel 3417: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3418: 	    } elsif ($partial > 0) {
                   3419: 		$score = 'correct_by_override';
                   3420: 	    } elsif ($partial == 0) {
                   3421: 		$score = 'incorrect_by_override';
                   3422: 	    }
1.257     albertel 3423: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3424: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3425: 
1.292     albertel 3426: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3427: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3428: 	    if ($dropMenu eq 'reset status' &&
                   3429: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3430: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3431: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3432: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3433: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3434: 		$updateflag = 1;
1.269     raeburn  3435:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3436:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3437:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3438:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3439:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3440:                     $aggregateflag = 1;
                   3441:                 }
1.139     albertel 3442: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3443: 		$updateflag = 1;
                   3444: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3445: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3446: 		$rec_update++;
1.125     ng       3447: 	    }
                   3448: 
1.93      albertel 3449: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3450: 		'<td align="center">'.$awarded.
                   3451: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3452: 
1.54      albertel 3453: 
                   3454: 	    my $partid=$_;
                   3455: 	    foreach my $stores (@parts) {
                   3456: 		my ($part,$type) = &split_part_type($stores);
                   3457: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3458: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3459: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3460: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3461: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3462: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3463: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3464: 		    $updateflag=1;
                   3465: 		}
1.93      albertel 3466: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3467: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3468: 	    }
1.44      ng       3469: 	}
1.93      albertel 3470: 	$line.='</tr>'."\n";
1.301     albertel 3471: 
                   3472: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3473: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3474: 
1.44      ng       3475: 	if ($updateflag) {
                   3476: 	    $count++;
1.257     albertel 3477: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3478: 				    $udom,$uname);
1.301     albertel 3479: 
                   3480: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3481: 					      $cnum,$udom,$uname)) {
                   3482: 		# need to figure out if should be in queue.
                   3483: 		my %record =  
                   3484: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3485: 					     $udom,$uname);
                   3486: 		my $all_graded = 1;
                   3487: 		my $none_graded = 1;
                   3488: 		foreach my $part (@parts) {
                   3489: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3490: 			$all_graded = 0;
                   3491: 		    } else {
                   3492: 			$none_graded = 0;
                   3493: 		    }
                   3494: 		}
                   3495: 
                   3496: 		if ($all_graded || $none_graded) {
                   3497: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3498: 							   $symb,$cdom,$cnum,
                   3499: 							   $udom,$uname);
                   3500: 		}
                   3501: 	    }
                   3502: 
1.126     ng       3503: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3504: 	    $updateCtr++;
1.93      albertel 3505: 	} else {
1.126     ng       3506: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3507: 	    $noupdateCtr++;
1.44      ng       3508: 	}
1.269     raeburn  3509:         if ($aggregateflag) {
                   3510:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3511: 				  $cdom,$cnum);
1.269     raeburn  3512:         }
1.93      albertel 3513:     }
                   3514:     if ($noupdate) {
1.126     ng       3515: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3516: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3517: 	$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       3518:     }
1.72      ng       3519:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3520: 	&show_grading_menu_form ($symb);
1.125     ng       3521:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3522: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3523: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3524:     return $title.$msg.$result;
1.5       albertel 3525: }
1.54      albertel 3526: 
                   3527: sub split_part_type {
                   3528:     my ($partstr) = @_;
                   3529:     my ($temp,@allparts)=split(/_/,$partstr);
                   3530:     my $type=pop(@allparts);
1.439     albertel 3531:     my $part=join('_',@allparts);
1.54      albertel 3532:     return ($part,$type);
                   3533: }
                   3534: 
1.44      ng       3535: #------------- end of section for handling grading by section/class ---------
                   3536: #
                   3537: #----------------------------------------------------------------------------
                   3538: 
1.5       albertel 3539: 
1.44      ng       3540: #----------------------------------------------------------------------------
                   3541: #
                   3542: #-------------------------- Next few routines handles grading by csv upload
                   3543: #
                   3544: #--- Javascript to handle csv upload
1.27      albertel 3545: sub csvupload_javascript_reverse_associate {
1.246     albertel 3546:     my $error1=&mt('You need to specify the username or ID');
                   3547:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3548:   return(<<ENDPICK);
                   3549:   function verify(vf) {
                   3550:     var foundsomething=0;
                   3551:     var founduname=0;
1.243     albertel 3552:     var foundID=0;
1.27      albertel 3553:     for (i=0;i<=vf.nfields.value;i++) {
                   3554:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3555:       if (i==0 && tw!=0) { foundID=1; }
                   3556:       if (i==1 && tw!=0) { founduname=1; }
                   3557:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3558:     }
1.246     albertel 3559:     if (founduname==0 && foundID==0) {
                   3560: 	alert('$error1');
                   3561: 	return;
1.27      albertel 3562:     }
                   3563:     if (foundsomething==0) {
1.246     albertel 3564: 	alert('$error2');
                   3565: 	return;
1.27      albertel 3566:     }
                   3567:     vf.submit();
                   3568:   }
                   3569:   function flip(vf,tf) {
                   3570:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3571:     var i;
                   3572:     for (i=0;i<=vf.nfields.value;i++) {
                   3573:       //can not pick the same destination field for both name and domain
                   3574:       if (((i ==0)||(i ==1)) && 
                   3575:           ((tf==0)||(tf==1)) && 
                   3576:           (i!=tf) &&
                   3577:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3578:         eval('vf.f'+i+'.selectedIndex=0;')
                   3579:       }
                   3580:     }
                   3581:   }
                   3582: ENDPICK
                   3583: }
                   3584: 
                   3585: sub csvupload_javascript_forward_associate {
1.246     albertel 3586:     my $error1=&mt('You need to specify the username or ID');
                   3587:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3588:   return(<<ENDPICK);
                   3589:   function verify(vf) {
                   3590:     var foundsomething=0;
                   3591:     var founduname=0;
1.243     albertel 3592:     var foundID=0;
1.27      albertel 3593:     for (i=0;i<=vf.nfields.value;i++) {
                   3594:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3595:       if (tw==1) { foundID=1; }
                   3596:       if (tw==2) { founduname=1; }
                   3597:       if (tw>3) { foundsomething=1; }
1.27      albertel 3598:     }
1.246     albertel 3599:     if (founduname==0 && foundID==0) {
                   3600: 	alert('$error1');
                   3601: 	return;
1.27      albertel 3602:     }
                   3603:     if (foundsomething==0) {
1.246     albertel 3604: 	alert('$error2');
                   3605: 	return;
1.27      albertel 3606:     }
                   3607:     vf.submit();
                   3608:   }
                   3609:   function flip(vf,tf) {
                   3610:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3611:     var i;
                   3612:     //can not pick the same destination field twice
                   3613:     for (i=0;i<=vf.nfields.value;i++) {
                   3614:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3615:         eval('vf.f'+i+'.selectedIndex=0;')
                   3616:       }
                   3617:     }
                   3618:   }
                   3619: ENDPICK
                   3620: }
                   3621: 
1.26      albertel 3622: sub csvuploadmap_header {
1.324     albertel 3623:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3624:     my $javascript;
1.257     albertel 3625:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3626: 	$javascript=&csvupload_javascript_reverse_associate();
                   3627:     } else {
                   3628: 	$javascript=&csvupload_javascript_forward_associate();
                   3629:     }
1.45      ng       3630: 
1.324     albertel 3631:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3632:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3633:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3634:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3635:     $request->print(<<ENDPICK);
1.26      albertel 3636: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3637: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3638: $result
1.326     albertel 3639: <hr />
1.26      albertel 3640: <h3>Identify fields</h3>
                   3641: Total number of records found in file: $distotal <hr />
                   3642: Enter as many fields as you can. The system will inform you and bring you back
                   3643: to this page if the data selected is insufficient to run your class.<hr />
                   3644: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3645: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3646: <input type="hidden" name="associate"  value="" />
                   3647: <input type="hidden" name="phase"      value="three" />
                   3648: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3649: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3650: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3651: <input type="hidden" name="upfile_associate" 
1.257     albertel 3652:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3653: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3654: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3655: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3656: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3657: <hr />
                   3658: <script type="text/javascript" language="Javascript">
                   3659: $javascript
                   3660: </script>
                   3661: ENDPICK
1.118     ng       3662:     return '';
1.26      albertel 3663: 
                   3664: }
                   3665: 
                   3666: sub csvupload_fields {
1.324     albertel 3667:     my ($symb) = @_;
                   3668:     my (@parts) = &getpartlist($symb);
1.243     albertel 3669:     my @fields=(['ID','Student ID'],
                   3670: 		['username','Student Username'],
                   3671: 		['domain','Student Domain']);
1.324     albertel 3672:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3673:     foreach my $part (sort(@parts)) {
                   3674: 	my @datum;
                   3675: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3676: 	my $name=$part;
                   3677: 	if  (!$display) { $display = $name; }
                   3678: 	@datum=($name,$display);
1.244     albertel 3679: 	if ($name=~/^stores_(.*)_awarded/) {
                   3680: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3681: 	}
1.41      ng       3682: 	push(@fields,\@datum);
                   3683:     }
                   3684:     return (@fields);
1.26      albertel 3685: }
                   3686: 
                   3687: sub csvuploadmap_footer {
1.41      ng       3688:     my ($request,$i,$keyfields) =@_;
                   3689:     $request->print(<<ENDPICK);
1.26      albertel 3690: </table>
                   3691: <input type="hidden" name="nfields" value="$i" />
                   3692: <input type="hidden" name="keyfields" value="$keyfields" />
                   3693: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3694: </form>
                   3695: ENDPICK
                   3696: }
                   3697: 
1.283     albertel 3698: sub checkforfile_js {
1.86      ng       3699:     my $result =<<CSVFORMJS;
                   3700: <script type="text/javascript" language="javascript">
                   3701:     function checkUpload(formname) {
                   3702: 	if (formname.upfile.value == "") {
                   3703: 	    alert("Please use the browse button to select a file from your local directory.");
                   3704: 	    return false;
                   3705: 	}
                   3706: 	formname.submit();
                   3707:     }
                   3708:     </script>
                   3709: CSVFORMJS
1.283     albertel 3710:     return $result;
                   3711: }
                   3712: 
                   3713: sub upcsvScores_form {
                   3714:     my ($request) = shift;
1.324     albertel 3715:     my ($symb)=&get_symb($request);
1.283     albertel 3716:     if (!$symb) {return '';}
                   3717:     my $result=&checkforfile_js();
1.257     albertel 3718:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3719:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3720:     $result.=$table;
1.326     albertel 3721:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3722:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3723:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3724: 	'.</b></td></tr>'."\n";
                   3725:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3726:     my $upload=&mt("Upload Scores");
1.86      ng       3727:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3728:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3729:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3730:     $result.=<<ENDUPFORM;
1.106     albertel 3731: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3732: <input type="hidden" name="symb" value="$symb" />
                   3733: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3734: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3735: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3736: $upfile_select
1.370     www      3737: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3738: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3739: </form>
                   3740: ENDUPFORM
1.370     www      3741:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3742:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3743:     .'</td></tr></table>'."\n";
1.86      ng       3744:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3745:     $result.=&show_grading_menu_form($symb);
1.86      ng       3746:     return $result;
                   3747: }
                   3748: 
                   3749: 
1.26      albertel 3750: sub csvuploadmap {
1.41      ng       3751:     my ($request)= @_;
1.324     albertel 3752:     my ($symb)=&get_symb($request);
1.41      ng       3753:     if (!$symb) {return '';}
1.72      ng       3754: 
1.41      ng       3755:     my $datatoken;
1.257     albertel 3756:     if (!$env{'form.datatoken'}) {
1.41      ng       3757: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3758:     } else {
1.257     albertel 3759: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3760: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3761:     }
1.41      ng       3762:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3763:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3764:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3765:     my ($i,$keyfields);
                   3766:     if (@records) {
1.324     albertel 3767: 	my @fields=&csvupload_fields($symb);
1.45      ng       3768: 
1.257     albertel 3769: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3770: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3771: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3772: 							  \@fields);
                   3773: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3774: 	    chop($keyfields);
                   3775: 	} else {
                   3776: 	    unshift(@fields,['none','']);
                   3777: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3778: 							    \@fields);
1.311     banghart 3779:             foreach my $rec (@records) {
                   3780:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3781:                 if (%temp) {
                   3782:                     $keyfields=join(',',sort(keys(%temp)));
                   3783:                     last;
                   3784:                 }
                   3785:             }
1.41      ng       3786: 	}
                   3787:     }
                   3788:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3789:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3790: 
1.41      ng       3791:     return '';
1.27      albertel 3792: }
                   3793: 
1.246     albertel 3794: sub csvuploadoptions {
1.41      ng       3795:     my ($request)= @_;
1.324     albertel 3796:     my ($symb)=&get_symb($request);
1.257     albertel 3797:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3798:     my $ignore=&mt('Ignore First Line');
                   3799:     $request->print(<<ENDPICK);
                   3800: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3801: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3802: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3803: <!--
1.246     albertel 3804: <p>
                   3805: <label>
                   3806:    <input type="checkbox" name="show_full_results" />
                   3807:    Show a table of all changes
                   3808: </label>
                   3809: </p>
1.302     albertel 3810: -->
1.246     albertel 3811: <p>
                   3812: <label>
                   3813:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3814:    Overwrite any existing score
                   3815: </label>
                   3816: </p>
                   3817: ENDPICK
                   3818:     my %fields=&get_fields();
                   3819:     if (!defined($fields{'domain'})) {
1.257     albertel 3820: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3821: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3822:     }
1.257     albertel 3823:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3824: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3825: 	my $cleankey=$1;
                   3826: 	if ($cleankey eq 'command') { next; }
                   3827: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3828: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3829:     }
                   3830:     # FIXME do a check for any duplicated user ids...
                   3831:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3832:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3833: <hr /></form>'."\n");
1.324     albertel 3834:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3835:     return '';
                   3836: }
                   3837: 
                   3838: sub get_fields {
                   3839:     my %fields;
1.257     albertel 3840:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3841:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3842: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3843: 	    if ($env{'form.f'.$i} ne 'none') {
                   3844: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3845: 	    }
                   3846: 	} else {
1.257     albertel 3847: 	    if ($env{'form.f'.$i} ne 'none') {
                   3848: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3849: 	    }
                   3850: 	}
1.27      albertel 3851:     }
1.246     albertel 3852:     return %fields;
                   3853: }
                   3854: 
                   3855: sub csvuploadassign {
                   3856:     my ($request)= @_;
1.324     albertel 3857:     my ($symb)=&get_symb($request);
1.246     albertel 3858:     if (!$symb) {return '';}
1.345     bowersj2 3859:     my $error_msg = '';
1.246     albertel 3860:     &Apache::loncommon::load_tmp_file($request);
                   3861:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3862:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3863:     my %fields=&get_fields();
1.41      ng       3864:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3865:     my $courseid=$env{'request.course.id'};
1.97      albertel 3866:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3867:     my @notallowed;
1.41      ng       3868:     my @skipped;
                   3869:     my $countdone=0;
                   3870:     foreach my $grade (@gradedata) {
                   3871: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3872: 	my $domain;
                   3873: 	if ($entries{$fields{'domain'}}) {
                   3874: 	    $domain=$entries{$fields{'domain'}};
                   3875: 	} else {
1.257     albertel 3876: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3877: 	}
1.243     albertel 3878: 	$domain=~s/\s//g;
1.41      ng       3879: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3880: 	$username=~s/\s//g;
1.243     albertel 3881: 	if (!$username) {
                   3882: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3883: 	    $id=~s/\s//g;
1.243     albertel 3884: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3885: 	    $username=$ids{$id};
                   3886: 	}
1.41      ng       3887: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3888: 	    my $id=$entries{$fields{'ID'}};
                   3889: 	    $id=~s/\s//g;
                   3890: 	    if ($id) {
                   3891: 		push(@skipped,"$id:$domain");
                   3892: 	    } else {
                   3893: 		push(@skipped,"$username:$domain");
                   3894: 	    }
1.41      ng       3895: 	    next;
                   3896: 	}
1.108     albertel 3897: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3898: 	if (!&canmodify($usec)) {
                   3899: 	    push(@notallowed,"$username:$domain");
                   3900: 	    next;
                   3901: 	}
1.244     albertel 3902: 	my %points;
1.41      ng       3903: 	my %grades;
                   3904: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3905: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3906: 		$dest eq 'domain') { next; }
                   3907: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3908: 	    if ($dest=~/stores_(.*)_points/) {
                   3909: 		my $part=$1;
                   3910: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3911: 					      $symb,$domain,$username);
1.345     bowersj2 3912:                 if ($wgt) {
                   3913:                     $entries{$fields{$dest}}=~s/\s//g;
                   3914:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3915:                     my $award='correct_by_override';
                   3916:                     $grades{"resource.$part.awarded"}=$pcr;
                   3917:                     $grades{"resource.$part.solved"}=$award;
                   3918:                     $points{$part}=1;
                   3919:                 } else {
                   3920:                     $error_msg = "<br />" .
                   3921:                         &mt("Some point values were assigned"
                   3922:                             ." for problems with a weight "
                   3923:                             ."of zero. These values were "
                   3924:                             ."ignored.");
                   3925:                 }
1.244     albertel 3926: 	    } else {
                   3927: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3928: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3929: 		my $store_key=$dest;
                   3930: 		$store_key=~s/^stores/resource/;
                   3931: 		$store_key=~s/_/\./g;
                   3932: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3933: 	    }
1.41      ng       3934: 	}
1.398     albertel 3935: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3936: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3937: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3938: 					   $env{'request.course.id'},
                   3939: 					   $domain,$username);
                   3940: 	if ($result eq 'ok') {
                   3941: 	    $request->print('.');
                   3942: 	} else {
                   3943: 	    $request->print("<p>
1.398     albertel 3944:                               <span class=\"LC_error\">
                   3945:                                  Failed to save student $username:$domain.
                   3946:                                  Message when trying to save was ($result)
                   3947:                               </span>
1.302     albertel 3948:                              </p>" );
                   3949: 	}
1.41      ng       3950: 	$request->rflush();
                   3951: 	$countdone++;
                   3952:     }
1.398     albertel 3953:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3954:     if (@skipped) {
1.398     albertel 3955: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3956: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3957:     }
                   3958:     if (@notallowed) {
1.398     albertel 3959: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3960: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3961:     }
1.106     albertel 3962:     $request->print("<br />\n");
1.324     albertel 3963:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3964:     return $error_msg;
1.26      albertel 3965: }
1.44      ng       3966: #------------- end of section for handling csv file upload ---------
                   3967: #
                   3968: #-------------------------------------------------------------------
                   3969: #
1.122     ng       3970: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3971: #
                   3972: #--- Select a page/sequence and a student to grade
1.68      ng       3973: sub pickStudentPage {
                   3974:     my ($request) = shift;
                   3975: 
                   3976:     $request->print(<<LISTJAVASCRIPT);
                   3977: <script type="text/javascript" language="javascript">
                   3978: 
                   3979: function checkPickOne(formname) {
1.76      ng       3980:     if (radioSelection(formname.student) == null) {
1.68      ng       3981: 	alert("Please select the student you wish to grade.");
                   3982: 	return;
                   3983:     }
1.125     ng       3984:     ptr = pullDownSelection(formname.selectpage);
                   3985:     formname.page.value = formname["page"+ptr].value;
                   3986:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3987:     formname.submit();
                   3988: }
                   3989: 
                   3990: </script>
                   3991: LISTJAVASCRIPT
1.118     ng       3992:     &commonJSfunctions($request);
1.324     albertel 3993:     my ($symb) = &get_symb($request);
1.257     albertel 3994:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3995:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3996:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3997: 
1.398     albertel 3998:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3999: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       4000: 
1.80      ng       4001:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       4002:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 4003:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4004:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4005: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4006: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4007:     my $ctr=0;
1.68      ng       4008:     foreach (@$titles) {
                   4009: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4010: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4011: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4012: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4013: 	$ctr++;
1.68      ng       4014:     }
1.326     albertel 4015:     $result.= '</select>'."<br />\n";
1.70      ng       4016:     $ctr=0;
                   4017:     foreach (@$titles) {
                   4018: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4019: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4020: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4021: 	$ctr++;
                   4022:     }
1.72      ng       4023:     $result.='<input type="hidden" name="page" />'."\n".
                   4024: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4025: 
1.401     albertel 4026:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4027: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4028: 
1.71      ng       4029:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4030: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4031: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4032: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4033:     
                   4034:     $result.=&build_section_inputs();
1.442     banghart 4035:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4036:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4037: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4038: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4039: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4040: 
1.382     albertel 4041:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4042: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4043: 
1.80      ng       4044:     $result.='&nbsp;<input type="button" '.
1.126     ng       4045: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4046: 
1.68      ng       4047:     $request->print($result);
                   4048: 
1.326     albertel 4049:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4050: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4051: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4052: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4053: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4054: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4055: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4056:  
1.76      ng       4057:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4058:     my $ptr = 1;
1.294     albertel 4059:     foreach my $student (sort 
                   4060: 			 {
                   4061: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4062: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4063: 			     }
                   4064: 			     return $a cmp $b;
                   4065: 			 } (keys(%$fullname))) {
1.68      ng       4066: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4067: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4068: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4069: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4070: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4071: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4072: 	$ptr++;
                   4073:     }
1.381     albertel 4074:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4075:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4076:     $studentTable.='<input type="button" '.
                   4077: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4078: 
1.324     albertel 4079:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4080:     $request->print($studentTable);
                   4081: 
                   4082:     return '';
                   4083: }
                   4084: 
                   4085: sub getSymbMap {
1.132     bowersj2 4086:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4087: 
                   4088:     my %symbx = ();
                   4089:     my @titles = ();
1.117     bowersj2 4090:     my $minder = 0;
                   4091: 
                   4092:     # Gather every sequence that has problems.
1.240     albertel 4093:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4094: 					       1,0,1);
1.117     bowersj2 4095:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4096: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4097: 	    my $title = $minder.'.'.
                   4098: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4099: 	    push(@titles, $title); # minder in case two titles are identical
                   4100: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4101: 	    $minder++;
1.241     albertel 4102: 	}
1.68      ng       4103:     }
                   4104:     return \@titles,\%symbx;
                   4105: }
                   4106: 
1.72      ng       4107: #
                   4108: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4109: sub displayPage {
                   4110:     my ($request) = shift;
                   4111: 
1.324     albertel 4112:     my ($symb) = &get_symb($request);
1.257     albertel 4113:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4114:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4115:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4116:     my $pageTitle = $env{'form.page'};
1.103     albertel 4117:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4118:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4119:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4120: 
                   4121:     #need to make sure we have the correct data for later EXT calls, 
                   4122:     #thus invalidate the cache
                   4123:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4124:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4125:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4126:     &Apache::lonnet::clear_EXT_cache_status();
                   4127: 
1.103     albertel 4128:     if (!&canview($usec)) {
1.398     albertel 4129: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4130: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4131: 	return;
                   4132:     }
1.398     albertel 4133:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4134:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4135: 	'</h3>'."\n";
1.382     albertel 4136:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4137: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4138:     } else {
                   4139: 	delete($env{'form.CODE'});
                   4140:     }
1.71      ng       4141:     &sub_page_js($request);
                   4142:     $request->print($result);
                   4143: 
1.132     bowersj2 4144:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4145:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4146:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4147:     if (!$map) {
1.398     albertel 4148: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4149: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4150: 	return; 
                   4151:     }
1.68      ng       4152:     my $iterator = $navmap->getIterator($map->map_start(),
                   4153: 					$map->map_finish());
                   4154: 
1.71      ng       4155:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4156: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4157: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4158: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4159: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4160: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4161: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4162: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4163: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4164: 
1.382     albertel 4165:     if (defined($env{'form.CODE'})) {
                   4166: 	$studentTable.=
                   4167: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4168:     }
1.381     albertel 4169:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4170: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4171: 	'/check.gif" height="16" border="0" />';
                   4172: 
1.118     ng       4173:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4174: 	' symbol.'."\n".
1.71      ng       4175: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4176: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4177: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4178: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4179: 
1.329     albertel 4180:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4181:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4182:     $iterator->next(); # skip the first BEGIN_MAP
                   4183:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4184:     while ($depth > 0) {
1.68      ng       4185:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4186:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4187: 
1.385     albertel 4188:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4189: 	    my $parts = $curRes->parts();
1.68      ng       4190:             my $title = $curRes->compTitle();
1.71      ng       4191: 	    my $symbx = $curRes->symb();
1.196     albertel 4192: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4193: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4194: 	    $studentTable.='<td valign="top">';
1.382     albertel 4195: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4196: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4197: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4198: 					     undef,'both',\%form);
1.71      ng       4199: 	    } else {
1.382     albertel 4200: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4201: 		$companswer =~ s|<form(.*?)>||g;
                   4202: 		$companswer =~ s|</form>||g;
1.71      ng       4203: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4204: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4205: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4206: #		}
1.116     ng       4207: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4208: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4209: 	    }
                   4210: 
1.257     albertel 4211: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4212: 
1.257     albertel 4213: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4214: 		if ($record{'version'} eq '') {
1.398     albertel 4215: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4216: 		} else {
1.116     ng       4217: 		    my %responseType = ();
                   4218: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4219: 			my @responseIds =$curRes->responseIds($partid);
                   4220: 			my @responseType =$curRes->responseType($partid);
                   4221: 			my %responseIds;
                   4222: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4223: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4224: 			}
                   4225: 			$responseType{$partid} = \%responseIds;
1.116     ng       4226: 		    }
1.148     albertel 4227: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4228: 
1.71      ng       4229: 		}
1.257     albertel 4230: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4231: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4232: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4233: 									$env{'request.course.id'},
1.71      ng       4234: 									'','.submission');
                   4235:  
                   4236: 	    }
1.103     albertel 4237: 	    if (&canmodify($usec)) {
                   4238: 		foreach my $partid (@{$parts}) {
                   4239: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4240: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4241: 		    $question++;
                   4242: 		}
1.196     albertel 4243: 		$prob++;
1.71      ng       4244: 	    }
                   4245: 	    $studentTable.='</td></tr>';
1.68      ng       4246: 
1.103     albertel 4247: 	}
1.68      ng       4248:         $curRes = $iterator->next();
                   4249:     }
                   4250: 
1.381     albertel 4251:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4252: 	'<input type="button" value="Save" '.
1.381     albertel 4253: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4254: 	'</form>'."\n";
1.324     albertel 4255:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4256:     $request->print($studentTable);
                   4257: 
                   4258:     return '';
1.119     ng       4259: }
                   4260: 
                   4261: sub displaySubByDates {
1.148     albertel 4262:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4263:     my $isCODE=0;
1.335     albertel 4264:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4265:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4266:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4267: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4268: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4269: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4270: 	'<td><b>Submission</b></td>'.
                   4271: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4272:     my ($version);
                   4273:     my %mark;
1.148     albertel 4274:     my %orders;
1.119     ng       4275:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4276:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4277: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4278:     }
1.335     albertel 4279: 
                   4280:     my $interaction;
1.119     ng       4281:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4282: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4283: 	if (exists($$record{$version.':resource.0.version'})) {
                   4284: 	    $interaction = $$record{$version.':resource.0.version'};
                   4285: 	}
                   4286: 
                   4287: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4288: 		             : "$version:resource");
1.119     ng       4289: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4290: 	if ($isCODE) {
                   4291: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4292: 	}
1.119     ng       4293: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4294: 	my @displaySub = ();
                   4295: 	foreach my $partid (@{$parts}) {
1.335     albertel 4296: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4297: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4298: 	    
                   4299: 
1.122     ng       4300: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4301: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4302: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4303: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4304: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4305: 
                   4306: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4307: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4308: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4309: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4310: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4311: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4312: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4313: 		    } else {
                   4314: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4315: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4316: 		    }
1.335     albertel 4317: 		    my $responseType=($isTask ? 'Task'
                   4318:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4319: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4320: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4321: 			$orders{$partid}->{$responseId}=
                   4322: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4323: 		    }
1.147     albertel 4324: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4325: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4326: 		}
                   4327: 	    }
1.335     albertel 4328: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4329: 		$displaySub[1].='Checked in by '.
                   4330: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4331: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4332: 		    '<br />';
                   4333: 	    }
                   4334: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4335: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4336: 		    lc($$record{"$where.$partid.award"}).' '.
                   4337: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4338: 		    '<br />';
                   4339: 	    }
1.335     albertel 4340: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4341: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4342: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4343: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4344: 		$displaySub[2].=
                   4345: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4346: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4347: 	    }
                   4348: 	}
                   4349: 	# needed because old essay regrader has not parts info
                   4350: 	if (exists $$record{"$version:resource.regrader"}) {
                   4351: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4352: 	}
                   4353: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4354: 	if ($displaySub[2]) {
                   4355: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4356: 	}
1.382     albertel 4357: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4358:     
1.119     ng       4359:     }
                   4360:     $studentTable.='</table></td></tr></table>';
                   4361:     return $studentTable;
1.71      ng       4362: }
                   4363: 
                   4364: sub updateGradeByPage {
                   4365:     my ($request) = shift;
                   4366: 
1.257     albertel 4367:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4368:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4369:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4370:     my $pageTitle = $env{'form.page'};
1.103     albertel 4371:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4372:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4373:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4374:     if (!&canmodify($usec)) {
1.398     albertel 4375: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4376: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4377: 	return;
                   4378:     }
1.398     albertel 4379:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4380:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4381: 	'</h3>'."\n";
1.70      ng       4382: 
1.68      ng       4383:     $request->print($result);
                   4384: 
1.132     bowersj2 4385:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4386:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4387:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4388:     if (!$map) {
1.398     albertel 4389: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4390: 	my ($symb)=&get_symb($request);
                   4391: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4392: 	return; 
                   4393:     }
1.71      ng       4394:     my $iterator = $navmap->getIterator($map->map_start(),
                   4395: 					$map->map_finish());
1.70      ng       4396: 
1.71      ng       4397:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4398: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4399: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4400: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4401: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4402: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4403: 
                   4404:     $iterator->next(); # skip the first BEGIN_MAP
                   4405:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4406:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4407:     while ($depth > 0) {
1.71      ng       4408:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4409:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4410: 
1.385     albertel 4411:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4412: 	    my $parts = $curRes->parts();
1.71      ng       4413:             my $title = $curRes->compTitle();
                   4414: 	    my $symbx = $curRes->symb();
1.196     albertel 4415: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4416: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4417: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4418: 
                   4419: 	    my %newrecord=();
                   4420: 	    my @displayPts=();
1.269     raeburn  4421:             my %aggregate = ();
                   4422:             my $aggregateflag = 0;
1.71      ng       4423: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4424: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4425: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4426: 
1.257     albertel 4427: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4428: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4429: 		my $partial = $newpts/$wgt;
                   4430: 		my $score;
                   4431: 		if ($partial > 0) {
                   4432: 		    $score = 'correct_by_override';
1.125     ng       4433: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4434: 		    $score = 'incorrect_by_override';
                   4435: 		}
1.257     albertel 4436: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4437: 		if ($dropMenu eq 'excused') {
1.71      ng       4438: 		    $partial = '';
                   4439: 		    $score = 'excused';
1.125     ng       4440: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4441: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4442: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4443: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4444: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4445: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4446: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4447: 		    $changeflag++;
                   4448: 		    $newpts = '';
1.269     raeburn  4449:                     
                   4450:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4451:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4452:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4453:                     if ($aggtries > 0) {
                   4454:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4455:                         $aggregateflag = 1;
                   4456:                     }
1.71      ng       4457: 		}
1.324     albertel 4458: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4459: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4460: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4461: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4462: 		    '&nbsp;<br />';
1.207     albertel 4463: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4464: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4465: 		    '&nbsp;<br />';
1.71      ng       4466: 		$question++;
1.380     albertel 4467: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4468: 
1.71      ng       4469: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4470: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4471: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4472: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4473: 
                   4474: 		$changeflag++;
                   4475: 	    }
                   4476: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4477: 		my %record = 
                   4478: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4479: 					     $udom,$uname);
                   4480: 
                   4481: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4482: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4483: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4484: 		    $newrecord{'resource.CODE'} = '';
                   4485: 		}
1.257     albertel 4486: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4487: 					$udom,$uname);
1.382     albertel 4488: 		%record = &Apache::lonnet::restore($symbx,
                   4489: 						   $env{'request.course.id'},
                   4490: 						   $udom,$uname);
1.380     albertel 4491: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4492: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4493: 	    }
1.380     albertel 4494: 	    
1.269     raeburn  4495:             if ($aggregateflag) {
                   4496:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4497:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4498:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4499:             }
1.125     ng       4500: 
1.71      ng       4501: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4502: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4503: 		'</tr>';
1.68      ng       4504: 
1.196     albertel 4505: 	    $prob++;
1.68      ng       4506: 	}
1.71      ng       4507:         $curRes = $iterator->next();
1.68      ng       4508:     }
1.98      albertel 4509: 
1.71      ng       4510:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4511:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4512:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4513: 		  'The scores were changed for '.
                   4514: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4515:     $request->print($grademsg.$studentTable);
1.68      ng       4516: 
1.70      ng       4517:     return '';
                   4518: }
                   4519: 
1.72      ng       4520: #-------- end of section for handling grading by page/sequence ---------
                   4521: #
                   4522: #-------------------------------------------------------------------
                   4523: 
1.75      albertel 4524: #--------------------Scantron Grading-----------------------------------
                   4525: #
                   4526: #------ start of section for handling grading by page/sequence ---------
                   4527: 
1.423     albertel 4528: =pod
                   4529: 
                   4530: =head1 Bubble sheet grading routines
                   4531: 
1.424     albertel 4532:   For this documentation:
                   4533: 
                   4534:    'scanline' refers to the full line of characters
                   4535:    from the file that we are parsing that represents one entire sheet
                   4536: 
                   4537:    'bubble line' refers to the data
                   4538:    representing the line of bubbles that are on the physical bubble sheet
                   4539: 
                   4540: 
                   4541: The overall process is that a scanned in bubble sheet data is uploaded
                   4542: into a course. When a user wants to grade, they select a
                   4543: sequence/folder of resources, a file of bubble sheet info, and pick
                   4544: one of the predefined configurations for what each scanline looks
                   4545: like.
                   4546: 
                   4547: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4548: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4549: because too light bubbling), 'double bubble' (each bubble line should
                   4550: have no more that one letter picked), invalid or duplicated CODE,
                   4551: invalid student ID
                   4552: 
                   4553: If the CODE option is used that determines the randomization of the
                   4554: homework problems, either way the student ID is looked up into a
                   4555: username:domain.
                   4556: 
                   4557: During the validation phase the instructor can choose to skip scanlines. 
                   4558: 
1.435     foxr     4559: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4560: 
                   4561:   scantron_original_filename (unmodified original file)
                   4562:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4563:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4564: 
                   4565: Also there is a separate hash nohist_scantrondata that contains extra
                   4566: correction information that isn't representable in the bubble sheet
                   4567: file (see &scantron_getfile() for more information)
                   4568: 
                   4569: After all scanlines are either valid, marked as valid or skipped, then
                   4570: foreach line foreach problem in the picked sequence, an ssi request is
                   4571: made that simulates a user submitting their selected letter(s) against
                   4572: the homework problem.
1.423     albertel 4573: 
                   4574: =over 4
                   4575: 
                   4576: 
                   4577: 
                   4578: =item defaultFormData
                   4579: 
                   4580:   Returns html hidden inputs used to hold context/default values.
                   4581: 
                   4582:  Arguments:
                   4583:   $symb - $symb of the current resource 
                   4584: 
                   4585: =cut
1.422     foxr     4586: 
1.81      albertel 4587: sub defaultFormData {
1.324     albertel 4588:     my ($symb)=@_;
1.447     foxr     4589:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4590:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4591:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4592: }
                   4593: 
1.447     foxr     4594: 
1.423     albertel 4595: =pod 
                   4596: 
                   4597: =item getSequenceDropDown
                   4598: 
                   4599:    Return html dropdown of possible sequences to grade
                   4600:  
                   4601:  Arguments:
                   4602:    $symb - $symb of the current resource 
                   4603: 
                   4604: =cut
1.422     foxr     4605: 
1.75      albertel 4606: sub getSequenceDropDown {
1.423     albertel 4607:     my ($symb)=@_;
1.75      albertel 4608:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4609:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4610:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4611:     my $ctr=0;
                   4612:     foreach (@$titles) {
                   4613: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4614: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4615: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4616: 	    '>'.$showtitle.'</option>'."\n";
                   4617: 	$ctr++;
                   4618:     }
                   4619:     $result.= '</select>';
                   4620:     return $result;
                   4621: }
                   4622: 
1.423     albertel 4623: 
                   4624: =pod 
                   4625: 
                   4626: =item scantron_filenames
                   4627: 
                   4628:    Returns a list of the scantron files in the current course 
                   4629: 
                   4630: =cut
1.422     foxr     4631: 
1.202     albertel 4632: sub scantron_filenames {
1.257     albertel 4633:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4634:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4635:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4636: 				    &propath($cdom,$cname));
1.202     albertel 4637:     my @possiblenames;
1.201     albertel 4638:     foreach my $filename (sort(@files)) {
1.157     albertel 4639: 	($filename)=split(/&/,$filename);
                   4640: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4641: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4642: 	push(@possiblenames,$filename);
                   4643:     }
                   4644:     return @possiblenames;
                   4645: }
                   4646: 
1.423     albertel 4647: =pod 
                   4648: 
                   4649: =item scantron_uploads
                   4650: 
                   4651:    Returns  html drop-down list of scantron files in current course.
                   4652: 
                   4653:  Arguments:
                   4654:    $file2grade - filename to set as selected in the dropdown
                   4655: 
                   4656: =cut
1.422     foxr     4657: 
1.202     albertel 4658: sub scantron_uploads {
1.209     ng       4659:     my ($file2grade) = @_;
1.202     albertel 4660:     my $result=	'<select name="scantron_selectfile">';
                   4661:     $result.="<option></option>";
                   4662:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4663: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4664:     }
                   4665:     $result.="</select>";
                   4666:     return $result;
                   4667: }
                   4668: 
1.423     albertel 4669: =pod 
                   4670: 
                   4671: =item scantron_scantab
                   4672: 
                   4673:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4674:   file.
                   4675: 
                   4676: =cut
1.422     foxr     4677: 
1.82      albertel 4678: sub scantron_scantab {
                   4679:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4680:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4681:     $result.='<option></option>'."\n";
1.82      albertel 4682:     foreach my $line (<$fh>) {
                   4683: 	my ($name,$descrip)=split(/:/,$line);
                   4684: 	if ($name =~ /^\#/) { next; }
                   4685: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4686:     }
                   4687:     $result.='</select>'."\n";
                   4688: 
                   4689:     return $result;
                   4690: }
                   4691: 
1.423     albertel 4692: =pod 
                   4693: 
                   4694: =item scantron_CODElist
                   4695: 
                   4696:   Returns html drop down of the saved CODE lists from current course,
                   4697:   generated from earlier printings.
                   4698: 
                   4699: =cut
1.422     foxr     4700: 
1.186     albertel 4701: sub scantron_CODElist {
1.257     albertel 4702:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4703:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4704:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4705:     my $namechoice='<option></option>';
1.225     albertel 4706:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4707: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4708: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4709: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4710:     }
                   4711:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4712:     return $namechoice;
                   4713: }
                   4714: 
1.423     albertel 4715: =pod 
                   4716: 
                   4717: =item scantron_CODEunique
                   4718: 
                   4719:   Returns the html for "Each CODE to be used once" radio.
                   4720: 
                   4721: =cut
1.422     foxr     4722: 
1.186     albertel 4723: sub scantron_CODEunique {
1.381     albertel 4724:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4725:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4726:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4727:                 </span>
                   4728:                 <span style="white-space: nowrap;">
1.272     albertel 4729:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4730:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4731:                 </span>';
1.186     albertel 4732:     return $result;
                   4733: }
1.423     albertel 4734: 
                   4735: =pod 
                   4736: 
                   4737: =item scantron_selectphase
                   4738: 
                   4739:   Generates the initial screen to start the bubble sheet process.
                   4740:   Allows for - starting a grading run.
1.424     albertel 4741:              - downloading existing scan data (original, corrected
1.423     albertel 4742:                                                 or skipped info)
                   4743: 
                   4744:              - uploading new scan data
                   4745: 
                   4746:  Arguments:
                   4747:   $r          - The Apache request object
                   4748:   $file2grade - name of the file that contain the scanned data to score
                   4749: 
                   4750: =cut
1.186     albertel 4751: 
1.75      albertel 4752: sub scantron_selectphase {
1.209     ng       4753:     my ($r,$file2grade) = @_;
1.324     albertel 4754:     my ($symb)=&get_symb($r);
1.75      albertel 4755:     if (!$symb) {return '';}
1.423     albertel 4756:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4757:     my $default_form_data=&defaultFormData($symb);
                   4758:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4759:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4760:     my $format_selector=&scantron_scantab();
1.186     albertel 4761:     my $CODE_selector=&scantron_CODElist();
                   4762:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4763:     my $result;
1.422     foxr     4764: 
                   4765:     # Chunk of form to prompt for a file to grade and how:
                   4766: 
1.75      albertel 4767:     $result.= <<SCANTRONFORM;
1.162     albertel 4768:     <table width="100%" border="0">
1.75      albertel 4769:     <tr>
1.226     albertel 4770:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4771:       <td bgcolor="#777777">
1.203     albertel 4772:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4773:         $default_form_data
1.75      albertel 4774:         <table width="100%" border="0">
                   4775:           <tr bgcolor="#e6ffff">
1.174     albertel 4776:             <td colspan="2">
                   4777:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4778:             </td>
                   4779:           </tr>
                   4780:           <tr bgcolor="#ffffe6">
1.174     albertel 4781:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4782:           </tr>
                   4783:           <tr bgcolor="#ffffe6">
1.174     albertel 4784:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4785:           </tr>
1.82      albertel 4786:           <tr bgcolor="#ffffe6">
1.174     albertel 4787:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4788:           </tr>
1.157     albertel 4789:           <tr bgcolor="#ffffe6">
1.186     albertel 4790:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4791:           </tr>
                   4792:           <tr bgcolor="#ffffe6">
                   4793:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4794:           </tr>
                   4795:           <tr bgcolor="#ffffe6">
1.187     albertel 4796: 	    <td> Options: </td>
                   4797:             <td>
1.272     albertel 4798: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4799:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4800:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4801: 	    </td>
                   4802:           </tr>
                   4803:           <tr bgcolor="#ffffe6">
1.174     albertel 4804:             <td colspan="2">
1.265     www      4805:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4806:             </td>
                   4807:           </tr>
                   4808:         </table>
1.226     albertel 4809:        </td>
                   4810:      </form>
1.162     albertel 4811:     </tr>
                   4812: SCANTRONFORM
                   4813:    
                   4814:     $r->print($result);
                   4815: 
1.257     albertel 4816:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4817:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4818: 
1.422     foxr     4819: 	# Chunk of form to prompt for a scantron file upload.
                   4820: 
1.162     albertel 4821:         $r->print(<<SCANTRONFORM);
                   4822:     <tr>
                   4823:       <td bgcolor="#777777">
                   4824:         <table width="100%" border="0">
                   4825:           <tr bgcolor="#e6ffff">
                   4826:             <td>
1.174     albertel 4827:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4828:             </td>
                   4829:           </tr>
                   4830:           <tr bgcolor="#ffffe6">
                   4831:             <td>
                   4832: SCANTRONFORM
1.324     albertel 4833:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4834:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4835:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4836:     $r->print(<<UPLOAD);
                   4837:               <script type="text/javascript" language="javascript">
                   4838:     function checkUpload(formname) {
                   4839: 	if (formname.upfile.value == "") {
                   4840: 	    alert("Please use the browse button to select a file from your local directory.");
                   4841: 	    return false;
                   4842: 	}
                   4843: 	formname.submit();
                   4844:     }
                   4845:               </script>
                   4846: 
                   4847:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4848:                 $default_form_data
                   4849:                 <input name='courseid' type='hidden' value='$cnum' />
                   4850:                 <input name='domainid' type='hidden' value='$cdom' />
                   4851:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4852:                 File to upload:<input type="file" name="upfile" size="50" />
                   4853:                 <br />
                   4854:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4855:               </form>
                   4856: UPLOAD
1.162     albertel 4857: 
                   4858:         $r->print(<<SCANTRONFORM);
                   4859:             </td>
                   4860:           </tr>
1.75      albertel 4861:         </table>
                   4862:       </td>
                   4863:     </tr>
1.162     albertel 4864: SCANTRONFORM
                   4865:     }
1.422     foxr     4866: 
                   4867:     # Chunk of the form that prompts to view a scoring office file,
                   4868:     # corrected file, skipped records in a file.
                   4869: 
1.187     albertel 4870:     $r->print(<<SCANTRONFORM);
                   4871:     <tr>
1.226     albertel 4872:       <form action='/adm/grades' name='scantron_download'>
                   4873:         <td bgcolor="#777777">
1.379     albertel 4874: 	  $default_form_data
1.187     albertel 4875:           <input type="hidden" name="command" value="scantron_download" />
                   4876:           <table width="100%" border="0">
                   4877:             <tr bgcolor="#e6ffff">
                   4878:               <td colspan="2">
                   4879:                 &nbsp;<b>Download a scoring office file</b>
                   4880:               </td>
                   4881:             </tr>
                   4882:             <tr bgcolor="#ffffe6">
                   4883:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4884:             </tr>
                   4885:             <tr bgcolor="#ffffe6">
                   4886:               <td colspan="2">
1.293     www      4887:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4888:               </td>
                   4889:             </tr>
                   4890:           </table>
1.226     albertel 4891:         </td>
                   4892:       </form>
1.187     albertel 4893:     </tr>
                   4894: SCANTRONFORM
1.162     albertel 4895: 
                   4896:     $r->print(<<SCANTRONFORM);
1.75      albertel 4897:   </table>
1.81      albertel 4898: $grading_menu_button
1.75      albertel 4899: SCANTRONFORM
                   4900: 
1.162     albertel 4901:     return
1.75      albertel 4902: }
                   4903: 
1.423     albertel 4904: =pod
                   4905: 
                   4906: =item get_scantron_config
                   4907: 
                   4908:    Parse and return the scantron configuration line selected as a
                   4909:    hash of configuration file fields.
                   4910: 
                   4911:  Arguments:
                   4912:     which - the name of the configuration to parse from the file.
                   4913: 
                   4914: 
                   4915:  Returns:
                   4916:             If the named configuration is not in the file, an empty
                   4917:             hash is returned.
                   4918:     a hash with the fields
                   4919:       name         - internal name for the this configuration setup
                   4920:       description  - text to display to operator that describes this config
                   4921:       CODElocation - if 0 or the string 'none'
                   4922:                           - no CODE exists for this config
                   4923:                      if -1 || the string 'letter'
                   4924:                           - a CODE exists for this config and is
                   4925:                             a string of letters
                   4926:                      Unsupported value (but planned for future support)
                   4927:                           if a positive integer
                   4928:                                - The CODE exists as the first n items from
                   4929:                                  the question section of the form
                   4930:                           if the string 'number'
                   4931:                                - The CODE exists for this config and is
                   4932:                                  a string of numbers
                   4933:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4934:                      the CODE starts
                   4935:       CODElength  - length of the CODE
                   4936:       IDstart     - column where the student ID number starts
                   4937:       IDlength    - length of the student ID info
                   4938:       Qstart      - column where the information from the bubbled
                   4939:                     'questions' start
                   4940:       Qlength     - number of columns comprising a single bubble line from
                   4941:                     the sheet. (usually either 1 or 10)
1.424     albertel 4942:       Qon         - either a single character representing the character used
1.423     albertel 4943:                     to signal a bubble was chosen in the positional setup, or
                   4944:                     the string 'letter' if the letter of the chosen bubble is
                   4945:                     in the final, or 'number' if a number representing the
                   4946:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4947:       Qoff        - the character used to represent that a bubble was
                   4948:                     left blank
1.423     albertel 4949:       PaperID     - if the scanning process generates a unique number for each
                   4950:                     sheet scanned the column that this ID number starts in
                   4951:       PaperIDlength - number of columns that comprise the unique ID number
                   4952:                       for the sheet of paper
1.424     albertel 4953:       FirstName   - column that the first name starts in
1.423     albertel 4954:       FirstNameLength - number of columns that the first name spans
                   4955:  
                   4956:       LastName    - column that the last name starts in
                   4957:       LastNameLength - number of columns that the last name spans
                   4958: 
                   4959: =cut
1.422     foxr     4960: 
1.82      albertel 4961: sub get_scantron_config {
                   4962:     my ($which) = @_;
                   4963:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4964:     my %config;
1.157     albertel 4965:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4966:     foreach my $line (<$fh>) {
                   4967: 	my ($name,$descrip)=split(/:/,$line);
                   4968: 	if ($name ne $which ) { next; }
                   4969: 	chomp($line);
                   4970: 	my @config=split(/:/,$line);
                   4971: 	$config{'name'}=$config[0];
                   4972: 	$config{'description'}=$config[1];
                   4973: 	$config{'CODElocation'}=$config[2];
                   4974: 	$config{'CODEstart'}=$config[3];
                   4975: 	$config{'CODElength'}=$config[4];
                   4976: 	$config{'IDstart'}=$config[5];
                   4977: 	$config{'IDlength'}=$config[6];
                   4978: 	$config{'Qstart'}=$config[7];
                   4979: 	$config{'Qlength'}=$config[8];
                   4980: 	$config{'Qoff'}=$config[9];
                   4981: 	$config{'Qon'}=$config[10];
1.157     albertel 4982: 	$config{'PaperID'}=$config[11];
                   4983: 	$config{'PaperIDlength'}=$config[12];
                   4984: 	$config{'FirstName'}=$config[13];
                   4985: 	$config{'FirstNamelength'}=$config[14];
                   4986: 	$config{'LastName'}=$config[15];
                   4987: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4988: 	last;
                   4989:     }
                   4990:     return %config;
                   4991: }
                   4992: 
1.423     albertel 4993: =pod 
                   4994: 
                   4995: =item username_to_idmap
                   4996: 
                   4997:     creates a hash keyed by student id with values of the corresponding
                   4998:     student username:domain.
                   4999: 
                   5000:   Arguments:
                   5001: 
                   5002:     $classlist - reference to the class list hash. This is a hash
                   5003:                  keyed by student name:domain  whose elements are references
1.424     albertel 5004:                  to arrays containing various chunks of information
1.423     albertel 5005:                  about the student. (See loncoursedata for more info).
                   5006: 
                   5007:   Returns
                   5008:     %idmap - the constructed hash
                   5009: 
                   5010: =cut
                   5011: 
1.82      albertel 5012: sub username_to_idmap {
                   5013:     my ($classlist)= @_;
                   5014:     my %idmap;
                   5015:     foreach my $student (keys(%$classlist)) {
                   5016: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5017: 	    $student;
                   5018:     }
                   5019:     return %idmap;
                   5020: }
1.423     albertel 5021: 
                   5022: =pod
                   5023: 
1.424     albertel 5024: =item scantron_fixup_scanline
1.423     albertel 5025: 
                   5026:    Process a requested correction to a scanline.
                   5027: 
                   5028:   Arguments:
                   5029:     $scantron_config   - hash from &get_scantron_config()
                   5030:     $scan_data         - hash of correction information 
                   5031:                           (see &scantron_getfile())
                   5032:     $line              - existing scanline
                   5033:     $whichline         - line number of the passed in scanline
                   5034:     $field             - type of change to process 
                   5035:                          (either 
                   5036:                           'ID'     -> correct the student ID number
                   5037:                           'CODE'   -> correct the CODE
                   5038:                           'answer' -> fixup the submitted answers)
                   5039:     
                   5040:    $args               - hash of additional info,
                   5041:                           - 'ID' 
                   5042:                                'newid' -> studentID to use in replacement
1.424     albertel 5043:                                           of existing one
1.423     albertel 5044:                           - 'CODE' 
                   5045:                                'CODE_ignore_dup' - set to true if duplicates
                   5046:                                                    should be ignored.
                   5047: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5048:                                         if the existing unfound code should
1.423     albertel 5049:                                         be used as is
                   5050:                           - 'answer'
                   5051:                                'response' - new answer or 'none' if blank
                   5052:                                'question' - the bubble line to change
                   5053: 
                   5054:   Returns:
                   5055:     $line - the modified scanline
                   5056: 
                   5057:   Side effects: 
                   5058:     $scan_data - may be updated
                   5059: 
                   5060: =cut
                   5061: 
1.82      albertel 5062: 
1.157     albertel 5063: sub scantron_fixup_scanline {
                   5064:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5065: 
1.157     albertel 5066:     if ($field eq 'ID') {
                   5067: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5068: 	    return ($line,1,'New value too large');
1.157     albertel 5069: 	}
                   5070: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5071: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5072: 				     $args->{'newid'});
                   5073: 	}
                   5074: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5075: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5076: 	if ($args->{'newid'}=~/^\s*$/) {
                   5077: 	    &scan_data($scan_data,"$whichline.user",
                   5078: 		       $args->{'username'}.':'.$args->{'domain'});
                   5079: 	}
1.186     albertel 5080:     } elsif ($field eq 'CODE') {
1.192     albertel 5081: 	if ($args->{'CODE_ignore_dup'}) {
                   5082: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5083: 	}
                   5084: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5085: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5086: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5087: 		return ($line,1,'New CODE value too large');
                   5088: 	    }
                   5089: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5090: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5091: 	    }
                   5092: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5093: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5094: 	}
1.157     albertel 5095:     } elsif ($field eq 'answer') {
                   5096: 	my $length=$scantron_config->{'Qlength'};
                   5097: 	my $off=$scantron_config->{'Qoff'};
                   5098: 	my $on=$scantron_config->{'Qon'};
                   5099: 	my $answer=${off}x$length;
                   5100: 	if ($args->{'response'} eq 'none') {
                   5101: 	    &scan_data($scan_data,
                   5102: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5103: 	} else {
1.274     albertel 5104: 	    if ($on eq 'letter') {
                   5105: 		my @alphabet=('A'..'Z');
                   5106: 		$answer=$alphabet[$args->{'response'}];
                   5107: 	    } elsif ($on eq 'number') {
                   5108: 		$answer=$args->{'response'}+1;
1.389     albertel 5109: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5110: 	    } else {
                   5111: 		substr($answer,$args->{'response'},1)=$on;
                   5112: 	    }
1.157     albertel 5113: 	    &scan_data($scan_data,
                   5114: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5115: 	}
                   5116: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5117: 	substr($line,$where-1,$length)=$answer;
                   5118:     }
                   5119:     return $line;
                   5120: }
1.423     albertel 5121: 
                   5122: =pod
                   5123: 
                   5124: =item scan_data
                   5125: 
                   5126:     Edit or look up  an item in the scan_data hash.
                   5127: 
                   5128:   Arguments:
                   5129:     $scan_data  - The hash (see scantron_getfile)
                   5130:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5131:                   scantronfilename_key).
1.423     albertel 5132:     $data        - New value of the hash entry.
                   5133:     $delete      - If true, the entry is removed from the hash.
                   5134: 
                   5135:   Returns:
                   5136:     The new value of the hash table field (undefined if deleted).
                   5137: 
                   5138: =cut
                   5139: 
                   5140: 
1.157     albertel 5141: sub scan_data {
                   5142:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5143:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5144:     if (defined($value)) {
                   5145: 	$scan_data->{$filename.'_'.$key} = $value;
                   5146:     }
                   5147:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5148:     return $scan_data->{$filename.'_'.$key};
                   5149: }
1.423     albertel 5150: 
                   5151: =pod 
                   5152: 
                   5153: =item scantron_parse_scanline
                   5154: 
                   5155:   Decodes a scanline from the selected scantron file
                   5156: 
                   5157:  Arguments:
                   5158:     line             - The text of the scantron file line to process
                   5159:     whichline        - Line number
                   5160:     scantron_config  - Hash describing the format of the scantron lines.
                   5161:     scan_data        - Hash of extra information about the scanline
                   5162:                        (see scantron_getfile for more information)
                   5163:     just_header      - True if should not process question answers but only
                   5164:                        the stuff to the left of the answers.
                   5165:  Returns:
                   5166:    Hash containing the result of parsing the scanline
                   5167: 
                   5168:    Keys are all proceeded by the string 'scantron.'
                   5169: 
                   5170:        CODE    - the CODE in use for this scanline
                   5171:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5172:                  by the operator
                   5173:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5174:                             CODEs were selected, but the usage has been
                   5175:                             forced by the operator
                   5176:        ID  - student ID
                   5177:        PaperID - if used, the ID number printed on the sheet when the 
                   5178:                  paper was scanned
                   5179:        FirstName - first name from the sheet
                   5180:        LastName  - last name from the sheet
                   5181: 
                   5182:      if just_header was not true these key may also exist
                   5183: 
1.447     foxr     5184:        missingerror - a list of bubble ranges that are considered to be answers
                   5185:                       to a single question that don't have any bubbles filled in.
                   5186:                       Of the form questionnumber:firstbubblenumber:count.
                   5187:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5188:                       to a single question that have more than one bubble filled in.
                   5189:                       Of the form questionnumber::firstbubblenumber:count
                   5190:    
                   5191:                 In the above, count is the number of bubble responses in the
                   5192:                 input line needed to represent the possible answers to the question.
                   5193:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5194:                 per line would have count = 2.
                   5195: 
1.423     albertel 5196:        maxquest     - the number of the last bubble line that was parsed
                   5197: 
                   5198:        (<number> starts at 1)
                   5199:        <number>.answer - zero or more letters representing the selected
                   5200:                          letters from the scanline for the bubble line 
                   5201:                          <number>.
                   5202:                          if blank there was either no bubble or there where
                   5203:                          multiple bubbles, (consult the keys missingerror and
                   5204:                          doubleerror if this is an error condition)
                   5205: 
                   5206: =cut
                   5207: 
1.82      albertel 5208: sub scantron_parse_scanline {
1.423     albertel 5209:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5210:     my %record;
1.422     foxr     5211:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5212:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5213:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5214: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5215: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5216: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5217: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5218: 	    $record{'scantron.CODE'}=substr($data,
                   5219: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5220: 					    $$scantron_config{'CODElength'});
1.191     albertel 5221: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5222: 		$record{'scantron.useCODE'}=1;
                   5223: 	    }
1.192     albertel 5224: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5225: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5226: 	    }
1.82      albertel 5227: 	} else {
                   5228: 	    #FIXME interpret first N questions
                   5229: 	}
                   5230:     }
1.83      albertel 5231:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5232: 				  $$scantron_config{'IDlength'});
1.157     albertel 5233:     $record{'scantron.PaperID'}=
                   5234: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5235: 	       $$scantron_config{'PaperIDlength'});
                   5236:     $record{'scantron.FirstName'}=
                   5237: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5238: 	       $$scantron_config{'FirstNamelength'});
                   5239:     $record{'scantron.LastName'}=
                   5240: 	substr($data,$$scantron_config{'LastName'}-1,
                   5241: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5242:     if ($just_header) { return \%record; }
1.194     albertel 5243: 
1.82      albertel 5244:     my @alphabet=('A'..'Z');
                   5245:     my $questnum=0;
1.447     foxr     5246:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5247: 
1.82      albertel 5248:     while ($questions) {
1.447     foxr     5249: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5250: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5251: 
                   5252: 
                   5253: 
1.82      albertel 5254: 	$questnum++;
1.447     foxr     5255: 	my $currentquest = substr($questions,0,$answer_length);
                   5256: 	$questions       = substr($questions,0,$answer_length)='';
                   5257: 	if (length($currentquest) < $answer_length) { next; }
                   5258: 
                   5259: 	# Qon letter implies for each slot in currentquest we have:
                   5260: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5261:         #    about anything else (esp. a value of Qoff for missing
                   5262: 	#    bubbles.
                   5263: 
                   5264: 
1.239     albertel 5265: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5266: 
                   5267: 	    if ($currentquest =~ /\?/
                   5268: 		|| $currentquest =~ /\*/
                   5269: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5270: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5271: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5272: 		    $record{"scantron.$ansnum.answer"}='';
                   5273: 		    $ansnum++;
                   5274: 		}
                   5275: 
1.389     albertel 5276: 	    } elsif (!defined($currentquest)
1.447     foxr     5277: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5278: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5279: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5280: 		    $record{"scantron.$ansnum.answer"}='';
                   5281: 		    $ansnum++;
                   5282: 
                   5283: 		}
1.239     albertel 5284: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5285: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5286: 		    $ansnum += $answers_needed;
1.239     albertel 5287: 		}
1.447     foxr     5288: 
1.239     albertel 5289: 	    } else {
1.447     foxr     5290: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5291: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5292: 		    $ansnum++;
                   5293: 		}
1.239     albertel 5294: 	    }
1.447     foxr     5295: 
                   5296: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5297: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5298:         #    and *? for double bubbles on a line.
                   5299: 	#    these answers are also stored as letters.
                   5300: 
1.239     albertel 5301: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5302: 	    if ($currentquest =~ /\?/
                   5303: 		|| $currentquest =~ /\*/
                   5304: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5305: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5306: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5307: 		    $record{"scantron.$ansnum.answer"}='';
                   5308: 		    $ansnum++;
                   5309: 		}
                   5310: 
1.389     albertel 5311: 	    } elsif (!defined($currentquest)
1.447     foxr     5312: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5313: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5314: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5315: 		    $record{"scantron.$ansnum.answer"}='';
                   5316: 		    $ansnum++;
                   5317: 
                   5318: 		}
1.239     albertel 5319: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5320: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5321: 		    $ansnum += $answers_needed;
1.239     albertel 5322: 		}
1.447     foxr     5323: 
1.239     albertel 5324: 	    } else {
1.447     foxr     5325: 		$currentquest = &digits_to_letters($currentquest);
                   5326: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5327: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5328: 		    $ansnum++;
1.371     albertel 5329: 		}
1.239     albertel 5330: 	    }
1.82      albertel 5331: 	} else {
1.447     foxr     5332: 
                   5333: 	    # Otherwise there's a positional notation;
                   5334: 	    # each bubble line requires Qlength items, and there are filled in
                   5335: 	    # bubbles for each case where there 'Qon' characters.
                   5336: 	    #
                   5337: 
1.239     albertel 5338: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5339: 
                   5340: 	    # If the split only  giveas us one element.. the full length of the
                   5341: 	    # answser string, no bubbles are filled in:
                   5342: 
                   5343: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5344: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5345: 		    $record{"scantron.$ansnum.answer"}='';
                   5346: 		    $ansnum++;
                   5347: 
                   5348: 		}
1.239     albertel 5349: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5350: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5351: 		}
1.447     foxr     5352: 	    } elsif (scalar(@array) lt 2) {
                   5353: 
                   5354: 		my $location      = [length($array[0])];
                   5355: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5356: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5357: 
                   5358: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5359: 		    if ($ans eq $line_num) {
                   5360: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5361: 		    } else {
                   5362: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5363: 		    }
                   5364: 		    $ansnum++;
                   5365: 		}
1.239     albertel 5366: 	    }
1.447     foxr     5367: 	    #  If there's more than one instance of a bubble character
                   5368: 	    #  That's a double bubble; with positional notation we can
                   5369: 	    #  record all the bubbles filled in as well as the 
                   5370: 	    #  fact this response consists of multiple bubbles.
                   5371: 	    #
                   5372: 	    else {
1.239     albertel 5373: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5374: 
                   5375: 		my $first_answer = $ansnum;
                   5376: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5377: 		    $record{"scantron.$ansnum.answer"} = '';
                   5378: 		    $ans++;
                   5379: 		}
                   5380: 
1.239     albertel 5381: 		my @ans=@array;
                   5382: 		my $i=length($ans[0]);shift(@ans);
                   5383: 		while ($#ans) {
                   5384: 		    $i+=length($ans[0])+1;
1.447     foxr     5385: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5386: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5387: 
                   5388: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5389: 		    shift(@ans);
                   5390: 		}
                   5391: 	    }
1.82      albertel 5392: 	}
                   5393:     }
1.83      albertel 5394:     $record{'scantron.maxquest'}=$questnum;
                   5395:     return \%record;
1.82      albertel 5396: }
                   5397: 
1.423     albertel 5398: =pod
                   5399: 
                   5400: =item scantron_add_delay
                   5401: 
                   5402:    Adds an error message that occurred during the grading phase to a
                   5403:    queue of messages to be shown after grading pass is complete
                   5404: 
                   5405:  Arguments:
1.424     albertel 5406:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5407:    $scanline    - the scanline that caused the error
                   5408:    $errormesage - the error message
                   5409:    $errorcode   - a numeric code for the error
                   5410: 
                   5411:  Side Effects:
1.424     albertel 5412:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5413: 
                   5414: =cut
                   5415: 
1.82      albertel 5416: sub scantron_add_delay {
1.140     albertel 5417:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5418:     push(@$delayqueue,
                   5419: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5420: 	  'ecode' => $errorcode }
                   5421: 	 );
1.82      albertel 5422: }
                   5423: 
1.423     albertel 5424: =pod
                   5425: 
                   5426: =item scantron_find_student
                   5427: 
1.424     albertel 5428:    Finds the username for the current scanline
                   5429: 
                   5430:   Arguments:
                   5431:    $scantron_record - hash result from scantron_parse_scanline
                   5432:    $scan_data       - hash of correction information 
                   5433:                       (see &scantron_getfile() form more information)
                   5434:    $idmap           - hash from &username_to_idmap()
                   5435:    $line            - number of current scanline
                   5436:  
                   5437:   Returns:
                   5438:    Either 'username:domain' or undef if unknown
                   5439: 
1.423     albertel 5440: =cut
                   5441: 
1.82      albertel 5442: sub scantron_find_student {
1.157     albertel 5443:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5444:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5445:     if ($scanID =~ /^\s*$/) {
                   5446:  	return &scan_data($scan_data,"$line.user");
                   5447:     }
1.83      albertel 5448:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5449:  	if (lc($id) eq lc($scanID)) {
                   5450:  	    return $$idmap{$id};
                   5451:  	}
1.83      albertel 5452:     }
                   5453:     return undef;
                   5454: }
                   5455: 
1.423     albertel 5456: =pod
                   5457: 
                   5458: =item scantron_filter
                   5459: 
1.424     albertel 5460:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5461:    hidden resources was selected
                   5462: 
1.423     albertel 5463: =cut
                   5464: 
1.83      albertel 5465: sub scantron_filter {
                   5466:     my ($curres)=@_;
1.331     albertel 5467: 
                   5468:     if (ref($curres) && $curres->is_problem()) {
                   5469: 	# if the user has asked to not have either hidden
                   5470: 	# or 'randomout' controlled resources to be graded
                   5471: 	# don't include them
                   5472: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5473: 	    && $curres->randomout) {
                   5474: 	    return 0;
                   5475: 	}
1.83      albertel 5476: 	return 1;
                   5477:     }
                   5478:     return 0;
1.82      albertel 5479: }
                   5480: 
1.423     albertel 5481: =pod
                   5482: 
                   5483: =item scantron_process_corrections
                   5484: 
1.424     albertel 5485:    Gets correction information out of submitted form data and corrects
                   5486:    the scanline
                   5487: 
1.423     albertel 5488: =cut
                   5489: 
1.157     albertel 5490: sub scantron_process_corrections {
                   5491:     my ($r) = @_;
1.257     albertel 5492:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5493:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5494:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5495:     my $which=$env{'form.scantron_line'};
1.200     albertel 5496:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5497:     my ($skip,$err,$errmsg);
1.257     albertel 5498:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5499: 	$skip=1;
1.257     albertel 5500:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5501: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5502: 	    $env{'form.scantron_domain'};
1.157     albertel 5503: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5504: 	($line,$err,$errmsg)=
                   5505: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5506: 				     'ID',{'newid'=>$newid,
1.257     albertel 5507: 				    'username'=>$env{'form.scantron_username'},
                   5508: 				    'domain'=>$env{'form.scantron_domain'}});
                   5509:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5510: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5511: 	my $newCODE;
1.192     albertel 5512: 	my %args;
1.190     albertel 5513: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5514: 	    $newCODE='use_unfound';
1.190     albertel 5515: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5516: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5517: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5518: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5519: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5520: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5521: 	}
1.257     albertel 5522: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5523: 	    $args{'CODE_ignore_dup'}=1;
                   5524: 	}
                   5525: 	$args{'CODE'}=$newCODE;
1.186     albertel 5526: 	($line,$err,$errmsg)=
                   5527: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5528: 				     'CODE',\%args);
1.257     albertel 5529:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5530: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5531: 	    ($line,$err,$errmsg)=
                   5532: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5533: 					 $which,'answer',
                   5534: 					 { 'question'=>$question,
1.257     albertel 5535: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5536: 	    if ($err) { last; }
                   5537: 	}
                   5538:     }
                   5539:     if ($err) {
1.398     albertel 5540: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5541:     } else {
1.200     albertel 5542: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5543: 	&scantron_putfile($scanlines,$scan_data);
                   5544:     }
                   5545: }
                   5546: 
1.423     albertel 5547: =pod
                   5548: 
                   5549: =item reset_skipping_status
                   5550: 
1.424     albertel 5551:    Forgets the current set of remember skipped scanlines (and thus
                   5552:    reverts back to considering all lines in the
                   5553:    scantron_skipped_<filename> file)
                   5554: 
1.423     albertel 5555: =cut
                   5556: 
1.200     albertel 5557: sub reset_skipping_status {
                   5558:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5559:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5560:     &scantron_putfile(undef,$scan_data);
                   5561: }
                   5562: 
1.423     albertel 5563: =pod
                   5564: 
                   5565: =item start_skipping
                   5566: 
1.424     albertel 5567:    Marks a scanline to be skipped. 
                   5568: 
1.423     albertel 5569: =cut
                   5570: 
1.376     albertel 5571: sub start_skipping {
1.200     albertel 5572:     my ($scan_data,$i)=@_;
                   5573:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5574:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5575: 	$remembered{$i}=2;
                   5576:     } else {
                   5577: 	$remembered{$i}=1;
                   5578:     }
1.200     albertel 5579:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5580: }
                   5581: 
1.423     albertel 5582: =pod
                   5583: 
                   5584: =item should_be_skipped
                   5585: 
1.424     albertel 5586:    Checks whether a scanline should be skipped.
                   5587: 
1.423     albertel 5588: =cut
                   5589: 
1.200     albertel 5590: sub should_be_skipped {
1.376     albertel 5591:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5592:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5593: 	# not redoing old skips
1.376     albertel 5594: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5595: 	return 0;
                   5596:     }
                   5597:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5598: 
                   5599:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5600: 	return 0;
                   5601:     }
1.200     albertel 5602:     return 1;
                   5603: }
                   5604: 
1.423     albertel 5605: =pod
                   5606: 
                   5607: =item remember_current_skipped
                   5608: 
1.424     albertel 5609:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5610:    file and remembers them into scan_data for later use.
                   5611: 
1.423     albertel 5612: =cut
                   5613: 
1.200     albertel 5614: sub remember_current_skipped {
                   5615:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5616:     my %to_remember;
                   5617:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5618: 	if ($scanlines->{'skipped'}[$i]) {
                   5619: 	    $to_remember{$i}=1;
                   5620: 	}
                   5621:     }
1.376     albertel 5622: 
1.200     albertel 5623:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5624:     &scantron_putfile(undef,$scan_data);
                   5625: }
                   5626: 
1.423     albertel 5627: =pod
                   5628: 
                   5629: =item check_for_error
                   5630: 
1.424     albertel 5631:     Checks if there was an error when attempting to remove a specific
                   5632:     scantron_.. bubble sheet data file. Prints out an error if
                   5633:     something went wrong.
                   5634: 
1.423     albertel 5635: =cut
                   5636: 
1.200     albertel 5637: sub check_for_error {
                   5638:     my ($r,$result)=@_;
                   5639:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5640: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5641:     }
                   5642: }
1.157     albertel 5643: 
1.423     albertel 5644: =pod
                   5645: 
                   5646: =item scantron_warning_screen
                   5647: 
1.424     albertel 5648:    Interstitial screen to make sure the operator has selected the
                   5649:    correct options before we start the validation phase.
                   5650: 
1.423     albertel 5651: =cut
                   5652: 
1.203     albertel 5653: sub scantron_warning_screen {
                   5654:     my ($button_text)=@_;
1.257     albertel 5655:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5656:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5657:     my $CODElist;
1.284     albertel 5658:     if ($scantron_config{'CODElocation'} &&
                   5659: 	$scantron_config{'CODEstart'} &&
                   5660: 	$scantron_config{'CODElength'}) {
                   5661: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5662: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5663: 	$CODElist=
                   5664: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5665: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5666:     }
1.203     albertel 5667:     return (<<STUFF);
                   5668: <p>
1.398     albertel 5669: <span class="LC_warning">Please double check the information
                   5670:                  below before clicking on '$button_text'</span>
1.203     albertel 5671: </p>
                   5672: <table>
1.284     albertel 5673: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5674: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5675: $CODElist
1.203     albertel 5676: </table>
                   5677: <br />
                   5678: <p> If this information is correct, please click on '$button_text'.</p>
                   5679: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5680: 
                   5681: <br />
                   5682: STUFF
                   5683: }
                   5684: 
1.423     albertel 5685: =pod
                   5686: 
                   5687: =item scantron_do_warning
                   5688: 
1.424     albertel 5689:    Check if the operator has picked something for all required
                   5690:    fields. Error out if something is missing.
                   5691: 
1.423     albertel 5692: =cut
                   5693: 
1.203     albertel 5694: sub scantron_do_warning {
                   5695:     my ($r)=@_;
1.324     albertel 5696:     my ($symb)=&get_symb($r);
1.203     albertel 5697:     if (!$symb) {return '';}
1.324     albertel 5698:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5699:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5700:     if ( $env{'form.selectpage'} eq '' ||
                   5701: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5702: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5703: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5704: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5705: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5706: 	} 
1.257     albertel 5707: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5708: 	    $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 5709: 	} 
1.257     albertel 5710: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5711: 	    $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 5712: 	} 
                   5713:     } else {
1.265     www      5714: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5715: 	$r->print(<<STUFF);
1.203     albertel 5716: $warning
1.265     www      5717: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5718: <input type="hidden" name="command" value="scantron_validate" />
                   5719: STUFF
1.237     albertel 5720:     }
1.352     albertel 5721:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5722:     return '';
                   5723: }
                   5724: 
1.423     albertel 5725: =pod
                   5726: 
                   5727: =item scantron_form_start
                   5728: 
1.424     albertel 5729:     html hidden input for remembering all selected grading options
                   5730: 
1.423     albertel 5731: =cut
                   5732: 
1.203     albertel 5733: sub scantron_form_start {
                   5734:     my ($max_bubble)=@_;
                   5735:     my $result= <<SCANTRONFORM;
                   5736: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5737:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5738:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5739:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5740:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5741:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5742:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5743:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5744:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5745:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5746: SCANTRONFORM
1.447     foxr     5747: 
                   5748:   my $line = 0;
                   5749:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448     foxr     5750: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5751:        my $chunk =
                   5752: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5753:        $chunk .=
                   5754: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5755:        $result .= $chunk;
                   5756:        $line++;
                   5757:    }
1.203     albertel 5758:     return $result;
                   5759: }
                   5760: 
1.423     albertel 5761: =pod
                   5762: 
                   5763: =item scantron_validate_file
                   5764: 
1.424     albertel 5765:     Dispatch routine for doing validation of a bubble sheet data file.
                   5766: 
                   5767:     Also processes any necessary information resets that need to
                   5768:     occur before validation begins (ignore previous corrections,
                   5769:     restarting the skipped records processing)
                   5770: 
1.423     albertel 5771: =cut
                   5772: 
1.157     albertel 5773: sub scantron_validate_file {
                   5774:     my ($r) = @_;
1.324     albertel 5775:     my ($symb)=&get_symb($r);
1.157     albertel 5776:     if (!$symb) {return '';}
1.324     albertel 5777:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5778:     
                   5779:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5780:     # them when doing the corrections reset
1.257     albertel 5781:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5782: 	&reset_skipping_status();
                   5783:     }
1.257     albertel 5784:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5785: 	&remember_current_skipped();
1.257     albertel 5786: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5787:     }
                   5788: 
1.257     albertel 5789:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5790: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5791: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5792: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5793: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5794:     }
1.200     albertel 5795: 
1.257     albertel 5796:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5797: 	&scantron_process_corrections($r);
                   5798:     }
1.424     albertel 5799:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5800:     #get the student pick code ready
                   5801:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5802:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5803:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5804:     $r->print($result);
                   5805:     
1.334     albertel 5806:     my @validate_phases=( 'sequence',
                   5807: 			  'ID',
1.157     albertel 5808: 			  'CODE',
                   5809: 			  'doublebubble',
                   5810: 			  'missingbubbles');
1.257     albertel 5811:     if (!$env{'form.validatepass'}) {
                   5812: 	$env{'form.validatepass'} = 0;
1.157     albertel 5813:     }
1.257     albertel 5814:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5815: 
1.448     foxr     5816:     &Apache::lonnet::logthis("Phase: $currentphase");
                   5817: 
1.157     albertel 5818:     my $stop=0;
                   5819:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5820: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5821: 	$r->rflush();
                   5822: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5823: 	{
                   5824: 	    no strict 'refs';
                   5825: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5826: 	}
                   5827:     }
                   5828:     if (!$stop) {
1.203     albertel 5829: 	my $warning=&scantron_warning_screen('Start Grading');
                   5830: 	$r->print(<<STUFF);
                   5831: Validation process complete.<br />
                   5832: $warning
                   5833: <input type="submit" name="submit" value="Start Grading" />
                   5834: <input type="hidden" name="command" value="scantron_process" />
                   5835: STUFF
                   5836: 
1.157     albertel 5837:     } else {
                   5838: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5839: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5840:     }
                   5841:     if ($stop) {
1.334     albertel 5842: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5843: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5844: 	    $r->print(' this error <br />');
                   5845: 
                   5846: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5847: 	} else {
                   5848: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5849: 	    $r->print(' using corrected info <br />');
                   5850: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5851: 	    $r->print(" this scanline saving it for later.");
                   5852: 	}
1.157     albertel 5853:     }
1.352     albertel 5854:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5855:     return '';
                   5856: }
                   5857: 
1.423     albertel 5858: 
                   5859: =pod
                   5860: 
                   5861: =item scantron_remove_file
                   5862: 
1.424     albertel 5863:    Removes the requested bubble sheet data file, makes sure that
                   5864:    scantron_original_<filename> is never removed
                   5865: 
                   5866: 
1.423     albertel 5867: =cut
                   5868: 
1.200     albertel 5869: sub scantron_remove_file {
1.192     albertel 5870:     my ($which)=@_;
1.257     albertel 5871:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5872:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5873:     my $file='scantron_';
1.200     albertel 5874:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5875: 	$file.=$which.'_';
1.192     albertel 5876:     } else {
                   5877: 	return 'refused';
                   5878:     }
1.257     albertel 5879:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5880:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5881: }
                   5882: 
1.423     albertel 5883: 
                   5884: =pod
                   5885: 
                   5886: =item scantron_remove_scan_data
                   5887: 
1.424     albertel 5888:    Removes all scan_data correction for the requested bubble sheet
                   5889:    data file.  (In the case that both the are doing skipped records we need
                   5890:    to remember the old skipped lines for the time being so that element
                   5891:    persists for a while.)
                   5892: 
1.423     albertel 5893: =cut
                   5894: 
1.200     albertel 5895: sub scantron_remove_scan_data {
1.257     albertel 5896:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5897:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5898:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5899:     my @todelete;
1.257     albertel 5900:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5901:     foreach my $key (@keys) {
                   5902: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5903: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5904: 		$key=~/remember_skipping/) {
                   5905: 		next;
                   5906: 	    }
1.192     albertel 5907: 	    push(@todelete,$key);
                   5908: 	}
                   5909:     }
1.200     albertel 5910:     my $result;
1.192     albertel 5911:     if (@todelete) {
1.200     albertel 5912: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5913:     }
                   5914:     return $result;
                   5915: }
                   5916: 
1.423     albertel 5917: 
                   5918: =pod
                   5919: 
                   5920: =item scantron_getfile
                   5921: 
1.424     albertel 5922:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5923:     the scan_data hash
                   5924:   
                   5925:   Arguments:
                   5926:     None
                   5927: 
                   5928:   Returns:
                   5929:     2 hash references
                   5930: 
                   5931:      - first one has 
                   5932:          orig      -
                   5933:          corrected -
                   5934:          skipped   -  each of which points to an array ref of the specified
                   5935:                       file broken up into individual lines
                   5936:          count     - number of scanlines
                   5937:  
                   5938:      - second is the scan_data hash possible keys are
1.425     albertel 5939:        ($number refers to scanline numbered $number and thus the key affects
                   5940:         only that scanline
                   5941:         $bubline refers to the specific bubble line element and the aspects
                   5942:         refers to that specific bubble line element)
                   5943: 
                   5944:        $number.user - username:domain to use
                   5945:        $number.CODE_ignore_dup 
                   5946:                     - ignore the duplicate CODE error 
                   5947:        $number.useCODE
                   5948:                     - use the CODE in the scanline as is
                   5949:        $number.no_bubble.$bubline
                   5950:                     - it is valid that there is no bubbled in bubble
                   5951:                       at $number $bubline
                   5952:        remember_skipping
                   5953:                     - a frozen hash containing keys of $number and values
                   5954:                       of either 
                   5955:                         1 - we are on a 'do skipped records pass' and plan
                   5956:                             on processing this line
                   5957:                         2 - we are on a 'do skipped records pass' and this
                   5958:                             scanline has been marked to skip yet again
1.424     albertel 5959: 
1.423     albertel 5960: =cut
                   5961: 
1.157     albertel 5962: sub scantron_getfile {
1.200     albertel 5963:     #FIXME really would prefer a scantron directory
1.257     albertel 5964:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5965:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5966:     my $lines;
                   5967:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5968: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5969:     my %scanlines;
                   5970:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5971:     my $temp=$scanlines{'orig'};
                   5972:     $scanlines{'count'}=$#$temp;
                   5973: 
                   5974:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5975: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5976:     if ($lines eq '-1') {
                   5977: 	$scanlines{'corrected'}=[];
                   5978:     } else {
                   5979: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5980:     }
                   5981:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5982: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5983:     if ($lines eq '-1') {
                   5984: 	$scanlines{'skipped'}=[];
                   5985:     } else {
                   5986: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5987:     }
1.175     albertel 5988:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5989:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5990:     my %scan_data = @tmp;
                   5991:     return (\%scanlines,\%scan_data);
                   5992: }
                   5993: 
1.423     albertel 5994: =pod
                   5995: 
                   5996: =item lonnet_putfile
                   5997: 
1.424     albertel 5998:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5999: 
                   6000:  Arguments:
                   6001:    $contents - data to store
                   6002:    $filename - filename to store $contents into
                   6003: 
                   6004:  Returns:
                   6005:    result value from &Apache::lonnet::finishuserfileupload
                   6006: 
1.423     albertel 6007: =cut
                   6008: 
1.157     albertel 6009: sub lonnet_putfile {
                   6010:     my ($contents,$filename)=@_;
1.257     albertel 6011:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6012:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6013:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6014:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6015: 
                   6016: }
                   6017: 
1.423     albertel 6018: =pod
                   6019: 
                   6020: =item scantron_putfile
                   6021: 
1.424     albertel 6022:     Stores the current version of the bubble sheet data files, and the
                   6023:     scan_data hash. (Does not modify the original version only the
                   6024:     corrected and skipped versions.
                   6025: 
                   6026:  Arguments:
                   6027:     $scanlines - hash ref that looks like the first return value from
                   6028:                  &scantron_getfile()
                   6029:     $scan_data - hash ref that looks like the second return value from
                   6030:                  &scantron_getfile()
                   6031: 
1.423     albertel 6032: =cut
                   6033: 
1.157     albertel 6034: sub scantron_putfile {
                   6035:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6036:     #FIXME really would prefer a scantron directory
1.257     albertel 6037:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6038:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6039:     if ($scanlines) {
                   6040: 	my $prefix='scantron_';
1.157     albertel 6041: # no need to update orig, shouldn't change
                   6042: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6043: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6044: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6045: 			$prefix.'corrected_'.
1.257     albertel 6046: 			$env{'form.scantron_selectfile'});
1.200     albertel 6047: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6048: 			$prefix.'skipped_'.
1.257     albertel 6049: 			$env{'form.scantron_selectfile'});
1.200     albertel 6050:     }
1.175     albertel 6051:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6052: }
                   6053: 
1.423     albertel 6054: =pod
                   6055: 
                   6056: =item scantron_get_line
                   6057: 
1.424     albertel 6058:    Returns the correct version of the scanline
                   6059: 
                   6060:  Arguments:
                   6061:     $scanlines - hash ref that looks like the first return value from
                   6062:                  &scantron_getfile()
                   6063:     $scan_data - hash ref that looks like the second return value from
                   6064:                  &scantron_getfile()
                   6065:     $i         - number of the requested line (starts at 0)
                   6066: 
                   6067:  Returns:
                   6068:    A scanline, (either the original or the corrected one if it
                   6069:    exists), or undef if the requested scanline should be
                   6070:    skipped. (Either because it's an skipped scanline, or it's an
                   6071:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6072:    pass.
                   6073: 
1.423     albertel 6074: =cut
                   6075: 
1.157     albertel 6076: sub scantron_get_line {
1.200     albertel 6077:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6078:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6079:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6080:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6081:     return $scanlines->{'orig'}[$i]; 
                   6082: }
                   6083: 
1.423     albertel 6084: =pod
                   6085: 
                   6086: =item scantron_todo_count
                   6087: 
1.424     albertel 6088:     Counts the number of scanlines that need processing.
                   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: 
                   6096:  Returns:
                   6097:     $count - number of scanlines to process
                   6098: 
1.423     albertel 6099: =cut
                   6100: 
1.200     albertel 6101: sub get_todo_count {
                   6102:     my ($scanlines,$scan_data)=@_;
                   6103:     my $count=0;
                   6104:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6105: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6106: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6107: 	$count++;
                   6108:     }
                   6109:     return $count;
                   6110: }
                   6111: 
1.423     albertel 6112: =pod
                   6113: 
                   6114: =item scantron_put_line
                   6115: 
1.424     albertel 6116:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6117:     data file.
                   6118: 
                   6119:  Arguments:
                   6120:     $scanlines - hash ref that looks like the first return value from
                   6121:                  &scantron_getfile()
                   6122:     $scan_data - hash ref that looks like the second return value from
                   6123:                  &scantron_getfile()
                   6124:     $i         - line number to update
                   6125:     $newline   - contents of the updated scanline
                   6126:     $skip      - if true make the line for skipping and update the
                   6127:                  'skipped' file
                   6128: 
1.423     albertel 6129: =cut
                   6130: 
1.157     albertel 6131: sub scantron_put_line {
1.200     albertel 6132:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6133:     if ($skip) {
                   6134: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6135: 	&start_skipping($scan_data,$i);
1.157     albertel 6136: 	return;
                   6137:     }
                   6138:     $scanlines->{'corrected'}[$i]=$newline;
                   6139: }
                   6140: 
1.423     albertel 6141: =pod
                   6142: 
                   6143: =item scantron_clear_skip
                   6144: 
1.424     albertel 6145:    Remove a line from the 'skipped' file
                   6146: 
                   6147:  Arguments:
                   6148:     $scanlines - hash ref that looks like the first return value from
                   6149:                  &scantron_getfile()
                   6150:     $scan_data - hash ref that looks like the second return value from
                   6151:                  &scantron_getfile()
                   6152:     $i         - line number to update
                   6153: 
1.423     albertel 6154: =cut
                   6155: 
1.376     albertel 6156: sub scantron_clear_skip {
                   6157:     my ($scanlines,$scan_data,$i)=@_;
                   6158:     if (exists($scanlines->{'skipped'}[$i])) {
                   6159: 	undef($scanlines->{'skipped'}[$i]);
                   6160: 	return 1;
                   6161:     }
                   6162:     return 0;
                   6163: }
                   6164: 
1.423     albertel 6165: =pod
                   6166: 
                   6167: =item scantron_filter_not_exam
                   6168: 
1.424     albertel 6169:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6170:    filter out resources that are not marked as 'exam' mode
                   6171: 
1.423     albertel 6172: =cut
                   6173: 
1.334     albertel 6174: sub scantron_filter_not_exam {
                   6175:     my ($curres)=@_;
                   6176:     
                   6177:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6178: 	# if the user has asked to not have either hidden
                   6179: 	# or 'randomout' controlled resources to be graded
                   6180: 	# don't include them
                   6181: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6182: 	    && $curres->randomout) {
                   6183: 	    return 0;
                   6184: 	}
                   6185: 	return 1;
                   6186:     }
                   6187:     return 0;
                   6188: }
                   6189: 
1.423     albertel 6190: =pod
                   6191: 
                   6192: =item scantron_validate_sequence
                   6193: 
1.424     albertel 6194:     Validates the selected sequence, checking for resource that are
                   6195:     not set to exam mode.
                   6196: 
1.423     albertel 6197: =cut
                   6198: 
1.334     albertel 6199: sub scantron_validate_sequence {
                   6200:     my ($r,$currentphase) = @_;
                   6201: 
                   6202:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6203:     my (undef,undef,$sequence)=
                   6204: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6205: 
                   6206:     my $map=$navmap->getResourceByUrl($sequence);
                   6207: 
                   6208:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6209:                                     value="ignore" />');
                   6210:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6211: 	my @resources=
                   6212: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6213: 	if (@resources) {
1.357     banghart 6214: 	    $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 6215: 	    return (1,$currentphase);
                   6216: 	}
                   6217:     }
                   6218: 
                   6219:     return (0,$currentphase+1);
                   6220: }
                   6221: 
1.423     albertel 6222: =pod
                   6223: 
                   6224: =item scantron_validate_ID
                   6225: 
1.424     albertel 6226:    Validates all scanlines in the selected file to not have any
                   6227:    invalid or underspecified student IDs
                   6228: 
1.423     albertel 6229: =cut
                   6230: 
1.157     albertel 6231: sub scantron_validate_ID {
                   6232:     my ($r,$currentphase) = @_;
                   6233:     
                   6234:     #get student info
                   6235:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6236:     my %idmap=&username_to_idmap($classlist);
                   6237: 
                   6238:     #get scantron line setup
1.257     albertel 6239:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6240:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6241:     
                   6242:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6243: 
                   6244:     my %found=('ids'=>{},'usernames'=>{});
                   6245:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6246: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6247: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6248: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6249: 						 $scan_data);
                   6250: 	my $id=$$scan_record{'scantron.ID'};
                   6251: 	my $found;
                   6252: 	foreach my $checkid (keys(%idmap)) {
                   6253: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6254: 	}
                   6255: 	if ($found) {
                   6256: 	    my $username=$idmap{$found};
                   6257: 	    if ($found{'ids'}{$found}) {
                   6258: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6259: 					 $line,'duplicateID',$found);
1.194     albertel 6260: 		return(1,$currentphase);
1.157     albertel 6261: 	    } elsif ($found{'usernames'}{$username}) {
                   6262: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6263: 					 $line,'duplicateID',$username);
1.194     albertel 6264: 		return(1,$currentphase);
1.157     albertel 6265: 	    }
1.186     albertel 6266: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6267: 	    $found{'ids'}{$found}++;
                   6268: 	    $found{'usernames'}{$username}++;
                   6269: 	} else {
                   6270: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6271: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6272: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6273: 		    &scantron_get_correction($r,$i,$scan_record,
                   6274: 					     \%scantron_config,
                   6275: 					     $line,'duplicateID',$username);
1.194     albertel 6276: 		    return(1,$currentphase);
1.157     albertel 6277: 		} elsif (!defined($username)) {
                   6278: 		    &scantron_get_correction($r,$i,$scan_record,
                   6279: 					     \%scantron_config,
                   6280: 					     $line,'incorrectID');
1.194     albertel 6281: 		    return(1,$currentphase);
1.157     albertel 6282: 		}
                   6283: 		$found{'usernames'}{$username}++;
                   6284: 	    } else {
                   6285: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6286: 					 $line,'incorrectID');
1.194     albertel 6287: 		return(1,$currentphase);
1.157     albertel 6288: 	    }
                   6289: 	}
                   6290:     }
                   6291: 
                   6292:     return (0,$currentphase+1);
                   6293: }
                   6294: 
1.423     albertel 6295: =pod
                   6296: 
                   6297: =item scantron_get_correction
                   6298: 
1.424     albertel 6299:    Builds the interface screen to interact with the operator to fix a
                   6300:    specific error condition in a specific scanline
                   6301: 
                   6302:  Arguments:
                   6303:     $r           - Apache request object
                   6304:     $i           - number of the current scanline
                   6305:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6306:     $scan_config - hash ref as returned from &get_scantron_config()
                   6307:     $line        - full contents of the current scanline
                   6308:     $error       - error condition, valid values are
                   6309:                    'incorrectCODE', 'duplicateCODE',
                   6310:                    'doublebubble', 'missingbubble',
                   6311:                    'duplicateID', 'incorrectID'
                   6312:     $arg         - extra information needed
                   6313:        For errors:
                   6314:          - duplicateID   - paper number that this studentID was seen before on
                   6315:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6316:                            seen on before
                   6317:          - incorrectCODE - current incorrect CODE 
                   6318:          - doublebubble  - array ref of the bubble lines that have double
                   6319:                            bubble errors
                   6320:          - missingbubble - array ref of the bubble lines that have missing
                   6321:                            bubble errors
                   6322: 
1.423     albertel 6323: =cut
                   6324: 
1.157     albertel 6325: sub scantron_get_correction {
                   6326:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6327: 
1.454   ! banghart 6328: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6329: #to show both the current line and the previous one and allow skipping
                   6330: #the previous one or the current one
                   6331: 
1.161     albertel 6332:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6333:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6334: 	$r->print(" for PaperID <tt>".
                   6335: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6336:     } else {
                   6337: 	$r->print(" in scanline $i <pre>".
                   6338: 		  $line."</pre> \n");
                   6339:     }
1.242     albertel 6340:     my $message="<p>The ID on the form is  <tt>".
                   6341: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6342: 	"The name on the paper is ".
                   6343: 	$$scan_record{'scantron.LastName'}.",".
                   6344: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6345: 
1.157     albertel 6346:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6347:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6348:     if ($error =~ /ID$/) {
1.186     albertel 6349: 	if ($error eq 'incorrectID') {
1.157     albertel 6350: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6351: 	} elsif ($error eq 'duplicateID') {
                   6352: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6353: 	}
1.242     albertel 6354: 	$r->print($message);
1.157     albertel 6355: 	$r->print("<p>How should I handle this? <br /> \n");
                   6356: 	$r->print("\n<ul><li> ");
                   6357: 	#FIXME it would be nice if this sent back the user ID and
                   6358: 	#could do partial userID matches
                   6359: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6360: 				       'scantron_username','scantron_domain'));
                   6361: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6362: 	$r->print("\n@".
1.257     albertel 6363: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6364: 
                   6365: 	$r->print('</li>');
1.186     albertel 6366:     } elsif ($error =~ /CODE$/) {
                   6367: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6368: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6369: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6370: 	    $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 6371: 	}
1.224     albertel 6372: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6373: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6374: 	$r->print($message);
1.186     albertel 6375: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6376: 	$r->print("\n<br /> ");
1.194     albertel 6377: 	my $i=0;
1.273     albertel 6378: 	if ($error eq 'incorrectCODE' 
                   6379: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6380: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6381: 	    if ($closest > 0) {
                   6382: 		foreach my $testcode (@{$closest}) {
                   6383: 		    my $checked='';
1.401     albertel 6384: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6385: 		    $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' />");
                   6386: 		    $r->print("\n<br />");
                   6387: 		    $i++;
                   6388: 		}
1.194     albertel 6389: 	    }
                   6390: 	}
1.273     albertel 6391: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6392: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6393: 	    $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>");
                   6394: 	    $r->print("\n<br />");
                   6395: 	}
1.194     albertel 6396: 
1.188     albertel 6397: 	$r->print(<<ENDSCRIPT);
                   6398: <script type="text/javascript">
                   6399: function change_radio(field) {
1.190     albertel 6400:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6401:     var i;
                   6402:     for (i=0;i<slct.length;i++) {
                   6403:         if (slct[i].value==field) { slct[i].checked=true; }
                   6404:     }
                   6405: }
                   6406: </script>
                   6407: ENDSCRIPT
1.187     albertel 6408: 	my $href="/adm/pickcode?".
1.359     www      6409: 	   "form=".&escape("scantronupload").
                   6410: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6411: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6412: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6413: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6414: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6415: 	    $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')\" />");
                   6416: 	    $r->print("\n<br />");
                   6417: 	}
1.272     albertel 6418: 	$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 6419: 	$r->print("\n<br /><br />");
1.157     albertel 6420:     } elsif ($error eq 'doublebubble') {
                   6421: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6422: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6423: 		  join(',',@{$arg}).'" />');
1.242     albertel 6424: 	$r->print($message);
1.157     albertel 6425: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6426: 	foreach my $question (@{$arg}) {
1.447     foxr     6427: 
                   6428: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6429: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6430: 				      split('',$selected));
1.157     albertel 6431: 	}
                   6432:     } elsif ($error eq 'missingbubble') {
                   6433: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6434: 	$r->print($message);
1.157     albertel 6435: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6436: 	$r->print("Some questions have no scanned bubbles\n");
                   6437: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6438: 		  join(',',@{$arg}).'" />');
                   6439: 	foreach my $question (@{$arg}) {
1.448     foxr     6440: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6441: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6442: 	}
                   6443:     } else {
                   6444: 	$r->print("\n<ul>");
                   6445:     }
                   6446:     $r->print("\n</li></ul>");
                   6447: 
                   6448: }
1.423     albertel 6449: 
                   6450: =pod
                   6451: 
                   6452: =item scantron_bubble_selector
                   6453:   
                   6454:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6455:    possibly showing the existing the selected bubbles if known
1.423     albertel 6456: 
                   6457:  Arguments:
                   6458:     $r           - Apache request object
                   6459:     $scan_config - hash from &get_scantron_config()
                   6460:     $quest       - number of the bubble line to make a corrector for
                   6461:     $selected    - array of letters of previously selected bubbles
                   6462: 
                   6463: =cut
                   6464: 
1.157     albertel 6465: sub scantron_bubble_selector {
1.447     foxr     6466:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6467:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6468: 
                   6469:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6470: 
                   6471: 
1.274     albertel 6472:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6473: 
1.448     foxr     6474:     my $response = $quest-1;
                   6475:     my $lines = $bubble_lines_per_response{$response};
                   6476:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6477: 
1.422     foxr     6478:     my $total_lines = $lines*2;
1.157     albertel 6479:     my @alphabet=('A'..'Z');
1.422     foxr     6480:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6481: 
                   6482:     for (my $l = 0; $l < $lines; $l++) {
                   6483: 	if ($l != 0) {
                   6484: 	    $r->print('<tr>');
                   6485: 	}
                   6486: 
                   6487: 	# FIXME:  This loop probably has to be considerably more clever for
                   6488: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6489: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6490: 
                   6491: 	for (my $i=0;$i<$max;$i++) {
                   6492: 	    $r->print("\n".'<td align="center">');
                   6493: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6494: 		$r->print('X'); 
                   6495: 		shift(@selected) ;
                   6496: 	    } else { 
                   6497: 		$r->print('&nbsp;'); 
                   6498: 	    }
                   6499: 	    $r->print('</td>');
                   6500: 	    
                   6501: 	}
                   6502: 
                   6503: 	if ($l == 0) {
                   6504: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6505: 
                   6506: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6507: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6508: 	
                   6509: 	}
                   6510: 
                   6511: 	$r->print('</tr><tr>');
                   6512: 
                   6513: 	# FIXME: This may have to be a bit more clever for
                   6514: 	#        multiline questions (different values e.g..).
                   6515: 
                   6516: 	for (my $i=0;$i<$max;$i++) {
                   6517: 	    $r->print("\n".
                   6518: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6519: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6520: 	}
                   6521: 	$r->print('</tr>');
                   6522: 
                   6523: 	    
1.157     albertel 6524:     }
1.422     foxr     6525:     $r->print('</table>');
1.157     albertel 6526: }
                   6527: 
1.423     albertel 6528: =pod
                   6529: 
                   6530: =item num_matches
                   6531: 
1.424     albertel 6532:    Counts the number of characters that are the same between the two arguments.
                   6533: 
                   6534:  Arguments:
                   6535:    $orig - CODE from the scanline
                   6536:    $code - CODE to match against
                   6537: 
                   6538:  Returns:
                   6539:    $count - integer count of the number of same characters between the
                   6540:             two arguments
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.194     albertel 6544: sub num_matches {
                   6545:     my ($orig,$code) = @_;
                   6546:     my @code=split(//,$code);
                   6547:     my @orig=split(//,$orig);
                   6548:     my $same=0;
                   6549:     for (my $i=0;$i<scalar(@code);$i++) {
                   6550: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6551:     }
                   6552:     return $same;
                   6553: }
                   6554: 
1.423     albertel 6555: =pod
                   6556: 
                   6557: =item scantron_get_closely_matching_CODEs
                   6558: 
1.424     albertel 6559:    Cycles through all CODEs and finds the set that has the greatest
                   6560:    number of same characters as the provided CODE
                   6561: 
                   6562:  Arguments:
                   6563:    $allcodes - hash ref returned by &get_codes()
                   6564:    $CODE     - CODE from the current scanline
                   6565: 
                   6566:  Returns:
                   6567:    2 element list
                   6568:     - first elements is number of how closely matching the best fit is 
                   6569:       (5 means best set has 5 matching characters)
                   6570:     - second element is an arrary ref containing the set of valid CODEs
                   6571:       that best fit the passed in CODE
                   6572: 
1.423     albertel 6573: =cut
                   6574: 
1.194     albertel 6575: sub scantron_get_closely_matching_CODEs {
                   6576:     my ($allcodes,$CODE)=@_;
                   6577:     my @CODEs;
                   6578:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6579: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6580:     }
                   6581: 
                   6582:     return ($#CODEs,$CODEs[-1]);
                   6583: }
                   6584: 
1.423     albertel 6585: =pod
                   6586: 
                   6587: =item get_codes
                   6588: 
1.424     albertel 6589:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6590:    set of remembered CODEs.
                   6591: 
                   6592:  Arguments:
                   6593:   $old_name - name of the set of remembered CODEs
                   6594:   $cdom     - domain of the course
                   6595:   $cnum     - internal course name
                   6596: 
                   6597:  Returns:
                   6598:   %allcodes - keys are the valid CODEs, values are all 1
                   6599: 
1.423     albertel 6600: =cut
                   6601: 
1.194     albertel 6602: sub get_codes {
1.280     foxr     6603:     my ($old_name, $cdom, $cnum) = @_;
                   6604:     if (!$old_name) {
                   6605: 	$old_name=$env{'form.scantron_CODElist'};
                   6606:     }
                   6607:     if (!$cdom) {
                   6608: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6609:     }
                   6610:     if (!$cnum) {
                   6611: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6612:     }
1.278     albertel 6613:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6614: 				    $cdom,$cnum);
                   6615:     my %allcodes;
                   6616:     if ($result{"type\0$old_name"} eq 'number') {
                   6617: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6618:     } else {
                   6619: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6620:     }
1.194     albertel 6621:     return %allcodes;
                   6622: }
                   6623: 
1.423     albertel 6624: =pod
                   6625: 
                   6626: =item scantron_validate_CODE
                   6627: 
1.424     albertel 6628:    Validates all scanlines in the selected file to not have any
                   6629:    invalid or underspecified CODEs and that none of the codes are
                   6630:    duplicated if this was requested.
                   6631: 
1.423     albertel 6632: =cut
                   6633: 
1.157     albertel 6634: sub scantron_validate_CODE {
                   6635:     my ($r,$currentphase) = @_;
1.257     albertel 6636:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6637:     if ($scantron_config{'CODElocation'} &&
                   6638: 	$scantron_config{'CODEstart'} &&
                   6639: 	$scantron_config{'CODElength'}) {
1.257     albertel 6640: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6641: 	    &FIXME_blow_up()
                   6642: 	}
                   6643:     } else {
                   6644: 	return (0,$currentphase+1);
                   6645:     }
                   6646:     
                   6647:     my %usedCODEs;
                   6648: 
1.194     albertel 6649:     my %allcodes=&get_codes();
1.186     albertel 6650: 
1.447     foxr     6651:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6652: 
1.186     albertel 6653:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6654:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6655: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6656: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6657: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6658: 						 $scan_data);
                   6659: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6660: 	my $error=0;
1.224     albertel 6661: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6662: 	    &scantron_get_correction($r,$i,$scan_record,
                   6663: 				     \%scantron_config,
                   6664: 				     $line,'incorrectCODE',\%allcodes);
                   6665: 	    return(1,$currentphase);
                   6666: 	}
1.221     albertel 6667: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6668: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6669: 	    &scantron_get_correction($r,$i,$scan_record,
                   6670: 				     \%scantron_config,
1.194     albertel 6671: 				     $line,'incorrectCODE',\%allcodes);
                   6672: 	    return(1,$currentphase);
1.186     albertel 6673: 	}
1.214     albertel 6674: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6675: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6676: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6677: 	    &scantron_get_correction($r,$i,$scan_record,
                   6678: 				     \%scantron_config,
1.194     albertel 6679: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6680: 	    return(1,$currentphase);
1.186     albertel 6681: 	}
1.194     albertel 6682: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6683:     }
1.157     albertel 6684:     return (0,$currentphase+1);
                   6685: }
                   6686: 
1.423     albertel 6687: =pod
                   6688: 
                   6689: =item scantron_validate_doublebubble
                   6690: 
1.424     albertel 6691:    Validates all scanlines in the selected file to not have any
                   6692:    bubble lines with multiple bubbles marked.
                   6693: 
1.423     albertel 6694: =cut
                   6695: 
1.157     albertel 6696: sub scantron_validate_doublebubble {
                   6697:     my ($r,$currentphase) = @_;
                   6698:     #get student info
                   6699:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6700:     my %idmap=&username_to_idmap($classlist);
                   6701: 
                   6702:     #get scantron line setup
1.257     albertel 6703:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6704:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6705: 
                   6706:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6707: 
1.157     albertel 6708:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6709: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6710: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6711: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6712: 						 $scan_data);
                   6713: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6714: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6715: 				 'doublebubble',
                   6716: 				 $$scan_record{'scantron.doubleerror'});
                   6717:     	return (1,$currentphase);
                   6718:     }
                   6719:     return (0,$currentphase+1);
                   6720: }
                   6721: 
1.423     albertel 6722: =pod
                   6723: 
                   6724: =item scantron_get_maxbubble
                   6725: 
1.424     albertel 6726:    Returns the maximum number of bubble lines that are expected to
                   6727:    occur. Does this by walking the selected sequence rendering the
                   6728:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6729:    for what the current value of the problem counter is.
                   6730: 
1.447     foxr     6731:    Caches the results to $env{'form.scantron_maxbubble'},
                   6732:    $env{'form.scantron.bubble_lines.n'} and 
                   6733:    $env{'form.scantron.first_bubble_line.n'}
                   6734:    which are the total number of bubble, lines, the number of bubble
                   6735:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6736: 
1.423     albertel 6737: =cut
                   6738: 
1.330     albertel 6739: sub scantron_get_maxbubble {    
1.448     foxr     6740:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6741:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6742: 	$env{'form.scantron_maxbubble'}) {
1.448     foxr     6743: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6744: 	&restore_bubble_lines();
1.257     albertel 6745: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6746:     }
1.448     foxr     6747:     &Apache::lonnet::logthis("computing");
1.330     albertel 6748: 
1.447     foxr     6749:     my (undef, undef, $sequence) =
1.257     albertel 6750: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6751: 
1.447     foxr     6752:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6753:     my $map=$navmap->getResourceByUrl($sequence);
                   6754:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6755: 
                   6756:     &Apache::lonxml::clear_problem_counter();
                   6757: 
1.435     foxr     6758:     my $uname       = $env{'form.student'};
                   6759:     my $udom        = $env{'form.userdom'};
                   6760:     my $cid         = $env{'request.course.id'};
                   6761:     my $total_lines = 0;
                   6762:     %bubble_lines_per_response = ();
1.447     foxr     6763:     %first_bubble_line         = ();
1.435     foxr     6764: 
1.447     foxr     6765:   
                   6766:     my $response_number = 0;
                   6767:     my $bubble_line     = 0;
1.191     albertel 6768:     foreach my $resource (@resources) {
1.435     foxr     6769: 	my $symb = $resource->symb();
1.447     foxr     6770: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6771: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6772: 					('symb' => $resource->symb()),
                   6773: 					('grade_target' => 'analyze'),
                   6774: 					('grade_courseid' => $cid),
                   6775: 					('grade_domain' => $udom),
                   6776: 					('grade_username' => $uname));
1.436     albertel 6777: 	my (undef, $an) =
1.435     foxr     6778: 	    split(/_HASH_REF__/,$result, 2);
                   6779: 
                   6780: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6781: 
                   6782: 
                   6783: 
                   6784: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6785: 	    my ($trash, $part) = split(/\./, $part_id);
                   6786: 
                   6787: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6788: 
                   6789: 	    # TODO - make this a persistent hash not an array.
                   6790: 
                   6791: 
                   6792: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6793: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6794: 	    $response_number++;
                   6795: 
                   6796: 	    $bubble_line +=  $lines;
                   6797: 	    $total_lines +=  $lines;
1.435     foxr     6798: 	}
                   6799: 
1.191     albertel 6800:     }
                   6801:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6802: 
                   6803:     &save_bubble_lines();
1.330     albertel 6804:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6805: 	$total_lines;
1.257     albertel 6806:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6807: }
                   6808: 
1.423     albertel 6809: =pod
                   6810: 
                   6811: =item scantron_validate_missingbubbles
                   6812: 
1.424     albertel 6813:    Validates all scanlines in the selected file to not have any
1.447     foxr     6814:     answers that don't have bubbles that have not been verified
                   6815:     to be bubble free.
1.424     albertel 6816: 
1.423     albertel 6817: =cut
                   6818: 
1.157     albertel 6819: sub scantron_validate_missingbubbles {
                   6820:     my ($r,$currentphase) = @_;
                   6821:     #get student info
                   6822:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6823:     my %idmap=&username_to_idmap($classlist);
                   6824: 
                   6825:     #get scantron line setup
1.257     albertel 6826:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6827:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6828:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6829:     if (!$max_bubble) { $max_bubble=2**31; }
                   6830:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6831: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6832: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6833: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6834: 						 $scan_data);
                   6835: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6836: 	my @to_correct;
                   6837: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6838: 	    if ($missing > $max_bubble) { next; }
                   6839: 	    push(@to_correct,$missing);
                   6840: 	}
                   6841: 	if (@to_correct) {
                   6842: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6843: 				     $line,'missingbubble',\@to_correct);
                   6844: 	    return (1,$currentphase);
                   6845: 	}
                   6846: 
                   6847:     }
                   6848:     return (0,$currentphase+1);
                   6849: }
                   6850: 
1.423     albertel 6851: =pod
                   6852: 
                   6853: =item scantron_process_students
                   6854: 
                   6855:    Routine that does the actual grading of the bubble sheet information.
                   6856: 
                   6857:    The parsed scanline hash is added to %env 
                   6858: 
                   6859:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6860:    foreach resource , with the form data of
                   6861: 
                   6862: 	'submitted'     =>'scantron' 
                   6863: 	'grade_target'  =>'grade',
                   6864: 	'grade_username'=> username of student
                   6865: 	'grade_domain'  => domain of student
                   6866: 	'grade_courseid'=> of course
                   6867: 	'grade_symb'    => symb of resource to grade
                   6868: 
                   6869:     This triggers a grading pass. The problem grading code takes care
                   6870:     of converting the bubbled letter information (now in %env) into a
                   6871:     valid submission.
                   6872: 
                   6873: =cut
                   6874: 
1.82      albertel 6875: sub scantron_process_students {
1.75      albertel 6876:     my ($r) = @_;
1.257     albertel 6877:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6878:     my ($symb)=&get_symb($r);
1.81      albertel 6879:     if (!$symb) {return '';}
1.324     albertel 6880:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6881: 
1.257     albertel 6882:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6883:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6884:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6885:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6886:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6887:     my $map=$navmap->getResourceByUrl($sequence);
                   6888:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6889: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6890:     my $result= <<SCANTRONFORM;
1.81      albertel 6891: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6892:   <input type="hidden" name="command" value="scantron_configphase" />
                   6893:   $default_form_data
                   6894: SCANTRONFORM
1.82      albertel 6895:     $r->print($result);
                   6896: 
                   6897:     my @delayqueue;
1.140     albertel 6898:     my %completedstudents;
                   6899:     
1.200     albertel 6900:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6901:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6902:  				    'Scantron Progress',$count,
1.195     albertel 6903: 				    'inline',undef,'scantronupload');
1.140     albertel 6904:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6905: 					  'Processing first student');
                   6906:     my $start=&Time::HiRes::time();
1.158     albertel 6907:     my $i=-1;
1.200     albertel 6908:     my ($uname,$udom,$started);
1.447     foxr     6909: 
                   6910:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6911: 
1.157     albertel 6912:     while ($i<$scanlines->{'count'}) {
                   6913:  	($uname,$udom)=('','');
                   6914:  	$i++;
1.200     albertel 6915:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6916:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6917: 	if ($started) {
                   6918: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6919: 						     'last student');
                   6920: 	}
                   6921: 	$started=1;
1.157     albertel 6922:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6923:  						 $scan_data);
                   6924:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6925:  					      \%idmap,$i)) {
                   6926:   	    &scantron_add_delay(\@delayqueue,$line,
                   6927:  				'Unable to find a student that matches',1);
                   6928:  	    next;
                   6929:   	}
                   6930:  	if (exists $completedstudents{$uname}) {
                   6931:  	    &scantron_add_delay(\@delayqueue,$line,
                   6932:  				'Student '.$uname.' has multiple sheets',2);
                   6933:  	    next;
                   6934:  	}
                   6935:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6936: 
                   6937: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6938:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6939: 
                   6940: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6941: 	    &scantron_putfile($scanlines,$scan_data);
                   6942: 	}
1.161     albertel 6943: 	
                   6944: 	my $i=0;
1.83      albertel 6945: 	foreach my $resource (@resources) {
1.85      albertel 6946: 	    $i++;
1.193     albertel 6947: 	    my %form=('submitted'     =>'scantron',
                   6948: 		      'grade_target'  =>'grade',
                   6949: 		      'grade_username'=>$uname,
                   6950: 		      'grade_domain'  =>$udom,
1.257     albertel 6951: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6952: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6953: 	    if (exists($scan_record->{'scantron.CODE'})
                   6954: 		&& 
                   6955: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6956: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6957: 	    } else {
                   6958: 		$form{'CODE'}='';
1.193     albertel 6959: 	    }
                   6960: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6961: 	    if ($result ne '') {
                   6962: 	    }
1.213     albertel 6963: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6964: 	}
1.140     albertel 6965: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6966: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6967:     } continue {
1.330     albertel 6968: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6969: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6970:     }
1.140     albertel 6971:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6972: #    my $lasttime = &Time::HiRes::time()-$start;
                   6973: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6974: 
1.200     albertel 6975:     $r->print("</form>");
1.324     albertel 6976:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6977:     return '';
1.75      albertel 6978: }
1.157     albertel 6979: 
1.423     albertel 6980: =pod
                   6981: 
                   6982: =item scantron_upload_scantron_data
                   6983: 
                   6984:     Creates the screen for adding a new bubble sheet data file to a course.
                   6985: 
                   6986: =cut
                   6987: 
1.157     albertel 6988: sub scantron_upload_scantron_data {
                   6989:     my ($r)=@_;
1.257     albertel 6990:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6991:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6992: 							  'domainid',
                   6993: 							  'coursename');
1.257     albertel 6994:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6995: 						   'domainid');
1.324     albertel 6996:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6997:     $r->print(<<UPLOAD);
                   6998: <script type="text/javascript" language="javascript">
                   6999:     function checkUpload(formname) {
                   7000: 	if (formname.upfile.value == "") {
                   7001: 	    alert("Please use the browse button to select a file from your local directory.");
                   7002: 	    return false;
                   7003: 	}
                   7004: 	formname.submit();
                   7005:     }
                   7006: </script>
                   7007: 
                   7008: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7009: $default_form_data
1.181     albertel 7010: <table>
                   7011: <tr><td>$select_link </td></tr>
                   7012: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7013: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7014: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7015: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7016: </table>
1.157     albertel 7017: <input name='command' value='scantronupload_save' type='hidden' />
                   7018: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7019: </form>
                   7020: UPLOAD
                   7021:     return '';
                   7022: }
                   7023: 
1.423     albertel 7024: =pod
                   7025: 
                   7026: =item scantron_upload_scantron_data_save
                   7027: 
                   7028:    Adds a provided bubble information data file to the course if user
                   7029:    has the correct privileges to do so.  
                   7030: 
                   7031: =cut
                   7032: 
1.157     albertel 7033: sub scantron_upload_scantron_data_save {
                   7034:     my($r)=@_;
1.324     albertel 7035:     my ($symb)=&get_symb($r,1);
1.182     albertel 7036:     my $doanotherupload=
                   7037: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7038: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7039: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7040: 	'</form>'."\n";
1.257     albertel 7041:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7042: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7043: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7044: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7045: 	if ($symb) {
1.324     albertel 7046: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7047: 	} else {
                   7048: 	    $r->print($doanotherupload);
                   7049: 	}
1.162     albertel 7050: 	return '';
                   7051:     }
1.257     albertel 7052:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7053:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7054:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7055:     #FIXME
                   7056:     #copied from lonnet::userfileupload()
                   7057:     #make that function able to target a specified course
                   7058:     # Replace Windows backslashes by forward slashes
                   7059:     $fname=~s/\\/\//g;
                   7060:     # Get rid of everything but the actual filename
                   7061:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7062:     # Replace spaces by underscores
                   7063:     $fname=~s/\s+/\_/g;
                   7064:     # Replace all other weird characters by nothing
                   7065:     $fname=~s/[^\w\.\-]//g;
                   7066:     # See if there is anything left
                   7067:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7068:     my $uploadedfile=$fname;
1.157     albertel 7069:     $fname='scantron_orig_'.$fname;
1.257     albertel 7070:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7071: 	$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 7072:     } else {
1.275     albertel 7073: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7074: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7075: 	    $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 7076: 	} else {
1.398     albertel 7077: 	    $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 7078: 	}
                   7079:     }
1.174     albertel 7080:     if ($symb) {
1.209     ng       7081: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7082:     } else {
1.182     albertel 7083: 	$r->print($doanotherupload);
1.174     albertel 7084:     }
1.157     albertel 7085:     return '';
                   7086: }
                   7087: 
1.423     albertel 7088: =pod
                   7089: 
                   7090: =item valid_file
                   7091: 
1.424     albertel 7092:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7093: 
                   7094: =cut
                   7095: 
1.202     albertel 7096: sub valid_file {
                   7097:     my ($requested_file)=@_;
                   7098:     foreach my $filename (sort(&scantron_filenames())) {
                   7099: 	if ($requested_file eq $filename) { return 1; }
                   7100:     }
                   7101:     return 0;
                   7102: }
                   7103: 
1.423     albertel 7104: =pod
                   7105: 
                   7106: =item scantron_download_scantron_data
                   7107: 
                   7108:    Shows a list of the three internal files (original, corrected,
                   7109:    skipped) for a specific bubble sheet data file that exists in the
                   7110:    course.
                   7111: 
                   7112: =cut
                   7113: 
1.202     albertel 7114: sub scantron_download_scantron_data {
                   7115:     my ($r)=@_;
1.324     albertel 7116:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7117:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7118:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7119:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7120:     if (! &valid_file($file)) {
                   7121: 	$r->print(<<ERROR);
                   7122: 	<p>
                   7123: 	    The requested file name was invalid.
                   7124:         </p>
                   7125: ERROR
1.324     albertel 7126: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7127: 	return;
                   7128:     }
                   7129:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7130:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7131:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7132:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7133:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7134:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7135:     $r->print(<<DOWNLOAD);
                   7136:     <p>
                   7137: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7138:     </p>
                   7139:     <p>
                   7140: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7141:     </p>
                   7142:     <p>
                   7143: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7144:     </p>
                   7145: DOWNLOAD
1.324     albertel 7146:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7147:     return '';
                   7148: }
1.157     albertel 7149: 
1.423     albertel 7150: =pod
                   7151: 
                   7152: =back
                   7153: 
                   7154: =cut
                   7155: 
1.75      albertel 7156: #-------- end of section for handling grading scantron forms -------
                   7157: #
                   7158: #-------------------------------------------------------------------
                   7159: 
1.72      ng       7160: #-------------------------- Menu interface -------------------------
                   7161: #
                   7162: #--- Show a Grading Menu button - Calls the next routine ---
                   7163: sub show_grading_menu_form {
1.324     albertel 7164:     my ($symb)=@_;
1.125     ng       7165:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7166: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7167: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7168: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7169: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7170: 	'</form>'."\n";
                   7171:     return $result;
                   7172: }
                   7173: 
1.77      ng       7174: # -- Retrieve choices for grading form
                   7175: sub savedState {
                   7176:     my %savedState = ();
1.257     albertel 7177:     if ($env{'form.saveState'}) {
                   7178: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7179: 	    my ($key,$value) = split(/=/,$_,2);
                   7180: 	    $savedState{$key} = $value;
                   7181: 	}
                   7182:     }
                   7183:     return \%savedState;
                   7184: }
1.76      ng       7185: 
1.443     banghart 7186: sub grading_menu {
                   7187:     my ($request) = @_;
                   7188:     my ($symb)=&get_symb($request);
                   7189:     if (!$symb) {return '';}
                   7190:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7191:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7192: 
                   7193:     #
                   7194:     # Define menu data
1.444     banghart 7195:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7196:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7197:     $request->print($table);
1.443     banghart 7198:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7199:                   'handgrade'=>$hdgrade,
                   7200:                   'probTitle'=>$probTitle,
                   7201:                   'command'=>'submit_options',
                   7202:                   'saveState'=>"",
                   7203:                   'gradingMenu'=>1,
                   7204:                   'showgrading'=>"yes");
                   7205:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7206:     my @menu = ({ url => $url,
                   7207:                      name => &mt('Manual Grading/View Submissions'),
                   7208:                      short_description => 
                   7209:     &mt('Start the process of hand grading submissions.'),
                   7210:                  });
                   7211:     $fields{'command'} = 'csvform';
                   7212:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7213:     push (@menu, { url => $url,
                   7214:                    name => &mt('Upload Scores'),
                   7215:                    short_description => 
                   7216:             &mt('Specify a file containing the class scores for current resource.')});
                   7217:     $fields{'command'} = 'processclicker';
                   7218:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7219:     push (@menu, { url => $url,
                   7220:                    name => &mt('Process Clicker'),
                   7221:                    short_description => 
                   7222:             &mt('Specify a file containing the clicker information for this resource.')});
                   7223:     $fields{'command'} = 'scantron_selectphase';
                   7224:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7225:     push (@menu, { url => $url,
1.454   ! banghart 7226:                    name => &mt('Grade/Manage Scantron Forms'),
        !          7227:                    short_description => 
        !          7228:             &mt('')});
        !          7229:     $fields{'command'} = 'codelist';
        !          7230:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
        !          7231:     push (@menu, { url => $url,
        !          7232:                    name => &mt('View Saved CODEs'),
1.443     banghart 7233:                    short_description => 
                   7234:             &mt('')});
                   7235:     $fields{'command'} = 'verify';
                   7236:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7237:     push (@menu, { url => "",
                   7238:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7239:                    name => &mt('Verify Receipt'),
                   7240:                    short_description => 
                   7241:             &mt('')});
                   7242: 
                   7243:     #
                   7244:     # Create the menu
                   7245:     my $Str;
1.444     banghart 7246:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7247:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7248:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7249:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7250: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7251: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7252: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7253: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7254: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7255: 
1.443     banghart 7256:     foreach my $menudata (@menu) {
1.445     banghart 7257:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7258:             $Str .='    <h3><a '.
                   7259:                 $menudata->{'jscript'}.
                   7260:                 ' href="'.
                   7261:                 $menudata->{'url'}.'" >'.
                   7262:                 $menudata->{'name'}."</a></h3>\n";
                   7263:         } else {
                   7264:             $Str .='    <h3><a '.
                   7265:                 $menudata->{'jscript'}.
1.446     banghart 7266:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7267:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7268:             $Str .= ('&nbsp;'x8).
                   7269:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7270:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7271:         }
1.443     banghart 7272:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7273:             "\n";
                   7274:     }
                   7275:     $Str .="</dl>\n";
1.444     banghart 7276:     $Str .="</form>\n";
1.443     banghart 7277:     $request->print(<<GRADINGMENUJS);
                   7278: <script type="text/javascript" language="javascript">
                   7279:     function checkChoice(formname,val,cmdx) {
                   7280: 	if (val <= 2) {
                   7281: 	    var cmd = radioSelection(formname.radioChoice);
                   7282: 	    var cmdsave = cmd;
                   7283: 	} else {
                   7284: 	    cmd = cmdx;
                   7285: 	    cmdsave = 'submission';
                   7286: 	}
                   7287: 	formname.command.value = cmd;
                   7288: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7289: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7290: 	if (val < 5) formname.submit();
                   7291: 	if (val == 5) {
                   7292: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7293: 	    formname.submit();
                   7294: 	}
                   7295: 	if (val < 7) formname.submit();
                   7296:     }
1.445     banghart 7297:     function checkChoice2(formname,val,cmdx) {
                   7298: 	if (val <= 2) {
                   7299: 	    var cmd = radioSelection(formname.radioChoice);
                   7300: 	    var cmdsave = cmd;
                   7301: 	} else {
                   7302: 	    cmd = cmdx;
                   7303: 	    cmdsave = 'submission';
                   7304: 	}
                   7305: 	formname.command.value = cmd;
                   7306: 	if (val < 5) formname.submit();
                   7307: 	if (val == 5) {
                   7308: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7309: 	    formname.submit();
                   7310: 	}
                   7311: 	if (val < 7) formname.submit();
                   7312:     }
1.443     banghart 7313: 
                   7314:     function checkReceiptNo(formname,nospace) {
                   7315: 	var receiptNo = formname.receipt.value;
                   7316: 	var checkOpt = false;
                   7317: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7318: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7319: 	if (checkOpt) {
                   7320: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7321: 	    formname.receipt.value = "";
                   7322: 	    formname.receipt.focus();
                   7323: 	    return false;
                   7324: 	}
                   7325: 	return true;
                   7326:     }
                   7327: </script>
                   7328: GRADINGMENUJS
                   7329:     &commonJSfunctions($request);
                   7330:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7331:     $result.=$table;
                   7332:     my (undef,$sections) = &getclasslist('all','0');
                   7333:     my $savedState = &savedState();
                   7334:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7335:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7336:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7337:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7338: 
                   7339:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7340: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7341: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7342: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7343: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7344: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7345: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7346: 
                   7347:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7348: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7349: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7350: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7351: 
                   7352:     $result.='<table width="100%" border="0">';
                   7353:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7354:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7355: #    $result.='<td>Groups</td>';
                   7356:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7357:     $result.='</tr>';
                   7358:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7359: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7360:     if (ref($sections)) {
                   7361: 	foreach (sort (@$sections)) {
                   7362: 	    $result.='<option value="'.$_.'" '.
                   7363: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7364: 	}
                   7365:     }
                   7366:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7367:     return $Str;    
                   7368: }
                   7369: 
                   7370: 
                   7371: #--- Displays the submissions first page -------
                   7372: sub submit_options {
1.72      ng       7373:     my ($request) = @_;
1.324     albertel 7374:     my ($symb)=&get_symb($request);
1.72      ng       7375:     if (!$symb) {return '';}
1.76      ng       7376:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7377: 
                   7378:     $request->print(<<GRADINGMENUJS);
                   7379: <script type="text/javascript" language="javascript">
1.116     ng       7380:     function checkChoice(formname,val,cmdx) {
                   7381: 	if (val <= 2) {
                   7382: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7383: 	    var cmdsave = cmd;
1.116     ng       7384: 	} else {
                   7385: 	    cmd = cmdx;
1.118     ng       7386: 	    cmdsave = 'submission';
1.116     ng       7387: 	}
                   7388: 	formname.command.value = cmd;
1.118     ng       7389: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7390: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7391: 	if (val < 5) formname.submit();
                   7392: 	if (val == 5) {
1.72      ng       7393: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7394: 	    formname.submit();
                   7395: 	}
1.238     albertel 7396: 	if (val < 7) formname.submit();
1.72      ng       7397:     }
                   7398: 
                   7399:     function checkReceiptNo(formname,nospace) {
                   7400: 	var receiptNo = formname.receipt.value;
                   7401: 	var checkOpt = false;
                   7402: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7403: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7404: 	if (checkOpt) {
                   7405: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7406: 	    formname.receipt.value = "";
                   7407: 	    formname.receipt.focus();
                   7408: 	    return false;
                   7409: 	}
                   7410: 	return true;
                   7411:     }
                   7412: </script>
                   7413: GRADINGMENUJS
1.118     ng       7414:     &commonJSfunctions($request);
1.398     albertel 7415:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7416:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7417:     $result.=$table;
1.76      ng       7418:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7419:     my $savedState = &savedState();
1.118     ng       7420:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7421:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7422:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7423:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7424: 
                   7425:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7426: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7427: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7428: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7429: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7430: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7431: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7432: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7433: 
1.446     banghart 7434:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7435: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7436: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7437: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7438: 
1.326     albertel 7439:     $result.='<table width="100%" border="0">';
1.442     banghart 7440:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7441:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7442:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7443:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7444:     $result.='</tr>';
1.116     ng       7445:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7446: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7447:     if (ref($sections)) {
1.155     albertel 7448: 	foreach (sort (@$sections)) {
                   7449: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7450: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7451: 	}
1.116     ng       7452:     }
1.401     albertel 7453:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7454:     $result.= '</td><td>'."\n";
                   7455:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7456:     $result.='</td><td>'."\n";
                   7457:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7458: 
1.116     ng       7459:     $result.='</td></tr>';
                   7460: 
1.442     banghart 7461:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7462: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7463: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7464: 	'</label> <select name="submitonly">'.
1.145     albertel 7465: 	'<option value="yes" '.
1.401     albertel 7466: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7467: 	'<option value="queued" '.
1.401     albertel 7468: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7469: 	'<option value="graded" '.
1.401     albertel 7470: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7471: 	'<option value="incorrect" '.
1.401     albertel 7472: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7473: 	'<option value="all" '.
1.401     albertel 7474: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7475: 
1.442     banghart 7476:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7477: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7478: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7479: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7480: 
1.442     banghart 7481:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7482: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7483: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7484: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7485: 
1.442     banghart 7486:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7487: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7488: 	'</td></tr></table>'."\n";
                   7489: 
1.446     banghart 7490:     $result.='</td>'; #<td valign="top">';
1.116     ng       7491: 
1.446     banghart 7492: #    $result.='<table width="100%" border="0">';
                   7493: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7494: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7495: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7496: #
                   7497: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7498: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7499: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7500: #
                   7501: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7502: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7503: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7504: #
                   7505: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7506: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7507: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7508: #	    ' '.&mt('receipt').': '.
                   7509: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7510: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7511: #	    '</td></tr>'."\n";
                   7512: #    } 
                   7513: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7514: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7515: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7516: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7517: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7518: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7519: #
                   7520: #    $result.='</table>'."\n".'</td>';
                   7521:     $result.= '</tr></table>'."\n".
1.401     albertel 7522: 	'</td></tr></table></form>'."\n";
1.44      ng       7523:     return $result;
1.2       albertel 7524: }
                   7525: 
1.285     albertel 7526: sub reset_perm {
                   7527:     undef(%perm);
                   7528: }
                   7529: 
                   7530: sub init_perm {
                   7531:     &reset_perm();
1.300     albertel 7532:     foreach my $test_perm ('vgr','mgr','opa') {
                   7533: 
                   7534: 	my $scope = $env{'request.course.id'};
                   7535: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7536: 
                   7537: 	    $scope .= '/'.$env{'request.course.sec'};
                   7538: 	    if ( $perm{$test_perm}=
                   7539: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7540: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7541: 	    } else {
                   7542: 		delete($perm{$test_perm});
                   7543: 	    }
1.285     albertel 7544: 	}
                   7545:     }
                   7546: }
                   7547: 
1.400     www      7548: sub gather_clicker_ids {
1.408     albertel 7549:     my %clicker_ids;
1.400     www      7550: 
                   7551:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7552: 
                   7553:     # Set up a couple variables.
1.407     albertel 7554:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7555:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7556:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7557: 
1.407     albertel 7558:     foreach my $student (keys(%$classlist)) {
1.438     www      7559:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7560:         my $username = $classlist->{$student}->[$username_idx];
                   7561:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7562:         my $clickers =
1.408     albertel 7563: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7564:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7565:             $id=~s/^[\#0]+//;
1.421     www      7566:             $id=~s/[\-\:]//g;
1.407     albertel 7567:             if (exists($clicker_ids{$id})) {
1.408     albertel 7568: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7569:             } else {
1.408     albertel 7570: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7571:             }
                   7572:         }
                   7573:     }
1.407     albertel 7574:     return %clicker_ids;
1.400     www      7575: }
                   7576: 
1.402     www      7577: sub gather_adv_clicker_ids {
1.408     albertel 7578:     my %clicker_ids;
1.402     www      7579:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7580:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7581:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7582:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7583:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7584:             my ($puname,$pudom)=split(/\:/,$person);
                   7585:             my $clickers =
1.408     albertel 7586: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7587:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7588: 		$id=~s/^[\#0]+//;
1.421     www      7589:                 $id=~s/[\-\:]//g;
1.408     albertel 7590: 		if (exists($clicker_ids{$id})) {
                   7591: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7592: 		} else {
                   7593: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7594: 		}
1.405     www      7595:             }
1.402     www      7596:         }
                   7597:     }
1.407     albertel 7598:     return %clicker_ids;
1.402     www      7599: }
                   7600: 
1.413     www      7601: sub clicker_grading_parameters {
                   7602:     return ('gradingmechanism' => 'scalar',
                   7603:             'upfiletype' => 'scalar',
                   7604:             'specificid' => 'scalar',
                   7605:             'pcorrect' => 'scalar',
                   7606:             'pincorrect' => 'scalar');
                   7607: }
                   7608: 
1.400     www      7609: sub process_clicker {
                   7610:     my ($r)=@_;
                   7611:     my ($symb)=&get_symb($r);
                   7612:     if (!$symb) {return '';}
                   7613:     my $result=&checkforfile_js();
                   7614:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7615:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7616:     $result.=$table;
                   7617:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7618:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7619:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7620:         '.</b></td></tr>'."\n";
                   7621:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7622: # Attempt to restore parameters from last session, set defaults if not present
                   7623:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7624:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7625:                                                  \%Saveable_Parameters);
                   7626:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7627:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7628:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7629:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7630: 
                   7631:     my %checked;
                   7632:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7633:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7634:           $checked{$gradingmechanism}="checked='checked'";
                   7635:        }
                   7636:     }
                   7637: 
1.400     www      7638:     my $upload=&mt("Upload File");
                   7639:     my $type=&mt("Type");
1.402     www      7640:     my $attendance=&mt("Award points just for participation");
                   7641:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7642:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7643:     my $pcorrect=&mt("Percentage points for correct solution");
                   7644:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7645:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7646: 						   ('iclicker' => 'i>clicker',
                   7647:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7648:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7649:     $result.=<<ENDUPFORM;
1.402     www      7650: <script type="text/javascript">
                   7651: function sanitycheck() {
                   7652: // Accept only integer percentages
                   7653:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7654:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7655: // Find out grading choice
                   7656:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7657:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7658:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7659:       }
                   7660:    }
                   7661: // By default, new choice equals user selection
                   7662:    newgradingchoice=gradingchoice;
                   7663: // Not good to give more points for false answers than correct ones
                   7664:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7665:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7666:    }
                   7667: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7668:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7669:       document.forms.gradesupload.pcorrect.value=100;
                   7670:       document.forms.gradesupload.pincorrect.value=100;
                   7671:    }
                   7672: // If the values are different, cannot be attendance only
                   7673:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7674:        (gradingchoice=='attendance')) {
                   7675:        newgradingchoice='personnel';
                   7676:    }
                   7677: // Change grading choice to new one
                   7678:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7679:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7680:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7681:       } else {
                   7682:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7683:       }
                   7684:    }
                   7685: // Remember the old state
                   7686:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7687: }
                   7688: </script>
1.400     www      7689: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7690: <input type="hidden" name="symb" value="$symb" />
                   7691: <input type="hidden" name="command" value="processclickerfile" />
                   7692: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7693: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7694: <input type="file" name="upfile" size="50" />
                   7695: <br /><label>$type: $selectform</label>
1.451     albertel 7696: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7697: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7698: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7699: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7700: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7701: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7702: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7703: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7704: </form>
                   7705: ENDUPFORM
                   7706:     $result.='</td></tr></table>'."\n".
                   7707:              '</td></tr></table><br /><br />'."\n";
                   7708:     $result.=&show_grading_menu_form($symb);
                   7709:     return $result;
                   7710: }
                   7711: 
                   7712: sub process_clicker_file {
                   7713:     my ($r)=@_;
                   7714:     my ($symb)=&get_symb($r);
                   7715:     if (!$symb) {return '';}
1.413     www      7716: 
                   7717:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7718:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7719:                                               \%Saveable_Parameters);
                   7720: 
1.400     www      7721:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7722:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7723: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7724: 	return $result.&show_grading_menu_form($symb);
1.404     www      7725:     }
1.407     albertel 7726:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7727:     my %correct_ids;
1.404     www      7728:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7729: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7730:     }
                   7731:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7732: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7733: 	   $correct_id=~tr/a-z/A-Z/;
                   7734: 	   $correct_id=~s/\s//gs;
                   7735: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7736:            $correct_id=~s/[\-\:]//g;
1.414     www      7737:            if ($correct_id) {
                   7738: 	      $correct_ids{$correct_id}='specified';
                   7739:            }
                   7740:         }
1.400     www      7741:     }
1.404     www      7742:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7743: 	$result.=&mt('Score based on attendance only');
1.404     www      7744:     } else {
1.408     albertel 7745: 	my $number=0;
1.411     www      7746: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7747: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7748: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7749: 	    if ($correct_ids{$id} eq 'specified') {
                   7750: 		$result.=&mt('specified');
                   7751: 	    } else {
                   7752: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7753: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7754: 	    }
                   7755: 	    $number++;
                   7756: 	}
1.411     www      7757:         $result.="</p>\n";
1.408     albertel 7758: 	if ($number==0) {
                   7759: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7760: 	    return $result.&show_grading_menu_form($symb);
                   7761: 	}
1.404     www      7762:     }
1.405     www      7763:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7764:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7765: 		     '<span class="LC_error">',
                   7766: 		     '</span>',
                   7767: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7768:         return $result.&show_grading_menu_form($symb);
                   7769:     }
1.410     www      7770: 
                   7771: # Were able to get all the info needed, now analyze the file
                   7772: 
1.411     www      7773:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7774:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7775:     my $heading=&mt('Scanning clicker file');
                   7776:     $result.=(<<ENDHEADER);
                   7777: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7778: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7779: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7780: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7781: <input type="hidden" name="symb" value="$symb" />
                   7782: <input type="hidden" name="command" value="assignclickergrades" />
                   7783: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7784: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7785: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7786: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7787: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7788: ENDHEADER
1.408     albertel 7789:     my %responses;
                   7790:     my @questiontitles;
1.405     www      7791:     my $errormsg='';
                   7792:     my $number=0;
                   7793:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7794: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7795:     }
1.419     www      7796:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7797:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7798:     }
1.411     www      7799:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7800:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7801:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7802:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7803:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7804:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7805:              '<br />';
1.414     www      7806: # Remember Question Titles
                   7807: # FIXME: Possibly need delimiter other than ":"
                   7808:     for (my $i=0;$i<$number;$i++) {
                   7809:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7810:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7811:     }
1.411     www      7812:     my $correct_count=0;
                   7813:     my $student_count=0;
                   7814:     my $unknown_count=0;
1.414     www      7815: # Match answers with usernames
                   7816: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7817:     foreach my $id (keys(%responses)) {
1.410     www      7818:        if ($correct_ids{$id}) {
1.414     www      7819:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7820:           $correct_count++;
1.410     www      7821:        } elsif ($clicker_ids{$id}) {
1.437     www      7822:           if ($clicker_ids{$id}=~/\,/) {
                   7823: # More than one user with the same clicker!
                   7824:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7825:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7826:                            "<select name='multi".$id."'>";
                   7827:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7828:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7829:              }
                   7830:              $result.='</select>';
                   7831:              $unknown_count++;
                   7832:           } else {
                   7833: # Good: found one and only one user with the right clicker
                   7834:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7835:              $student_count++;
                   7836:           }
1.410     www      7837:        } else {
1.411     www      7838:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7839:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7840:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7841:                    "\n".&mt("Domain").": ".
                   7842:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7843:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7844:           $unknown_count++;
1.410     www      7845:        }
1.405     www      7846:     }
1.412     www      7847:     $result.='<hr />'.
                   7848:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7849:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7850:        if ($correct_count==0) {
                   7851:           $errormsg.="Found no correct answers answers for grading!";
                   7852:        } elsif ($correct_count>1) {
1.414     www      7853:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7854:        }
                   7855:     }
1.428     www      7856:     if ($number<1) {
                   7857:        $errormsg.="Found no questions.";
                   7858:     }
1.412     www      7859:     if ($errormsg) {
                   7860:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7861:     } else {
                   7862:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7863:     }
                   7864:     $result.='</form></td></tr></table>'."\n".
1.410     www      7865:              '</td></tr></table><br /><br />'."\n";
1.404     www      7866:     return $result.&show_grading_menu_form($symb);
1.400     www      7867: }
                   7868: 
1.405     www      7869: sub iclicker_eval {
1.406     www      7870:     my ($questiontitles,$responses)=@_;
1.405     www      7871:     my $number=0;
                   7872:     my $errormsg='';
                   7873:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7874:         my %components=&Apache::loncommon::record_sep($line);
                   7875:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7876: 	if ($entries[0] eq 'Question') {
                   7877: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7878: 		$$questiontitles[$number]=$entries[$i];
                   7879: 		$number++;
                   7880: 	    }
                   7881: 	}
                   7882: 	if ($entries[0]=~/^\#/) {
                   7883: 	    my $id=$entries[0];
                   7884: 	    my @idresponses;
                   7885: 	    $id=~s/^[\#0]+//;
                   7886: 	    for (my $i=0;$i<$number;$i++) {
                   7887: 		my $idx=3+$i*6;
                   7888: 		push(@idresponses,$entries[$idx]);
                   7889: 	    }
                   7890: 	    $$responses{$id}=join(',',@idresponses);
                   7891: 	}
1.405     www      7892:     }
                   7893:     return ($errormsg,$number);
                   7894: }
                   7895: 
1.419     www      7896: sub interwrite_eval {
                   7897:     my ($questiontitles,$responses)=@_;
                   7898:     my $number=0;
                   7899:     my $errormsg='';
1.420     www      7900:     my $skipline=1;
                   7901:     my $questionnumber=0;
                   7902:     my %idresponses=();
1.419     www      7903:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7904:         my %components=&Apache::loncommon::record_sep($line);
                   7905:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7906:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7907:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7908:         next if $skipline;
                   7909:         if ($entries[0]!=$questionnumber) {
                   7910:            $questionnumber=$entries[0];
                   7911:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7912:            $number++;
1.419     www      7913:         }
1.420     www      7914:         my $id=$entries[4];
                   7915:         $id=~s/^[\#0]+//;
1.421     www      7916:         $id=~s/^v\d*\://i;
                   7917:         $id=~s/[\-\:]//g;
1.420     www      7918:         $idresponses{$id}[$number]=$entries[6];
                   7919:     }
                   7920:     foreach my $id (keys %idresponses) {
                   7921:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7922:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7923:     }
                   7924:     return ($errormsg,$number);
                   7925: }
                   7926: 
1.414     www      7927: sub assign_clicker_grades {
                   7928:     my ($r)=@_;
                   7929:     my ($symb)=&get_symb($r);
                   7930:     if (!$symb) {return '';}
1.416     www      7931: # See which part we are saving to
                   7932:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7933: # FIXME: This should probably look for the first handgradeable part
                   7934:     my $part=$$partlist[0];
                   7935: # Start screen output
1.414     www      7936:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7937: 
1.414     www      7938:     my $heading=&mt('Assigning grades based on clicker file');
                   7939:     $result.=(<<ENDHEADER);
                   7940: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7941: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7942: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7943: ENDHEADER
                   7944: # Get correct result
                   7945: # FIXME: Possibly need delimiter other than ":"
                   7946:     my @correct=();
1.415     www      7947:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7948:     my $number=$env{'form.number'};
                   7949:     if ($gradingmechanism ne 'attendance') {
1.414     www      7950:        foreach my $key (keys(%env)) {
                   7951:           if ($key=~/^form\.correct\:/) {
                   7952:              my @input=split(/\,/,$env{$key});
                   7953:              for (my $i=0;$i<=$#input;$i++) {
                   7954:                  if (($correct[$i]) && ($input[$i]) &&
                   7955:                      ($correct[$i] ne $input[$i])) {
                   7956:                     $result.='<br /><span class="LC_warning">'.
                   7957:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7958:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7959:                  } elsif ($input[$i]) {
                   7960:                     $correct[$i]=$input[$i];
                   7961:                  }
                   7962:              }
                   7963:           }
                   7964:        }
1.415     www      7965:        for (my $i=0;$i<$number;$i++) {
1.414     www      7966:           if (!$correct[$i]) {
                   7967:              $result.='<br /><span class="LC_error">'.
                   7968:                       &mt('No correct result given for question "[_1]"!',
                   7969:                           $env{'form.question:'.$i}).'</span>';
                   7970:           }
                   7971:        }
                   7972:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7973:     }
                   7974: # Start grading
1.415     www      7975:     my $pcorrect=$env{'form.pcorrect'};
                   7976:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7977:     my $storecount=0;
1.415     www      7978:     foreach my $key (keys(%env)) {
1.420     www      7979:        my $user='';
1.415     www      7980:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7981:           $user=$1;
                   7982:        }
                   7983:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7984:           my $id=$1;
                   7985:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7986:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7987:           } elsif ($env{'form.multi'.$id}) {
                   7988:              $user=$env{'form.multi'.$id};
1.420     www      7989:           }
                   7990:        }
                   7991:        if ($user) { 
1.415     www      7992:           my @answer=split(/\,/,$env{$key});
                   7993:           my $sum=0;
                   7994:           for (my $i=0;$i<$number;$i++) {
                   7995:              if ($answer[$i]) {
                   7996:                 if ($gradingmechanism eq 'attendance') {
                   7997:                    $sum+=$pcorrect;
                   7998:                 } else {
                   7999:                    if ($answer[$i] eq $correct[$i]) {
                   8000:                       $sum+=$pcorrect;
                   8001:                    } else {
                   8002:                       $sum+=$pincorrect;
                   8003:                    }
                   8004:                 }
                   8005:              }
                   8006:           }
1.416     www      8007:           my $ave=$sum/(100*$number);
                   8008: # Store
                   8009:           my ($username,$domain)=split(/\:/,$user);
                   8010:           my %grades=();
                   8011:           $grades{"resource.$part.solved"}='correct_by_override';
                   8012:           $grades{"resource.$part.awarded"}=$ave;
                   8013:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8014:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8015:                                                  $env{'request.course.id'},
                   8016:                                                  $domain,$username);
                   8017:           if ($returncode ne 'ok') {
                   8018:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8019:           } else {
                   8020:              $storecount++;
                   8021:           }
1.415     www      8022:        }
                   8023:     }
                   8024: # We are done
1.416     www      8025:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8026:              '</td></tr></table>'."\n".
1.414     www      8027:              '</td></tr></table><br /><br />'."\n";
                   8028:     return $result.&show_grading_menu_form($symb);
                   8029: }
                   8030: 
1.1       albertel 8031: sub handler {
1.41      ng       8032:     my $request=$_[0];
1.434     albertel 8033:     &reset_caches();
1.257     albertel 8034:     if ($env{'browser.mathml'}) {
1.141     www      8035: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8036:     } else {
1.141     www      8037: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8038:     }
                   8039:     $request->send_http_header;
1.44      ng       8040:     return '' if $request->header_only;
1.41      ng       8041:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8042:     my $symb=&get_symb($request,1);
1.160     albertel 8043:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8044:     my $command=$commands[0];
1.447     foxr     8045: 
1.160     albertel 8046:     if ($#commands > 0) {
                   8047: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8048:     }
1.447     foxr     8049: 
                   8050: 
1.353     albertel 8051:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8052:     if ($symb eq '' && $command eq '') {
1.257     albertel 8053: 	if ($env{'user.adv'}) {
                   8054: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8055: 		($env{'form.codethree'})) {
                   8056: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8057: 		    $env{'form.codethree'};
1.41      ng       8058: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8059: 		    &Apache::lonnet::checkin($token);
                   8060: 		if ($tsymb) {
1.137     albertel 8061: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8062: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8063: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8064: 					  ('grade_username' => $tuname,
                   8065: 					   'grade_domain' => $tudom,
                   8066: 					   'grade_courseid' => $tcrsid,
                   8067: 					   'grade_symb' => $tsymb)));
1.41      ng       8068: 		    } else {
1.45      ng       8069: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8070: 		    }
1.41      ng       8071: 		} else {
1.45      ng       8072: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8073: 		}
1.14      www      8074: 	    } else {
1.41      ng       8075: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8076: 	    }
                   8077: 	}
                   8078:     } else {
1.285     albertel 8079: 	&init_perm();
1.104     albertel 8080: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8081: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8082: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8083: 	    &pickStudentPage($request);
1.103     albertel 8084: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8085: 	    &displayPage($request);
1.104     albertel 8086: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8087: 	    &updateGradeByPage($request);
1.104     albertel 8088: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8089: 	    &processGroup($request);
1.104     albertel 8090: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8091: 	    $request->print(&grading_menu($request));
                   8092: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8093: 	    $request->print(&submit_options($request));
1.104     albertel 8094: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8095: 	    $request->print(&viewgrades($request));
1.104     albertel 8096: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8097: 	    $request->print(&processHandGrade($request));
1.106     albertel 8098: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8099: 	    $request->print(&editgrades($request));
1.106     albertel 8100: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8101: 	    $request->print(&verifyreceipt($request));
1.400     www      8102:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8103:             $request->print(&process_clicker($request));
                   8104:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8105:             $request->print(&process_clicker_file($request));
1.414     www      8106:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8107:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8108: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8109: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8110: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8111: 	    $request->print(&csvupload($request));
1.106     albertel 8112: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8113: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8114: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8115: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8116: 		$request->print(&csvuploadoptions($request));
1.41      ng       8117: 	    } else {
1.257     albertel 8118: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8119: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8120: 		} else {
1.257     albertel 8121: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8122: 		}
                   8123: 		$request->print(&csvuploadmap($request));
                   8124: 	    }
1.246     albertel 8125: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8126: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8127: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8128: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8129: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8130:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8131:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8132: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8133: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8134: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8135: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8136:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8137:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8138: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8139:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8140:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8141:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8142: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8143:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8144:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8145: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8146:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8147: 	} elsif ($command) {
1.157     albertel 8148: 	    $request->print("Access Denied ($command)");
1.26      albertel 8149: 	}
1.2       albertel 8150:     }
1.353     albertel 8151:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8152:     &reset_caches();
1.44      ng       8153:     return '';
                   8154: }
                   8155: 
1.1       albertel 8156: 1;
                   8157: 
1.13      albertel 8158: __END__;

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