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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.451   ! albertel    4: # $Id: grades.pm,v 1.450 2007/10/09 23:03:22 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
                    529: 	if (@getgroup) {
                    530: 	    my $exclude = 1;
                    531: 	    foreach my $grp(@getgroup) {
                    532: 	        if ($group eq $grp) {
                    533: 	            $exclude = 0;
                    534: 	        }
                    535: 	    }
                    536: 	    if ($exclude) {
                    537: 	        delete($classlist->{$student});
                    538: 	    }
                    539: 	}
1.205     matthew   540: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  541: 	if (&canview($section)) {
1.291     albertel  542: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  543: 		$sections{$section}++;
1.450     banghart  544: 		if ($classlist->{$student}) {
                    545: 		    $fullnames{$student}=$fullname;
                    546: 		}
1.103     albertel  547: 	    } else {
1.205     matthew   548: 		delete($classlist->{$student});
1.103     albertel  549: 	    }
                    550: 	} else {
1.205     matthew   551: 	    delete($classlist->{$student});
1.103     albertel  552: 	}
1.44      ng        553:     }
                    554:     my %seen = ();
1.56      matthew   555:     my @sections = sort(keys(%sections));
                    556:     return ($classlist,\@sections,\%fullnames);
1.44      ng        557: }
                    558: 
1.103     albertel  559: sub canmodify {
                    560:     my ($sec)=@_;
                    561:     if ($perm{'mgr'}) {
                    562: 	if (!defined($perm{'mgr_section'})) {
                    563: 	    # can modify whole class
                    564: 	    return 1;
                    565: 	} else {
                    566: 	    if ($sec eq $perm{'mgr_section'}) {
                    567: 		#can modify the requested section
                    568: 		return 1;
                    569: 	    } else {
                    570: 		# can't modify the request section
                    571: 		return 0;
                    572: 	    }
                    573: 	}
                    574:     }
                    575:     #can't modify
                    576:     return 0;
                    577: }
                    578: 
                    579: sub canview {
                    580:     my ($sec)=@_;
                    581:     if ($perm{'vgr'}) {
                    582: 	if (!defined($perm{'vgr_section'})) {
                    583: 	    # can modify whole class
                    584: 	    return 1;
                    585: 	} else {
                    586: 	    if ($sec eq $perm{'vgr_section'}) {
                    587: 		#can modify the requested section
                    588: 		return 1;
                    589: 	    } else {
                    590: 		# can't modify the request section
                    591: 		return 0;
                    592: 	    }
                    593: 	}
                    594:     }
                    595:     #can't modify
                    596:     return 0;
                    597: }
                    598: 
1.44      ng        599: #--- Retrieve the grade status of a student for all the parts
                    600: sub student_gradeStatus {
1.324     albertel  601:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  602:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        603:     my %partstatus = ();
                    604:     foreach (@$partlist) {
1.128     ng        605: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        606: 	$status              = 'nothing' if ($status eq '');
                    607: 	$partstatus{$_}      = $status;
                    608: 	my $subkey           = "resource.$_.submitted_by";
                    609: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    610:     }
                    611:     return %partstatus;
                    612: }
                    613: 
1.45      ng        614: # hidden form and javascript that calls the form
                    615: # Use by verifyscript and viewgrades
                    616: # Shows a student's view of problem and submission
                    617: sub jscriptNform {
1.324     albertel  618:     my ($symb) = @_;
1.442     banghart  619:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        620:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    621: 	'    function viewOneStudent(user,domain) {'."\n".
                    622: 	'	document.onestudent.student.value = user;'."\n".
                    623: 	'	document.onestudent.userdom.value = domain;'."\n".
                    624: 	'	document.onestudent.submit();'."\n".
                    625: 	'    }'."\n".
                    626: 	'</script>'."\n";
                    627:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  628: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  629: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    630: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  631: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        632: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    633: 	'<input type="hidden" name="student" value="" />'."\n".
                    634: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    635: 	'</form>'."\n";
                    636:     return $jscript;
                    637: }
1.39      ng        638: 
1.447     foxr      639: 
                    640: 
1.315     bowersj2  641: # Given the score (as a number [0-1] and the weight) what is the final
                    642: # point value? This function will round to the nearest tenth, third,
                    643: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  644: sub compute_points {
1.315     bowersj2  645:     my ($score, $weight) = @_;
                    646:     
                    647:     my $tolerance = .00001;
                    648:     my $points = $score * $weight;
                    649: 
                    650:     # Check for nearness to 1/x.
                    651:     my $check_for_nearness = sub {
                    652:         my ($factor) = @_;
                    653:         my $num = ($points * $factor) + $tolerance;
                    654:         my $floored_num = floor($num);
1.316     albertel  655:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  656:             return $floored_num / $factor;
                    657:         }
                    658:         return $points;
                    659:     };
                    660: 
                    661:     $points = $check_for_nearness->(10);
                    662:     $points = $check_for_nearness->(3);
                    663:     $points = $check_for_nearness->(4);
                    664:     
                    665:     return $points;
                    666: }
                    667: 
1.44      ng        668: #------------------ End of general use routines --------------------
1.87      www       669: 
                    670: #
                    671: # Find most similar essay
                    672: #
                    673: 
                    674: sub most_similar {
1.426     albertel  675:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       676: 
                    677: # ignore spaces and punctuation
                    678: 
                    679:     $uessay=~s/\W+/ /gs;
                    680: 
1.282     www       681: # ignore empty submissions (occuring when only files are sent)
                    682: 
                    683:     unless ($uessay=~/\w+/) { return ''; }
                    684: 
1.87      www       685: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       686:     my $limit=0.6;
1.87      www       687:     my $sname='';
                    688:     my $sdom='';
                    689:     my $scrsid='';
                    690:     my $sessay='';
                    691: # go through all essays ...
1.426     albertel  692:     foreach my $tkey (keys(%$old_essays)) {
                    693: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       694: # ... except the same student
1.426     albertel  695:         next if (($tname eq $uname) && ($tdom eq $udom));
                    696: 	my $tessay=$old_essays->{$tkey};
                    697: 	$tessay=~s/\W+/ /gs;
1.87      www       698: # String similarity gives up if not even limit
1.426     albertel  699: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       700: # Found one
1.426     albertel  701: 	if ($tsimilar>$limit) {
                    702: 	    $limit=$tsimilar;
                    703: 	    $sname=$tname;
                    704: 	    $sdom=$tdom;
                    705: 	    $scrsid=$tcrsid;
                    706: 	    $sessay=$old_essays->{$tkey};
                    707: 	}
1.87      www       708:     }
1.88      www       709:     if ($limit>0.6) {
1.87      www       710:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    711:     } else {
                    712:        return ('','','','',0);
                    713:     }
                    714: }
                    715: 
1.44      ng        716: #-------------------------------------------------------------------
                    717: 
                    718: #------------------------------------ Receipt Verification Routines
1.45      ng        719: #
1.44      ng        720: #--- Check whether a receipt number is valid.---
                    721: sub verifyreceipt {
                    722:     my $request  = shift;
                    723: 
1.257     albertel  724:     my $courseid = $env{'request.course.id'};
1.184     www       725:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  726: 	$env{'form.receipt'};
1.44      ng        727:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  728:     my ($symb)   = &get_symb($request);
1.44      ng        729: 
1.398     albertel  730:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    731: 	$receipt.'</h3></span>'."\n".
                    732: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        733: 
                    734:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   735:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  736:     
                    737:     my $receiptparts=0;
1.390     albertel  738:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    739: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  740:     my $parts=['0'];
1.324     albertel  741:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  742:     foreach (sort 
                    743: 	     {
                    744: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    745: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    746: 		 }
                    747: 		 return $a cmp $b;
                    748: 	     } (keys(%$fullname))) {
1.44      ng        749: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  750: 	foreach my $part (@$parts) {
                    751: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    752: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    753: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  754: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  755: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    756: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    757: 		if ($receiptparts) {
                    758: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    759: 		}
                    760: 		$contents.='</tr>'."\n";
                    761: 		
                    762: 		$matches++;
                    763: 	    }
1.44      ng        764: 	}
                    765:     }
                    766:     if ($matches == 0) {
                    767: 	$string = $title.'No match found for the above receipt.';
                    768:     } else {
1.324     albertel  769: 	$string = &jscriptNform($symb).$title.
1.44      ng        770: 	    'The above receipt matches the following student'.
                    771: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    772: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    773: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    774: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    775: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  776: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    777: 	if ($receiptparts) {
                    778: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    779: 	}
                    780: 	$string.='</tr>'."\n".$contents.
1.44      ng        781: 	    '</table></td></tr></table>'."\n";
                    782:     }
1.324     albertel  783:     return $string.&show_grading_menu_form($symb);
1.44      ng        784: }
                    785: 
                    786: #--- This is called by a number of programs.
                    787: #--- Called from the Grading Menu - View/Grade an individual student
                    788: #--- Also called directly when one clicks on the subm button 
                    789: #    on the problem page.
1.30      ng        790: sub listStudents {
1.41      ng        791:     my ($request) = shift;
1.49      albertel  792: 
1.324     albertel  793:     my ($symb) = &get_symb($request);
1.257     albertel  794:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    795:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    796:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  797:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  798:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    799:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    800:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    801: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  802: 
1.398     albertel  803:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    804: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        805: 
1.324     albertel  806:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  807: 
1.45      ng        808:     $request->print(<<LISTJAVASCRIPT);
                    809: <script type="text/javascript" language="javascript">
1.110     ng        810:     function checkSelect(checkBox) {
                    811: 	var ctr=0;
                    812: 	var sense="";
                    813: 	if (checkBox.length > 1) {
                    814: 	    for (var i=0; i<checkBox.length; i++) {
                    815: 		if (checkBox[i].checked) {
                    816: 		    ctr++;
                    817: 		}
                    818: 	    }
                    819: 	    sense = "a student or group of students";
                    820: 	} else {
                    821: 	    if (checkBox.checked) {
                    822: 		ctr = 1;
                    823: 	    }
                    824: 	    sense = "the student";
                    825: 	}
                    826: 	if (ctr == 0) {
1.126     ng        827: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        828: 	    return false;
                    829: 	}
                    830: 	document.gradesub.submit();
                    831:     }
                    832: 
                    833:     function reLoadList(formname) {
1.112     ng        834: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        835: 	formname.command.value = 'submission';
                    836: 	formname.submit();
                    837:     }
1.45      ng        838: </script>
                    839: LISTJAVASCRIPT
                    840: 
1.118     ng        841:     &commonJSfunctions($request);
1.41      ng        842:     $request->print($result);
1.39      ng        843: 
1.401     albertel  844:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    845:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  846:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    847: 	"\n".$table.
1.401     albertel  848: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  849: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    850: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    851: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    852: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  853: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  854: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  855:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  856: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  857:     }
1.442     banghart  858:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    859:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  860:     $env{'form.Status'} = $saveStatus;
1.267     albertel  861:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    862: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    863: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  864: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    865:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    866:         '<option value="1">Whole Points</option>'.
                    867:         '<option value=".5">Half Points</option>'.
1.349     albertel  868:         '<option value=".25">Quarter Points</option>'.
                    869:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  870:         '</select>'.
1.432     banghart  871:         &build_section_inputs().
1.45      ng        872: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  873: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    874: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    875: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    876: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  877: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        878: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    879: 
1.257     albertel  880:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  881: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        882:     } else {
                    883: 	$gradeTable.='<b>Student Status:</b> '.
                    884: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    885:     }
1.112     ng        886: 
1.126     ng        887:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    888: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        889: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  890: 
                    891: # checkall buttons
                    892:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        893:     $gradeTable.='<input type="button" '."\n".
1.45      ng        894: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  895: 	'value="Next->" /> <br />'."\n";
                    896:     $gradeTable.=&check_buttons();
1.401     albertel  897:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.450     banghart  898:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.45      ng        899:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        900: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    901:     my $loop = 0;
                    902:     while ($loop < 2) {
1.126     ng        903: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  904: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  905: 	if ($env{'form.showgrading'} eq 'yes' 
                    906: 	    && $submitonly ne 'queued'
                    907: 	    && $submitonly ne 'all') {
1.110     ng        908: 	    foreach (sort(@$partlist)) {
1.324     albertel  909: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  910: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    911: 		    ' Status&nbsp;</b></td>';
1.110     ng        912: 	    }
1.301     albertel  913: 	} elsif ($submitonly eq 'queued') {
                    914: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        915: 	}
                    916: 	$loop++;
1.126     ng        917: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        918:     }
1.45      ng        919:     $gradeTable.='</tr>'."\n";
1.41      ng        920: 
1.45      ng        921:     my $ctr = 0;
1.294     albertel  922:     foreach my $student (sort 
                    923: 			 {
                    924: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    925: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    926: 			     }
                    927: 			     return $a cmp $b;
                    928: 			 }
                    929: 			 (keys(%$fullname))) {
1.41      ng        930: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  931: 
1.110     ng        932: 	my %status = ();
1.301     albertel  933: 
                    934: 	if ($submitonly eq 'queued') {
                    935: 	    my %queue_status = 
                    936: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    937: 							$udom,$uname);
                    938: 	    next if (!defined($queue_status{'gradingqueue'}));
                    939: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    940: 	}
                    941: 
                    942: 	if ($env{'form.showgrading'} eq 'yes' 
                    943: 	    && $submitonly ne 'queued'
                    944: 	    && $submitonly ne 'all') {
1.324     albertel  945: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  946: 	    my $submitted = 0;
1.164     albertel  947: 	    my $graded = 0;
1.248     albertel  948: 	    my $incorrect = 0;
1.110     ng        949: 	    foreach (keys(%status)) {
1.145     albertel  950: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  951: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    952: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    953: 		
1.110     ng        954: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    955: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  956: 		    $submitted = 0;
1.150     albertel  957: 		    my ($part)=split(/\./,$partid);
1.110     ng        958: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  959: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        960: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    961: 		}
1.41      ng        962: 	    }
1.248     albertel  963: 	    
1.156     albertel  964: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    965: 				     $submitonly eq 'incorrect' ||
                    966: 				     $submitonly eq 'graded'));
1.248     albertel  967: 	    next if (!$graded && ($submitonly eq 'graded'));
                    968: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        969: 	}
1.34      ng        970: 
1.45      ng        971: 	$ctr++;
1.249     albertel  972: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    973: 
1.104     albertel  974: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        975: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        976: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  977:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    978:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    979: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    980: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    981: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        982: 
1.257     albertel  983: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        984: 		foreach (sort keys(%status)) {
                    985: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  986: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        987: 		}
1.41      ng        988: 	    }
1.126     ng        989: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        990: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        991: 	}
                    992:     }
1.110     ng        993:     if ($ctr%2 ==1) {
1.126     ng        994: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  995: 	    if ($env{'form.showgrading'} eq 'yes' 
                    996: 		&& $submitonly ne 'queued'
                    997: 		&& $submitonly ne 'all') {
1.110     ng        998: 		foreach (@$partlist) {
                    999: 		    $gradeTable.='<td>&nbsp;</td>';
                   1000: 		}
1.301     albertel 1001: 	    } elsif ($submitonly eq 'queued') {
                   1002: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1003: 	    }
                   1004: 	$gradeTable.='</tr>';
                   1005:     }
                   1006: 
1.249     albertel 1007:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng       1008: 	'<input type="button" '.
                   1009: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1010: 	'value="Next->" /></form>'."\n";
1.45      ng       1011:     if ($ctr == 0) {
1.96      albertel 1012: 	my $num_students=(scalar(keys(%$fullname)));
                   1013: 	if ($num_students eq 0) {
1.398     albertel 1014: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1015: 	} else {
1.171     albertel 1016: 	    my $submissions='submissions';
                   1017: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1018: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1019: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1021: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1022: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1023: 	}
1.46      ng       1024:     } elsif ($ctr == 1) {
                   1025: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1026:     }
1.324     albertel 1027:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1028:     $request->print($gradeTable);
1.44      ng       1029:     return '';
1.10      ng       1030: }
                   1031: 
1.44      ng       1032: #---- Called from the listStudents routine
1.249     albertel 1033: 
                   1034: sub check_script {
                   1035:     my ($form, $type)=@_;
                   1036:     my $chkallscript='<script type="text/javascript">
                   1037:     function checkall() {
                   1038:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1039:             ele = document.forms.'.$form.'.elements[i];
                   1040:             if (ele.name == "'.$type.'") {
                   1041:             document.forms.'.$form.'.elements[i].checked=true;
                   1042:                                        }
                   1043:         }
                   1044:     }
                   1045: 
                   1046:     function checksec() {
                   1047:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1048:             ele = document.forms.'.$form.'.elements[i];
                   1049:            string = document.forms.'.$form.'.chksec.value;
                   1050:            if
                   1051:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1052:               document.forms.'.$form.'.elements[i].checked=true;
                   1053:             }
                   1054:         }
                   1055:     }
                   1056: 
                   1057: 
                   1058:     function uncheckall() {
                   1059:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1060:             ele = document.forms.'.$form.'.elements[i];
                   1061:             if (ele.name == "'.$type.'") {
                   1062:             document.forms.'.$form.'.elements[i].checked=false;
                   1063:                                        }
                   1064:         }
                   1065:     }
                   1066: 
                   1067: </script>'."\n";
                   1068:     return $chkallscript;
                   1069: }
                   1070: 
                   1071: sub check_buttons {
                   1072:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1073:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1074:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1075:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1076:     return $buttons;
                   1077: }
                   1078: 
1.44      ng       1079: #     Displays the submissions for one student or a group of students
1.34      ng       1080: sub processGroup {
1.41      ng       1081:     my ($request)  = shift;
                   1082:     my $ctr        = 0;
1.155     albertel 1083:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1084:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1085: 
1.396     banghart 1086:     foreach my $student (@stuchecked) {
                   1087: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1088: 	$env{'form.student'}        = $uname;
                   1089: 	$env{'form.userdom'}        = $udom;
                   1090: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1091: 	&submission($request,$ctr,$total);
                   1092: 	$ctr++;
                   1093:     }
                   1094:     return '';
1.35      ng       1095: }
1.34      ng       1096: 
1.44      ng       1097: #------------------------------------------------------------------------------------
                   1098: #
                   1099: #-------------------------- Next few routines handles grading by student, essentially
                   1100: #                           handles essay response type problem/part
                   1101: #
                   1102: #--- Javascript to handle the submission page functionality ---
                   1103: sub sub_page_js {
                   1104:     my $request = shift;
                   1105:     $request->print(<<SUBJAVASCRIPT);
                   1106: <script type="text/javascript" language="javascript">
1.71      ng       1107:     function updateRadio(formname,id,weight) {
1.125     ng       1108: 	var gradeBox = formname["GD_BOX"+id];
                   1109: 	var radioButton = formname["RADVAL"+id];
                   1110: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1111: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1112: 	gradeBox.value = pts;
                   1113: 	var resetbox = false;
                   1114: 	if (isNaN(pts) || pts < 0) {
                   1115: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1116: 	    for (var i=0; i<radioButton.length; i++) {
                   1117: 		if (radioButton[i].checked) {
                   1118: 		    gradeBox.value = i;
                   1119: 		    resetbox = true;
                   1120: 		}
                   1121: 	    }
                   1122: 	    if (!resetbox) {
                   1123: 		formtextbox.value = "";
                   1124: 	    }
                   1125: 	    return;
1.44      ng       1126: 	}
1.71      ng       1127: 
                   1128: 	if (pts > weight) {
                   1129: 	    var resp = confirm("You entered a value ("+pts+
                   1130: 			       ") greater than the weight for the part. Accept?");
                   1131: 	    if (resp == false) {
1.125     ng       1132: 		gradeBox.value = oldpts;
1.71      ng       1133: 		return;
                   1134: 	    }
1.44      ng       1135: 	}
1.13      albertel 1136: 
1.71      ng       1137: 	for (var i=0; i<radioButton.length; i++) {
                   1138: 	    radioButton[i].checked=false;
                   1139: 	    if (pts == i && pts != "") {
                   1140: 		radioButton[i].checked=true;
                   1141: 	    }
                   1142: 	}
                   1143: 	updateSelect(formname,id);
1.125     ng       1144: 	formname["stores"+id].value = "0";
1.41      ng       1145:     }
1.5       albertel 1146: 
1.72      ng       1147:     function writeBox(formname,id,pts) {
1.125     ng       1148: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1149: 	if (checkSolved(formname,id) == 'update') {
                   1150: 	    gradeBox.value = pts;
                   1151: 	} else {
1.125     ng       1152: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1153: 	    gradeBox.value = oldpts;
1.125     ng       1154: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1155: 	    for (var i=0; i<radioButton.length; i++) {
                   1156: 		radioButton[i].checked=false;
1.72      ng       1157: 		if (i == oldpts) {
1.71      ng       1158: 		    radioButton[i].checked=true;
                   1159: 		}
                   1160: 	    }
1.41      ng       1161: 	}
1.125     ng       1162: 	formname["stores"+id].value = "0";
1.71      ng       1163: 	updateSelect(formname,id);
                   1164: 	return;
1.41      ng       1165:     }
1.44      ng       1166: 
1.71      ng       1167:     function clearRadBox(formname,id) {
                   1168: 	if (checkSolved(formname,id) == 'noupdate') {
                   1169: 	    updateSelect(formname,id);
                   1170: 	    return;
                   1171: 	}
1.125     ng       1172: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1173: 	for (var i=0; i<gradeSelect.length; i++) {
                   1174: 	    if (gradeSelect[i].selected) {
                   1175: 		var selectx=i;
                   1176: 	    }
                   1177: 	}
1.125     ng       1178: 	var stores = formname["stores"+id];
1.71      ng       1179: 	if (selectx == stores.value) { return };
1.125     ng       1180: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1181: 	gradeBox.value = "";
1.125     ng       1182: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1183: 	for (var i=0; i<radioButton.length; i++) {
                   1184: 	    radioButton[i].checked=false;
                   1185: 	}
                   1186: 	stores.value = selectx;
                   1187:     }
1.5       albertel 1188: 
1.71      ng       1189:     function checkSolved(formname,id) {
1.125     ng       1190: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1191: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1192: 	    if (!reply) {return "noupdate";}
1.120     ng       1193: 	    formname.overRideScore.value = 'yes';
1.41      ng       1194: 	}
1.71      ng       1195: 	return "update";
1.13      albertel 1196:     }
1.71      ng       1197: 
                   1198:     function updateSelect(formname,id) {
1.125     ng       1199: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1200: 	return;
1.41      ng       1201:     }
1.33      ng       1202: 
1.121     ng       1203: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1204:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1205: 	formname.gradeOpt.value = val;
1.71      ng       1206: 	if (val == "Save & Next") {
                   1207: 	    for (i=0;i<=total;i++) {
                   1208: 		for (j=0;j<parttot;j++) {
1.125     ng       1209: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1210: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1211: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1212: 			if (points == "") {
1.125     ng       1213: 			    var name = formname["name"+i].value;
1.129     ng       1214: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1215: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1216: 					       ", part "+partid+". Continue?");
1.71      ng       1217: 			    if (resp == false) {
1.125     ng       1218: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1219: 				return false;
                   1220: 			    }
                   1221: 			}
                   1222: 		    }
                   1223: 		    
                   1224: 		}
                   1225: 	    }
                   1226: 	    
                   1227: 	}
1.121     ng       1228: 	if (val == "Grade Student") {
                   1229: 	    formname.showgrading.value = "yes";
                   1230: 	    if (formname.Status.value == "") {
                   1231: 		formname.Status.value = "Active";
                   1232: 	    }
                   1233: 	    formname.studentNo.value = total;
                   1234: 	}
1.120     ng       1235: 	formname.submit();
                   1236:     }
                   1237: 
1.71      ng       1238: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1239:     function checkSubmitPage(formname,total) {
                   1240: 	noscore = new Array(100);
                   1241: 	var ptr = 0;
                   1242: 	for (i=1;i<total;i++) {
1.125     ng       1243: 	    var partid = formname["q_"+i].value;
1.127     ng       1244: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1245: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1246: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1247: 		if (points == "" && status != "correct_by_student") {
                   1248: 		    noscore[ptr] = i;
                   1249: 		    ptr++;
                   1250: 		}
                   1251: 	    }
                   1252: 	}
                   1253: 	if (ptr != 0) {
                   1254: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1255: 	    var prolist = "";
                   1256: 	    if (ptr == 1) {
                   1257: 		prolist = noscore[0];
                   1258: 	    } else {
                   1259: 		var i = 0;
                   1260: 		while (i < ptr-1) {
                   1261: 		    prolist += noscore[i]+", ";
                   1262: 		    i++;
                   1263: 		}
                   1264: 		prolist += "and "+noscore[i];
                   1265: 	    }
                   1266: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1267: 	    if (resp == false) {
                   1268: 		return false;
                   1269: 	    }
                   1270: 	}
1.45      ng       1271: 
1.71      ng       1272: 	formname.submit();
                   1273:     }
                   1274: </script>
                   1275: SUBJAVASCRIPT
                   1276: }
1.45      ng       1277: 
1.71      ng       1278: #--- javascript for essay type problem --
                   1279: sub sub_page_kw_js {
                   1280:     my $request = shift;
1.80      ng       1281:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1282:     &commonJSfunctions($request);
1.350     albertel 1283: 
1.351     albertel 1284:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1285:     <script text="text/javascript">
                   1286:     function checkInput() {
                   1287:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1288:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1289:       var usrctr = document.msgcenter.usrctr.value;
                   1290:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1291:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1292: 
                   1293:       var msgchk = "";
                   1294:       if (document.msgcenter.subchk.checked) {
                   1295:          msgchk = "msgsub,";
                   1296:       }
                   1297:       var includemsg = 0;
                   1298:       for (var i=1; i<=nmsg; i++) {
                   1299:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1300:           var frmmsg = document.msgcenter["msg"+i];
                   1301:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1302:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1303:           showflg.value = "1";
                   1304:           var chkbox = document.msgcenter["msgn"+i];
                   1305:           if (chkbox.checked) {
                   1306:              msgchk += "savemsg"+i+",";
                   1307:              includemsg = 1;
                   1308:           }
                   1309:       }
                   1310:       if (document.msgcenter.newmsgchk.checked) {
                   1311:          msgchk += "newmsg"+usrctr;
                   1312:          includemsg = 1;
                   1313:       }
                   1314:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1315:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1316:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1317:       includemsg.value = msgchk;
                   1318: 
                   1319:       self.close()
                   1320: 
                   1321:     }
                   1322:     </script>
                   1323: INNERJS
                   1324: 
1.351     albertel 1325:     my $inner_js_highlight_central=<<INNERJS;
                   1326:  <script type="text/javascript">
                   1327:     function updateChoice(flag) {
                   1328:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1329:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1330:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1331:       opener.document.SCORE.refresh.value = "on";
                   1332:       if (opener.document.SCORE.keywords.value!=""){
                   1333:          opener.document.SCORE.submit();
                   1334:       }
                   1335:       self.close()
                   1336:     }
                   1337: </script>
                   1338: INNERJS
                   1339: 
                   1340:     my $start_page_msg_central = 
                   1341:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1342: 				       {'js_ready'  => 1,
                   1343: 					'only_body' => 1,
                   1344: 					'bgcolor'   =>'#FFFFFF',});
                   1345:     my $end_page_msg_central = 
                   1346: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1347: 
                   1348: 
                   1349:     my $start_page_highlight_central = 
                   1350:         &Apache::loncommon::start_page('Highlight Central',
                   1351: 				       $inner_js_highlight_central,
1.350     albertel 1352: 				       {'js_ready'  => 1,
                   1353: 					'only_body' => 1,
                   1354: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1355:     my $end_page_highlight_central = 
1.350     albertel 1356: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1357: 
1.219     www      1358:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1359:     $docopen=~s/^document\.//;
1.71      ng       1360:     $request->print(<<SUBJAVASCRIPT);
                   1361: <script type="text/javascript" language="javascript">
1.45      ng       1362: 
1.44      ng       1363: //===================== Show list of keywords ====================
1.122     ng       1364:   function keywords(formname) {
                   1365:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1366:     if (nret==null) return;
1.122     ng       1367:     formname.keywords.value = nret;
1.44      ng       1368: 
1.122     ng       1369:     if (formname.keywords.value != "") {
1.128     ng       1370: 	formname.refresh.value = "on";
1.122     ng       1371: 	formname.submit();
1.44      ng       1372:     }
                   1373:     return;
                   1374:   }
                   1375: 
                   1376: //===================== Script to view submitted by ==================
                   1377:   function viewSubmitter(submitter) {
                   1378:     document.SCORE.refresh.value = "on";
                   1379:     document.SCORE.NCT.value = "1";
                   1380:     document.SCORE.unamedom0.value = submitter;
                   1381:     document.SCORE.submit();
                   1382:     return;
                   1383:   }
                   1384: 
                   1385: //===================== Script to add keyword(s) ==================
                   1386:   function getSel() {
                   1387:     if (document.getSelection) txt = document.getSelection();
                   1388:     else if (document.selection) txt = document.selection.createRange().text;
                   1389:     else return;
                   1390:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1391:     if (cleantxt=="") {
1.46      ng       1392: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1393: 	return;
                   1394:     }
                   1395:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1396:     if (nret==null) return;
1.127     ng       1397:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1398:     if (document.SCORE.keywords.value != "") {
1.127     ng       1399: 	document.SCORE.refresh.value = "on";
1.44      ng       1400: 	document.SCORE.submit();
                   1401:     }
                   1402:     return;
                   1403:   }
                   1404: 
                   1405: //====================== Script for composing message ==============
1.80      ng       1406:    // preload images
                   1407:    img1 = new Image();
                   1408:    img1.src = "$iconpath/mailbkgrd.gif";
                   1409:    img2 = new Image();
                   1410:    img2.src = "$iconpath/mailto.gif";
                   1411: 
1.44      ng       1412:   function msgCenter(msgform,usrctr,fullname) {
                   1413:     var Nmsg  = msgform.savemsgN.value;
                   1414:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1415:     var subject = msgform.msgsub.value;
1.127     ng       1416:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1417:     re = /msgsub/;
                   1418:     var shwsel = "";
                   1419:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1420:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1421:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1422:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1423: 	var testmsg = "savemsg"+i+",";
                   1424: 	re = new RegExp(testmsg,"g");
1.44      ng       1425: 	shwsel = "";
                   1426: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1427: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1428: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1429: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1430: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1431:     }
1.125     ng       1432:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1433:     shwsel = "";
                   1434:     re = /newmsg/;
                   1435:     if (re.test(msgchk)) { shwsel = "checked" }
                   1436:     newMsg(newmsg,shwsel);
                   1437:     msgTail(); 
                   1438:     return;
                   1439:   }
                   1440: 
1.123     ng       1441:   function checkEntities(strx) {
                   1442:     if (strx.length == 0) return strx;
                   1443:     var orgStr = ["&", "<", ">", '"']; 
                   1444:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1445:     var counter = 0;
                   1446:     while (counter < 4) {
                   1447: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1448: 	counter++;
                   1449:     }
                   1450:     return strx;
                   1451:   }
                   1452: 
                   1453:   function strReplace(strx, orgStr, newStr) {
                   1454:     return strx.split(orgStr).join(newStr);
                   1455:   }
                   1456: 
1.44      ng       1457:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1458:     var height = 70*Nmsg+250;
1.44      ng       1459:     var scrollbar = "no";
                   1460:     if (height > 600) {
                   1461: 	height = 600;
                   1462: 	scrollbar = "yes";
                   1463:     }
1.118     ng       1464:     var xpos = (screen.width-600)/2;
                   1465:     xpos = (xpos < 0) ? '0' : xpos;
                   1466:     var ypos = (screen.height-height)/2-30;
                   1467:     ypos = (ypos < 0) ? '0' : ypos;
                   1468: 
1.206     albertel 1469:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1470:     pWin.focus();
                   1471:     pDoc = pWin.document;
1.219     www      1472:     pDoc.$docopen;
1.351     albertel 1473:     pDoc.write('$start_page_msg_central');
1.76      ng       1474: 
                   1475:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1476:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1477:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1478: 
                   1479:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1480:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1481:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1482: }
                   1483:     function displaySubject(msg,shwsel) {
1.76      ng       1484:     pDoc = pWin.document;
                   1485:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1486:     pDoc.write("<td>Subject</td>");
                   1487:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1488:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1489: }
                   1490: 
1.72      ng       1491:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1492:     pDoc = pWin.document;
                   1493:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1494:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1495:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1496:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1497: }
                   1498: 
                   1499:   function newMsg(newmsg,shwsel) {
1.76      ng       1500:     pDoc = pWin.document;
                   1501:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1502:     pDoc.write("<td align=\\"center\\">New</td>");
                   1503:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1504:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1505: }
                   1506: 
                   1507:   function msgTail() {
1.76      ng       1508:     pDoc = pWin.document;
                   1509:     pDoc.write("</table>");
                   1510:     pDoc.write("</td></tr></table>&nbsp;");
                   1511:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1512:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1513:     pDoc.write("</form>");
1.351     albertel 1514:     pDoc.write('$end_page_msg_central');
1.128     ng       1515:     pDoc.close();
1.44      ng       1516: }
                   1517: 
                   1518: //====================== Script for keyword highlight options ==============
                   1519:   function kwhighlight() {
                   1520:     var kwclr    = document.SCORE.kwclr.value;
                   1521:     var kwsize   = document.SCORE.kwsize.value;
                   1522:     var kwstyle  = document.SCORE.kwstyle.value;
                   1523:     var redsel = "";
                   1524:     var grnsel = "";
                   1525:     var blusel = "";
                   1526:     if (kwclr=="red")   {var redsel="checked"};
                   1527:     if (kwclr=="green") {var grnsel="checked"};
                   1528:     if (kwclr=="blue")  {var blusel="checked"};
                   1529:     var sznsel = "";
                   1530:     var sz1sel = "";
                   1531:     var sz2sel = "";
                   1532:     if (kwsize=="0")  {var sznsel="checked"};
                   1533:     if (kwsize=="+1") {var sz1sel="checked"};
                   1534:     if (kwsize=="+2") {var sz2sel="checked"};
                   1535:     var synsel = "";
                   1536:     var syisel = "";
                   1537:     var sybsel = "";
                   1538:     if (kwstyle=="")    {var synsel="checked"};
                   1539:     if (kwstyle=="<i>") {var syisel="checked"};
                   1540:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1541:     highlightCentral();
                   1542:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1543:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1544:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1545:     highlightend();
                   1546:     return;
                   1547:   }
                   1548: 
                   1549:   function highlightCentral() {
1.76      ng       1550: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1551:     var xpos = (screen.width-400)/2;
                   1552:     xpos = (xpos < 0) ? '0' : xpos;
                   1553:     var ypos = (screen.height-330)/2-30;
                   1554:     ypos = (ypos < 0) ? '0' : ypos;
                   1555: 
1.206     albertel 1556:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1557:     hwdWin.focus();
                   1558:     var hDoc = hwdWin.document;
1.219     www      1559:     hDoc.$docopen;
1.351     albertel 1560:     hDoc.write('$start_page_highlight_central');
1.76      ng       1561:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1562:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1563: 
                   1564:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1565:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1566:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1567:   }
                   1568: 
                   1569:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1570:     var hDoc = hwdWin.document;
                   1571:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1572:     hDoc.write("<td align=\\"left\\">");
                   1573:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1574:     hDoc.write("<td align=\\"left\\">");
                   1575:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1576:     hDoc.write("<td align=\\"left\\">");
                   1577:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1578:     hDoc.write("</tr>");
1.44      ng       1579:   }
                   1580: 
                   1581:   function highlightend() { 
1.76      ng       1582:     var hDoc = hwdWin.document;
                   1583:     hDoc.write("</table>");
                   1584:     hDoc.write("</td></tr></table>&nbsp;");
                   1585:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1586:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1587:     hDoc.write("</form>");
1.351     albertel 1588:     hDoc.write('$end_page_highlight_central');
1.128     ng       1589:     hDoc.close();
1.44      ng       1590:   }
                   1591: 
                   1592: </script>
                   1593: SUBJAVASCRIPT
                   1594: }
                   1595: 
1.349     albertel 1596: sub get_increment {
1.348     bowersj2 1597:     my $increment = $env{'form.increment'};
                   1598:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1599:         $increment != .1) {
                   1600:         $increment = 1;
                   1601:     }
                   1602:     return $increment;
                   1603: }
                   1604: 
1.71      ng       1605: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1606: sub gradeBox {
1.322     albertel 1607:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1608:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1609: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1610: 	'/check.gif" height="16" border="0" />';
                   1611:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1612:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1613: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1614:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1615:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1616: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1617:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1618:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1619:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1620: 				       [$partid]);
                   1621:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1622:     if ($last_resets{$partid}) {
                   1623:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1624:     }
1.71      ng       1625:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1626: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1627:     my $ctr = 0;
1.348     bowersj2 1628:     my $thisweight = 0;
1.349     albertel 1629:     my $increment = &get_increment();
1.71      ng       1630:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1631:     while ($thisweight<=$wgt) {
1.381     albertel 1632: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1633: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1634: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1635: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1636: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1637:         $thisweight += $increment;
1.71      ng       1638: 	$ctr++;
                   1639:     }
                   1640:     $result.='</tr></table>';
                   1641:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1642:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1643: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1644: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1645: 	$wgt.')" /></td>'."\n";
                   1646:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1647: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1648: 	' </td><td>'."\n";
                   1649:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1650: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1651:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1652: 	$result.='<option></option>'.
1.401     albertel 1653: 	    '<option selected="selected">excused</option>';
1.71      ng       1654:     } else {
1.401     albertel 1655: 	$result.='<option selected="selected"></option>'.
1.125     ng       1656: 	    '<option>excused</option>';
1.71      ng       1657:     }
1.125     ng       1658:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1659:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1660:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1661: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1662: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1663: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1664:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1665:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1666:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1667:         $aggtries.'" />'."\n";
1.71      ng       1668:     $result.='</td></tr></table>'."\n";
1.323     banghart 1669:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1670:     return $result;
                   1671: }
1.322     albertel 1672: 
                   1673: sub handback_box {
1.323     banghart 1674:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1675:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1676:     my (@respids);
1.375     albertel 1677:      my @part_response_id = &flatten_responseType($responseType);
                   1678:     foreach my $part_response_id (@part_response_id) {
                   1679:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1680:         if ($part eq $partid) {
1.375     albertel 1681:             push(@respids,$resp);
1.323     banghart 1682:         }
                   1683:     }
1.318     banghart 1684:     my $result;
1.323     banghart 1685:     foreach my $respid (@respids) {
1.322     albertel 1686: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1687: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1688: 	next if (!@$files);
                   1689: 	my $file_counter = 1;
1.313     banghart 1690: 	foreach my $file (@$files) {
1.368     banghart 1691: 	    if ($file =~ /\/portfolio\//) {
                   1692:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1693:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1694:     	        $file_disp = "$name.$ext";
                   1695:     	        $file = $file_path.$file_disp;
                   1696:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1697:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1698:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1699:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1700:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1701:     	        $file_counter++;
                   1702: 	    }
1.322     albertel 1703: 	}
1.313     banghart 1704:     }
1.318     banghart 1705:     return $result;    
1.71      ng       1706: }
1.44      ng       1707: 
1.58      albertel 1708: sub show_problem {
1.382     albertel 1709:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1710:     my $rendered;
1.382     albertel 1711:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1712:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1713:     if ($mode eq 'both' or $mode eq 'text') {
                   1714: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1715: 						       $env{'request.course.id'},
                   1716: 						       undef,\%form);
1.144     albertel 1717:     }
1.58      albertel 1718:     if ($removeform) {
                   1719: 	$rendered=~s|<form(.*?)>||g;
                   1720: 	$rendered=~s|</form>||g;
1.374     albertel 1721: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1722:     }
1.144     albertel 1723:     my $companswer;
                   1724:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1725: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1726: 	$companswer=
                   1727: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1728: 						    $env{'request.course.id'},
                   1729: 						    %form);
1.144     albertel 1730:     }
1.58      albertel 1731:     if ($removeform) {
                   1732: 	$companswer=~s|<form(.*?)>||g;
                   1733: 	$companswer=~s|</form>||g;
1.144     albertel 1734: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1735:     }
                   1736:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1737:     $result.='<table border="0" width="100%">';
1.144     albertel 1738:     if ($viewon) {
                   1739: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1740: 	if ($mode eq 'both' or $mode eq 'text') {
                   1741: 	    $result.='View of the problem - ';
                   1742: 	} else {
                   1743: 	    $result.='Correct answer: ';
                   1744: 	}
1.257     albertel 1745: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1746:     }
                   1747:     if ($mode eq 'both') {
                   1748: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1749: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1750:     } elsif ($mode eq 'text') {
                   1751: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1752:     } elsif ($mode eq 'answer') {
                   1753: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1754:     }
1.58      albertel 1755:     $result.='</td></tr></table>';
                   1756:     $result.='</td></tr></table><br />';
1.71      ng       1757:     return $result;
1.58      albertel 1758: }
1.397     albertel 1759: 
1.396     banghart 1760: sub files_exist {
                   1761:     my ($r, $symb) = @_;
                   1762:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1763: 
1.396     banghart 1764:     foreach my $student (@students) {
                   1765:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1766:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1767: 					      $udom,$uname);
1.396     banghart 1768:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1769:         foreach my $submission (@$string) {
                   1770:             my ($partid,$respid) =
                   1771: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1772:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1773: 					   \%record);
                   1774:             return 1 if (@$files);
1.396     banghart 1775:         }
                   1776:     }
1.397     albertel 1777:     return 0;
1.396     banghart 1778: }
1.397     albertel 1779: 
1.394     banghart 1780: sub download_all_link {
                   1781:     my ($r,$symb) = @_;
1.395     albertel 1782:     my $all_students = 
                   1783: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1784: 
                   1785:     my $parts =
                   1786: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1787: 
1.394     banghart 1788:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1789:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1790:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1791:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1792:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1793: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1794:     return
                   1795: }
1.395     albertel 1796: 
1.432     banghart 1797: sub build_section_inputs {
                   1798:     my $section_inputs;
                   1799:     if ($env{'form.section'} eq '') {
                   1800:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1801:     } else {
                   1802:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1803:         foreach my $section (@sections) {
1.432     banghart 1804:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1805:         }
                   1806:     }
                   1807:     return $section_inputs;
                   1808: }
                   1809: 
1.44      ng       1810: # --------------------------- show submissions of a student, option to grade 
                   1811: sub submission {
                   1812:     my ($request,$counter,$total) = @_;
1.257     albertel 1813:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1814:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1815:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1816:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1817:     my $symb = &get_symb($request); 
                   1818:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1819: 
                   1820:     if (!&canview($usec)) {
1.398     albertel 1821: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1822: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1823: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1824: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1825: 	return;
                   1826:     }
                   1827: 
1.257     albertel 1828:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1829:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1830:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1831:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1832:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1833: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1834: 	'/check.gif" height="16" border="0" />';
1.41      ng       1835: 
1.426     albertel 1836:     my %old_essays;
1.41      ng       1837:     # header info
                   1838:     if ($counter == 0) {
                   1839: 	&sub_page_js($request);
1.257     albertel 1840: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1841: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1842: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1843: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1844: 	    &download_all_link($request, $symb);
                   1845: 	}
1.398     albertel 1846: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1847: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1848: 
1.257     albertel 1849: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1850: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1851: 		$checkIcon.' symbol.'."\n";
                   1852: 	    $request->print($checkMark);
                   1853: 	}
1.41      ng       1854: 
1.44      ng       1855: 	# option to display problem, only once else it cause problems 
                   1856:         # with the form later since the problem has a form.
1.257     albertel 1857: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1858: 	    my $mode;
1.257     albertel 1859: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1860: 		$mode='both';
1.257     albertel 1861: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1862: 		$mode='text';
1.257     albertel 1863: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1864: 		$mode='answer';
                   1865: 	    }
1.329     albertel 1866: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1867: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1868: 	}
1.441     www      1869: 
1.44      ng       1870: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1871:         # if this subroutine has been called once.
1.41      ng       1872: 	my %keyhash = ();
1.257     albertel 1873: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1874: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1875: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1876: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1877: 
1.257     albertel 1878: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1879: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1880: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1881: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1882: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1883: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1884: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1885: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1886: 	}
1.257     albertel 1887: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1888: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1889: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1890: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1891: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1892: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1893: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1894: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1895: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1896: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1897: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1898: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1899: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1900: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1901: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1902: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1903: 			&build_section_inputs().
1.326     albertel 1904: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1905: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1906: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1907: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1908: 	if ($env{'form.handgrade'} eq 'yes') {
                   1909: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1910: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1911: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1912: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1913: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1914: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1915: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1916: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1917: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1918: 	    }
1.123     ng       1919: 	}
1.41      ng       1920: 	
                   1921: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1922: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1923: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1924: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1925: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1926: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1927: 		'" />'."\n".
                   1928: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1929: 	    $cts++;
                   1930: 	}
                   1931: 	$request->print($prnmsg);
1.32      ng       1932: 
1.257     albertel 1933: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1934: #
                   1935: # Print out the keyword options line
                   1936: #
1.41      ng       1937: 	    $request->print(<<KEYWORDS);
1.38      ng       1938: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1939: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1940: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1941:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1942: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1943: KEYWORDS
1.88      www      1944: #
                   1945: # Load the other essays for similarity check
                   1946: #
1.324     albertel 1947:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1948: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1949: 	    $apath=&escape($apath);
1.88      www      1950: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1951: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1952:         }
                   1953:     }
1.44      ng       1954: 
1.441     www      1955: # This is where output for one specific student would start
                   1956:     my $bgcolor='#DDEEDD';
                   1957:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1958:     $request->print("\n\n".
                   1959:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1960: 
1.257     albertel 1961:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1962: 	my $mode;
1.257     albertel 1963: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1964: 	    $mode='both';
1.257     albertel 1965: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1966: 	    $mode='text';
1.257     albertel 1967: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1968: 	    $mode='answer';
                   1969: 	}
1.329     albertel 1970: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1971: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1972:     }
1.144     albertel 1973: 
1.257     albertel 1974:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1975:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1976: 
1.44      ng       1977:     # Display student info
1.41      ng       1978:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1979:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1980: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1981: 
1.257     albertel 1982:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1983:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1984: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1985: 
1.118     ng       1986:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1987:     my @col_fullnames;
1.56      matthew  1988:     my ($classlist,$fullname);
1.257     albertel 1989:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1990: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1991: 	for (keys (%$handgrade)) {
1.44      ng       1992: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1993: 					    '.maxcollaborators',
                   1994:                                             $symb,$udom,$uname);
                   1995: 	    next if ($ncol <= 0);
                   1996:             s/\_/\./g;
                   1997:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1998:             my @goodcollaborators = ();
                   1999:             my @badcollaborators  = ();
                   2000: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   2001: 		$_ =~ s/[\$\^\(\)]//g;
                   2002: 		next if ($_ eq '');
1.80      ng       2003: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       2004: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       2005: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       2006: 		# Doing this grep allows 'fuzzy' specification
                   2007: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   2008: 		if (! scalar(@Matches)) {
                   2009: 		    push @badcollaborators,$_;
                   2010: 		} else {
                   2011: 		    push @goodcollaborators, @Matches;
                   2012: 		}
1.80      ng       2013: 	    }
1.86      ng       2014:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  2015:                 $result.='<b>Collaborators: </b>';
1.86      ng       2016:                 foreach (@goodcollaborators) {
                   2017: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   2018: 		    push @col_fullnames, $givenn.' '.$lastname;
                   2019: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   2020: 		}
1.57      matthew  2021:                 $result.='<br />'."\n";
1.150     albertel 2022: 		my ($part)=split(/\./,$_);
1.86      ng       2023: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 2024: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2025: 		    "\n";
1.86      ng       2026: 	    }
                   2027: 	    if (scalar(@badcollaborators) > 0) {
                   2028: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2029: 		$result.='This student has submitted ';
                   2030: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2031: 		$result .= ': '.join(', ',@badcollaborators);
                   2032: 		$result .= '</td></tr></table>';
                   2033: 	    }         
                   2034: 	    if (scalar(@badcollaborators > $ncol)) {
                   2035: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2036: 		$result .= 'This student has submitted too many '.
                   2037: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2038: 		$result .= '</td></tr></table>';
                   2039: 	    }
1.41      ng       2040: 	}
                   2041:     }
1.44      ng       2042:     $request->print($result."\n");
1.33      ng       2043: 
1.44      ng       2044:     # print student answer/submission
                   2045:     # Options are (1) Handgaded submission only
                   2046:     #             (2) Last submission, includes submission that is not handgraded 
                   2047:     #                  (for multi-response type part)
                   2048:     #             (3) Last submission plus the parts info
                   2049:     #             (4) The whole record for this student
1.257     albertel 2050:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2051: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2052: 	my $lastsubonly=''.
                   2053: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2054: 	     $$timestamp)."</td></tr>\n";
                   2055: 	if ($$timestamp eq '') {
                   2056: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2057: 	} else {
                   2058: 	    my %seenparts;
1.375     albertel 2059: 	    my @part_response_id = &flatten_responseType($responseType);
                   2060: 	    foreach my $part (@part_response_id) {
1.393     albertel 2061: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2062: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2063: 
1.375     albertel 2064: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2065: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2066: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2067: 		    if (exists($seenparts{$partid})) { next; }
                   2068: 		    $seenparts{$partid}=1;
1.207     albertel 2069: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2070: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2071: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2072: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2073: 			'\');" target="_self">'.
1.257     albertel 2074: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2075: 		    $request->print($submitby);
                   2076: 		    next;
                   2077: 		}
                   2078: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2079: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2080: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2081: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2082: 			' )</span>&nbsp; &nbsp;'.
                   2083: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2084: 		    next;
                   2085: 		}
                   2086: 		foreach (@$string) {
                   2087: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2088: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2089: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2090: 		    # Similarity check
                   2091: 		    my $similar='';
1.257     albertel 2092: 		    if($env{'form.checkPlag'}){
1.151     albertel 2093: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2094: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2095: 			if ($osim) {
                   2096: 			    $osim=int($osim*100.0);
1.426     albertel 2097: 			    my %old_course_desc = 
                   2098: 				&Apache::lonnet::coursedescription($ocrsid,
                   2099: 								   {'one_time' => 1});
                   2100: 
                   2101: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2102: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2103: 				    $osim,
                   2104: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2105: 				    $oname,$odom,
1.426     albertel 2106: 				    $old_course_desc{'description'},
1.427     albertel 2107: 				    $old_course_desc{'num'},
1.426     albertel 2108: 				    $old_course_desc{'domain'}).
1.398     albertel 2109: 				'</span></h3><blockquote><i>'.
1.151     albertel 2110: 				&keywords_highlight($oessay).
                   2111: 				'</i></blockquote><hr />';
                   2112: 			}
1.150     albertel 2113: 		    }
1.151     albertel 2114: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2115: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2116: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2117: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2118: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2119: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2120: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2121: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2122: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2123: 			if (@$files) {
1.398     albertel 2124: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2125: 			    my $file_counter = 0;
1.313     banghart 2126: 			    foreach my $file (@$files) {
1.303     banghart 2127: 			        $file_counter ++;
1.232     albertel 2128: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2129: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2130: 			    }
1.236     albertel 2131: 			    $lastsubonly.='<br />';
1.41      ng       2132: 			}
1.151     albertel 2133: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2134: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2135: 					 $respid,\%record,$order);
                   2136: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2137: 		    }
                   2138: 		}
                   2139: 	    }
1.151     albertel 2140: 	}
                   2141: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2142: 	$request->print($lastsubonly);
1.257     albertel 2143:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2144: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2145: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2146:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2147: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2148: 								 $env{'request.course.id'},
1.44      ng       2149: 								 $last,'.submission',
                   2150: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2151:     }
1.120     ng       2152: 
1.121     ng       2153:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2154: 	.$udom.'" />'."\n");
1.41      ng       2155:     
1.44      ng       2156:     # return if view submission with no grading option
1.257     albertel 2157:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2158: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2159: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2160: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2161: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2162: 	if (($env{'form.command'} eq 'submission') || 
                   2163: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2164: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2165: 	}
1.180     albertel 2166: 	$request->print($toGrade);
1.41      ng       2167: 	return;
1.180     albertel 2168:     } else {
                   2169: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2170:     }
1.33      ng       2171: 
1.121     ng       2172:     # essay grading message center
1.257     albertel 2173:     if ($env{'form.handgrade'} eq 'yes') {
                   2174: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2175: 	my $msgfor = $givenn.' '.$lastname;
                   2176: 	if (scalar(@col_fullnames) > 0) {
                   2177: 	    my $lastone = pop @col_fullnames;
                   2178: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2179: 	}
                   2180: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2181: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2182: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2183: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2184: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2185: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2186: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2187: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2188: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2189: 	    '<br />&nbsp;('.
                   2190: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2191: 	$request->print($result);
1.118     ng       2192:     }
1.300     albertel 2193:     if ($perm{'vgr'}) {
1.297     www      2194: 	$request->print('<br />'.
1.300     albertel 2195: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2196: 						   $uname,$udom,'check'));
1.297     www      2197:     }
1.300     albertel 2198:     if ($perm{'opa'}) {
1.297     www      2199: 	$request->print('<br />'.
1.300     albertel 2200: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2201: 					 $uname,$udom,$symb,'check'));
1.297     www      2202:     }
1.41      ng       2203: 
                   2204:     my %seen = ();
                   2205:     my @partlist;
1.129     ng       2206:     my @gradePartRespid;
1.375     albertel 2207:     my @part_response_id = &flatten_responseType($responseType);
                   2208:     foreach my $part_response_id (@part_response_id) {
                   2209:     	my ($partid,$respid) = @{ $part_response_id };
                   2210: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2211: 	next if ($seen{$partid} > 0);
1.41      ng       2212: 	$seen{$partid}++;
1.393     albertel 2213: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2214: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2215: 	push @partlist,$partid;
1.129     ng       2216: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2217: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2218:     }
1.45      ng       2219:     $result='<input type="hidden" name="partlist'.$counter.
                   2220: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2221:     $result.='<input type="hidden" name="gradePartRespid'.
                   2222: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2223:     my $ctr = 0;
                   2224:     while ($ctr < scalar(@partlist)) {
                   2225: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2226: 	    $partlist[$ctr].'" />'."\n";
                   2227: 	$ctr++;
                   2228:     }
                   2229:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2230: 
1.441     www      2231: # Done with printing info for one student
                   2232: 
                   2233:     $request->print('</td></tr></table></p>');
                   2234: 
                   2235: 
1.41      ng       2236:     # print end of form
                   2237:     if ($counter == $total) {
1.297     www      2238: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2239: 	$endform.='<input type="button" value="Save & Next" '.
                   2240: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2241: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2242: 	my $ntstu ='<select name="NTSTU">'.
                   2243: 	    '<option>1</option><option>2</option>'.
                   2244: 	    '<option>3</option><option>5</option>'.
                   2245: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2246: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2247: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2248: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2249: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2250: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2251: 	    '<input type="button" value="Next" '.
1.417     albertel 2252: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2253: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2254:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2255:             "' name='increment' />";
1.45      ng       2256: 	$endform.='</td><tr></table></form>';
1.324     albertel 2257: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2258: 	$request->print($endform);
                   2259:     }
                   2260:     return '';
1.38      ng       2261: }
                   2262: 
1.44      ng       2263: #--- Retrieve the last submission for all the parts
1.38      ng       2264: sub get_last_submission {
1.119     ng       2265:     my ($returnhash)=@_;
1.46      ng       2266:     my (@string,$timestamp);
1.119     ng       2267:     if ($$returnhash{'version'}) {
1.46      ng       2268: 	my %lasthash=();
                   2269: 	my ($version);
1.119     ng       2270: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2271: 	    foreach my $key (sort(split(/\:/,
                   2272: 					$$returnhash{$version.':keys'}))) {
                   2273: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2274: 		$timestamp = 
                   2275: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2276: 	    }
                   2277: 	}
1.397     albertel 2278: 	foreach my $key (keys(%lasthash)) {
                   2279: 	    next if ($key !~ /\.submission$/);
                   2280: 
                   2281: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2282: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2283: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2284: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2285: 	}
                   2286:     }
1.397     albertel 2287:     if (!@string) {
                   2288: 	$string[0] =
1.398     albertel 2289: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2290:     }
                   2291:     return (\@string,\$timestamp);
1.38      ng       2292: }
1.35      ng       2293: 
1.44      ng       2294: #--- High light keywords, with style choosen by user.
1.38      ng       2295: sub keywords_highlight {
1.44      ng       2296:     my $string    = shift;
1.257     albertel 2297:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2298:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2299:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2300:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2301:     foreach my $keyword (@keylist) {
                   2302: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2303:     }
                   2304:     return $string;
1.38      ng       2305: }
1.36      ng       2306: 
1.44      ng       2307: #--- Called from submission routine
1.38      ng       2308: sub processHandGrade {
1.41      ng       2309:     my ($request) = shift;
1.324     albertel 2310:     my $symb   = &get_symb($request);
                   2311:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2312:     my $button = $env{'form.gradeOpt'};
                   2313:     my $ngrade = $env{'form.NCT'};
                   2314:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2315:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2316:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2317: 
1.44      ng       2318:     if ($button eq 'Save & Next') {
                   2319: 	my $ctr = 0;
                   2320: 	while ($ctr < $ngrade) {
1.257     albertel 2321: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2322: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2323: 	    if ($errorflag eq 'no_score') {
                   2324: 		$ctr++;
                   2325: 		next;
                   2326: 	    }
1.104     albertel 2327: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2328: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2329: 		$ctr++;
                   2330: 		next;
                   2331: 	    }
1.257     albertel 2332: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2333: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2334: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2335:             my ($feedurl,$showsymb) =
                   2336: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2337: 	    my $messagetail;
1.62      albertel 2338: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2339: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2340: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2341: 		$subject.=' ['.$restitle.']';
1.44      ng       2342: 		my (@msgnum) = split(/,/,$includemsg);
                   2343: 		foreach (@msgnum) {
1.257     albertel 2344: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2345: 		}
1.80      ng       2346: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2347: 		if ($env{'form.withgrades'.$ctr}) {
                   2348: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2349: 		    $messagetail = " for <a href=\"".
1.418     albertel 2350: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2351: 		}
                   2352: 		$msgstatus = 
                   2353:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2354: 						     $message.$messagetail,
1.418     albertel 2355:                                                      undef,$feedurl,undef,
1.386     raeburn  2356:                                                      undef,undef,$showsymb,
                   2357:                                                      $restitle);
                   2358: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2359: 				$msgstatus);
1.44      ng       2360: 	    }
1.257     albertel 2361: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2362: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2363: 		foreach my $collabstr (@collabstrs) {
                   2364: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2365: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2366: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2367: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2368: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2369: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2370: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2371: 			    next;
1.418     albertel 2372: 			} elsif ($message ne '') {
                   2373: 			    my ($baseurl,$showsymb) = 
                   2374: 				&get_feedurl_and_symb($symb,$collaborator,
                   2375: 						      $udom);
                   2376: 			    if ($env{'form.withgrades'.$ctr}) {
                   2377: 				$messagetail = " for <a href=\"".
1.386     raeburn  2378:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2379: 			    }
1.418     albertel 2380: 			    $msgstatus = 
                   2381: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2382: 			}
1.44      ng       2383: 		    }
                   2384: 		}
                   2385: 	    }
                   2386: 	    $ctr++;
                   2387: 	}
                   2388:     }
                   2389: 
1.257     albertel 2390:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2391: 	# Keywords sorted in alphabatical order
1.257     albertel 2392: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2393: 	my %keyhash = ();
1.257     albertel 2394: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2395: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2396: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2397: 	$env{'form.keywords'} = join(' ',@keywords);
                   2398: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2399: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2400: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2401: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2402: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2403: 
                   2404: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2405: 	# New messages are saved in env for the next student.
1.119     ng       2406: 	# All messages are saved in nohist_handgrade.db
                   2407: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2408: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2409: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2410: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2411: 		$idx++;
                   2412: 	    }
                   2413: 	    $ctr++;
1.41      ng       2414: 	}
1.119     ng       2415: 	$ctr = 0;
                   2416: 	while ($ctr < $ngrade) {
1.257     albertel 2417: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2418: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2419: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2420: 		$idx++;
                   2421: 	    }
                   2422: 	    $ctr++;
1.41      ng       2423: 	}
1.257     albertel 2424: 	$env{'form.savemsgN'} = --$idx;
                   2425: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2426: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2427: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2428:     }
1.44      ng       2429:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2430:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2431:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2432: 	my ($ctr,$total) = (0,0);
                   2433: 	while ($ctr < $ngrade) {
1.257     albertel 2434: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2435: 	    $ctr++;
                   2436: 	}
1.257     albertel 2437: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2438: 	$ctr = 0;
                   2439: 	while ($ctr < $total) {
1.257     albertel 2440: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2441: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2442: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2443: 	    &submission($request,$ctr,$total-1);
1.41      ng       2444: 	    $ctr++;
                   2445: 	}
                   2446: 	return '';
                   2447:     }
1.36      ng       2448: 
1.121     ng       2449: # Go directly to grade student - from submission or link from chart page
1.120     ng       2450:     if ($button eq 'Grade Student') {
1.324     albertel 2451: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2452: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2453: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2454: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2455: 	&submission($request,0,0);
                   2456: 	return '';
                   2457:     }
                   2458: 
1.44      ng       2459:     # Get the next/previous one or group of students
1.257     albertel 2460:     my $firststu = $env{'form.unamedom0'};
                   2461:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2462:     my $ctr = 2;
1.41      ng       2463:     while ($laststu eq '') {
1.257     albertel 2464: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2465: 	$ctr++;
                   2466: 	$laststu = $firststu if ($ctr > $ngrade);
                   2467:     }
1.44      ng       2468: 
1.41      ng       2469:     my (@parsedlist,@nextlist);
                   2470:     my ($nextflg) = 0;
1.294     albertel 2471:     foreach (sort 
                   2472: 	     {
                   2473: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2474: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2475: 		 }
                   2476: 		 return $a cmp $b;
                   2477: 	     } (keys(%$fullname))) {
1.41      ng       2478: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2479: 	    push @parsedlist,$_;
                   2480: 	}
                   2481: 	$nextflg = 1 if ($_ eq $laststu);
                   2482: 	if ($button eq 'Previous') {
                   2483: 	    last if ($_ eq $firststu);
                   2484: 	    push @parsedlist,$_;
                   2485: 	}
                   2486:     }
                   2487:     $ctr = 0;
                   2488:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2489:     my ($partlist) = &response_type($symb);
1.41      ng       2490:     foreach my $student (@parsedlist) {
1.257     albertel 2491: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2492: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2493: 	
                   2494: 	if ($submitonly eq 'queued') {
                   2495: 	    my %queue_status = 
                   2496: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2497: 							$udom,$uname);
                   2498: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2499: 	}
                   2500: 
1.156     albertel 2501: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2502: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2503: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2504: 	    my $submitted = 0;
1.248     albertel 2505: 	    my $ungraded = 0;
                   2506: 	    my $incorrect = 0;
1.145     albertel 2507: 	    foreach (keys(%status)) {
                   2508: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2509: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2510: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2511: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2512: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2513: 		    $submitted = 0;
                   2514: 		}
1.41      ng       2515: 	    }
1.156     albertel 2516: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2517: 				     $submitonly eq 'incorrect' ||
                   2518: 				     $submitonly eq 'graded'));
1.248     albertel 2519: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2520: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2521: 	}
                   2522: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2523: 	last if ($ctr == $ntstu);
1.41      ng       2524: 	$ctr++;
                   2525:     }
1.36      ng       2526: 
1.41      ng       2527:     $ctr = 0;
                   2528:     my $total = scalar(@nextlist)-1;
1.39      ng       2529: 
1.41      ng       2530:     foreach (sort @nextlist) {
                   2531: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2532: 	$env{'form.student'}  = $uname;
                   2533: 	$env{'form.userdom'}  = $udom;
                   2534: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2535: 	&submission($request,$ctr,$total);
                   2536: 	$ctr++;
                   2537:     }
                   2538:     if ($total < 0) {
1.398     albertel 2539: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2540: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2541: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2542: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2543: 	$request->print($the_end);
                   2544:     }
                   2545:     return '';
1.38      ng       2546: }
1.36      ng       2547: 
1.44      ng       2548: #---- Save the score and award for each student, if changed
1.38      ng       2549: sub saveHandGrade {
1.324     albertel 2550:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2551:     my @version_parts;
1.104     albertel 2552:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2553: 					   $env{'request.course.id'});
1.104     albertel 2554:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2555:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2556:     my @parts_graded;
1.77      ng       2557:     my %newrecord  = ();
                   2558:     my ($pts,$wgt) = ('','');
1.269     raeburn  2559:     my %aggregate = ();
                   2560:     my $aggregateflag = 0;
1.301     albertel 2561:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2562:     foreach my $new_part (@parts) {
1.337     banghart 2563: 	#collaborator ($submi may vary for different parts
1.259     banghart 2564: 	if ($submitter && $new_part ne $part) { next; }
                   2565: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2566: 	if ($dropMenu eq 'excused') {
1.259     banghart 2567: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2568: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2569: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2570: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2571: 		}
1.364     banghart 2572: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2573: 	    }
1.125     ng       2574: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2575: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2576: 	    foreach my $key (keys (%record)) {
1.259     banghart 2577: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2578: 	    }
1.259     banghart 2579: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2580: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2581:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2582: 
                   2583:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2584: 					       [$new_part]);
                   2585:             my $aggtries =$totaltries;
1.269     raeburn  2586:             if ($last_resets{$new_part}) {
1.270     albertel 2587:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2588: 					   $new_part);
1.269     raeburn  2589:             }
1.270     albertel 2590: 
                   2591:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2592:             if ($aggtries > 0) {
1.327     albertel 2593:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2594:                 $aggregateflag = 1;
                   2595:             }
1.125     ng       2596: 	} elsif ($dropMenu eq '') {
1.259     banghart 2597: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2598: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2599: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2600: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2601: 		next;
                   2602: 	    }
1.259     banghart 2603: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2604: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2605: 	    my $partial= $pts/$wgt;
1.259     banghart 2606: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2607: 		#do not update score for part if not changed.
1.346     banghart 2608:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2609: 		next;
1.251     banghart 2610: 	    } else {
1.259     banghart 2611: 	        push @parts_graded, $new_part;
1.153     albertel 2612: 	    }
1.259     banghart 2613: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2614: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2615: 	    }
1.259     banghart 2616: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2617: 	    if ($partial == 0) {
1.153     albertel 2618: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2619: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2620: 		}
1.41      ng       2621: 	    } else {
1.153     albertel 2622: 		if ($record{$reckey} ne 'correct_by_override') {
                   2623: 		    $newrecord{$reckey} = 'correct_by_override';
                   2624: 		}
                   2625: 	    }	    
                   2626: 	    if ($submitter && 
1.259     banghart 2627: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2628: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2629: 	    }
1.259     banghart 2630: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2631: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2632: 	}
1.259     banghart 2633: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2634: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2635: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2636: 	        $dropMenu eq 'reset status')
                   2637: 	   {
1.342     banghart 2638: 	    push (@version_parts,$new_part);
1.259     banghart 2639: 	}
1.41      ng       2640:     }
1.301     albertel 2641:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2642:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2643: 
1.344     albertel 2644:     if (%newrecord) {
                   2645:         if (@version_parts) {
1.364     banghart 2646:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2647:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2648: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2649: 	    foreach my $new_part (@version_parts) {
                   2650: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2651: 				$new_part,\%newrecord);
                   2652: 	    }
1.259     banghart 2653:         }
1.44      ng       2654: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2655: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2656: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2657: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2658:     }
1.269     raeburn  2659:     if ($aggregateflag) {
                   2660:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2661: 			      $cdom,$cnum);
1.269     raeburn  2662:     }
1.301     albertel 2663:     return ('',$pts,$wgt);
1.36      ng       2664: }
1.322     albertel 2665: 
1.380     albertel 2666: sub check_and_remove_from_queue {
                   2667:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2668:     my @ungraded_parts;
                   2669:     foreach my $part (@{$parts}) {
                   2670: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2671: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2672: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2673: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2674: 		) {
                   2675: 	    push(@ungraded_parts, $part);
                   2676: 	}
                   2677:     }
                   2678:     if ( !@ungraded_parts ) {
                   2679: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2680: 					       $cnum,$domain,$stuname);
                   2681:     }
                   2682: }
                   2683: 
1.337     banghart 2684: sub handback_files {
                   2685:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2686:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2687:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2688: 
                   2689:     my @part_response_id = &flatten_responseType($responseType);
                   2690:     foreach my $part_response_id (@part_response_id) {
                   2691:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2692: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2693:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2694:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2695:                 my $file_counter = 1;
1.367     albertel 2696: 		my $file_msg;
1.337     banghart 2697:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2698:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2699:                     my ($directory,$answer_file) = 
                   2700:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2701:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2702: 		        &file_name_version_ext($answer_file);
1.355     banghart 2703: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2704: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2705: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2706:                     # fix file name
                   2707:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2708:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2709:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2710:             	                                $save_file_name);
1.337     banghart 2711:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2712:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2713:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2714:                     } else {
1.360     banghart 2715:                         # mark the file as read only
                   2716:                         my @files = ($save_file_name);
1.372     albertel 2717:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2718:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2719: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2720: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2721: 			}
                   2722:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2723: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2724: 
1.337     banghart 2725:                     }
                   2726:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2727:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2728:                     $file_counter++;
                   2729:                 }
1.367     albertel 2730: 		my $subject = "File Handed Back by Instructor ";
                   2731: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2732: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2733: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2734: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2735: 		my ($feedurl,$showsymb) = 
                   2736: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2737:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2738: 		my $msgstatus = 
                   2739:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2740: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2741:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2742:             }
                   2743:         }
1.338     banghart 2744:     return;
1.337     banghart 2745: }
                   2746: 
1.418     albertel 2747: sub get_feedurl_and_symb {
                   2748:     my ($symb,$uname,$udom) = @_;
                   2749:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2750:     $url = &Apache::lonnet::clutter($url);
                   2751:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2752: 					$symb,$udom,$uname);
                   2753:     if ($encrypturl =~ /^yes$/i) {
                   2754: 	&Apache::lonenc::encrypted(\$url,1);
                   2755: 	&Apache::lonenc::encrypted(\$symb,1);
                   2756:     }
                   2757:     return ($url,$symb);
                   2758: }
                   2759: 
1.313     banghart 2760: sub get_submitted_files {
                   2761:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2762:     my @files;
                   2763:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2764:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2765:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2766:     	    push(@files,$file_url.$file);
                   2767:         }
                   2768:     }
                   2769:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2770:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2771:     }
                   2772:     return (\@files);
                   2773: }
1.322     albertel 2774: 
1.269     raeburn  2775: # ----------- Provides number of tries since last reset.
                   2776: sub get_num_tries {
                   2777:     my ($record,$last_reset,$part) = @_;
                   2778:     my $timestamp = '';
                   2779:     my $num_tries = 0;
                   2780:     if ($$record{'version'}) {
                   2781:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2782:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2783:                 $timestamp = $$record{$version.':timestamp'};
                   2784:                 if ($timestamp > $last_reset) {
                   2785:                     $num_tries ++;
                   2786:                 } else {
                   2787:                     last;
                   2788:                 }
                   2789:             }
                   2790:         }
                   2791:     }
                   2792:     return $num_tries;
                   2793: }
                   2794: 
                   2795: # ----------- Determine decrements required in aggregate totals 
                   2796: sub decrement_aggs {
                   2797:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2798:     my %decrement = (
                   2799:                         attempts => 0,
                   2800:                         users => 0,
                   2801:                         correct => 0
                   2802:                     );
                   2803:     $decrement{'attempts'} = $aggtries;
                   2804:     if ($solvedstatus =~ /^correct/) {
                   2805:         $decrement{'correct'} = 1;
                   2806:     }
                   2807:     if ($aggtries == $totaltries) {
                   2808:         $decrement{'users'} = 1;
                   2809:     }
                   2810:     foreach my $type (keys (%decrement)) {
                   2811:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2812:     }
                   2813:     return;
                   2814: }
                   2815: 
                   2816: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2817: sub get_last_resets {
1.270     albertel 2818:     my ($symb,$courseid,$partids) =@_;
                   2819:     my %last_resets;
1.269     raeburn  2820:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2821:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2822:     my @keys;
                   2823:     foreach my $part (@{$partids}) {
                   2824: 	push(@keys,"$symb\0$part\0resettime");
                   2825:     }
                   2826:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2827: 				     $cdom,$cname);
                   2828:     foreach my $part (@{$partids}) {
                   2829: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2830:     }
1.270     albertel 2831:     return %last_resets;
1.269     raeburn  2832: }
                   2833: 
1.251     banghart 2834: # ----------- Handles creating versions for portfolio files as answers
                   2835: sub version_portfiles {
1.343     banghart 2836:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2837:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2838:     my @returned_keys;
1.255     banghart 2839:     my $parts = join('|', @$parts_graded);
1.359     www      2840:     my $portfolio_root = &propath($domain,$stu_name).
                   2841: 	'/userfiles/portfolio';
1.277     albertel 2842:     foreach my $key (keys(%$record)) {
1.259     banghart 2843:         my $new_portfiles;
1.263     banghart 2844:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2845:             my @versioned_portfiles;
1.367     albertel 2846:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2847:             foreach my $file (@portfiles) {
1.306     banghart 2848:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2849:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2850: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2851: 		    &file_name_version_ext($answer_file);
1.306     banghart 2852:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2853:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2854:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2855:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2856:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2857:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2858:                         [$directory.$new_answer],
1.306     banghart 2859:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2860:                 }
1.252     banghart 2861:             }
1.343     banghart 2862:             $$record{$key} = join(',',@versioned_portfiles);
                   2863:             push(@returned_keys,$key);
1.251     banghart 2864:         }
                   2865:     } 
1.343     banghart 2866:     return (@returned_keys);   
1.305     banghart 2867: }
                   2868: 
1.307     banghart 2869: sub get_next_version {
1.341     banghart 2870:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2871:     my $version;
                   2872:     foreach my $row (@$dir_list) {
                   2873:         my ($file) = split(/\&/,$row,2);
                   2874:         my ($file_name,$file_version,$file_ext) =
                   2875: 	    &file_name_version_ext($file);
                   2876:         if (($file_name eq $answer_name) && 
                   2877: 	    ($file_ext eq $answer_ext)) {
                   2878:                 # gets here if filename and extension match, regardless of version
                   2879:                 if ($file_version ne '') {
                   2880:                 # a versioned file is found  so save it for later
                   2881:                 if ($file_version > $version) {
                   2882: 		    $version = $file_version;
                   2883: 	        }
                   2884:             }
                   2885:         }
                   2886:     } 
                   2887:     $version ++;
                   2888:     return($version);
                   2889: }
                   2890: 
1.305     banghart 2891: sub version_selected_portfile {
1.306     banghart 2892:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2893:     my ($answer_name,$answer_ver,$answer_ext) =
                   2894:         &file_name_version_ext($file_name);
                   2895:     my $new_answer;
                   2896:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2897:     if($env{'form.copy'} eq '-1') {
                   2898:         $new_answer = 'problem getting file';
                   2899:     } else {
                   2900:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2901:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2902:                             $stu_name,$domain,'copy',
                   2903: 		        '/portfolio'.$directory.$new_answer);
                   2904:     }    
                   2905:     return ($new_answer);
1.251     banghart 2906: }
                   2907: 
1.304     albertel 2908: sub file_name_version_ext {
                   2909:     my ($file)=@_;
                   2910:     my @file_parts = split(/\./, $file);
                   2911:     my ($name,$version,$ext);
                   2912:     if (@file_parts > 1) {
                   2913: 	$ext=pop(@file_parts);
                   2914: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2915: 	    $version=pop(@file_parts);
                   2916: 	}
                   2917: 	$name=join('.',@file_parts);
                   2918:     } else {
                   2919: 	$name=join('.',@file_parts);
                   2920:     }
                   2921:     return($name,$version,$ext);
                   2922: }
                   2923: 
1.44      ng       2924: #--------------------------------------------------------------------------------------
                   2925: #
                   2926: #-------------------------- Next few routines handles grading by section or whole class
                   2927: #
                   2928: #--- Javascript to handle grading by section or whole class
1.42      ng       2929: sub viewgrades_js {
                   2930:     my ($request) = shift;
                   2931: 
1.41      ng       2932:     $request->print(<<VIEWJAVASCRIPT);
                   2933: <script type="text/javascript" language="javascript">
1.45      ng       2934:    function writePoint(partid,weight,point) {
1.125     ng       2935: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2936: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2937: 	if (point == "textval") {
1.125     ng       2938: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2939: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2940: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2941: 		var resetbox = false;
                   2942: 		for (var i=0; i<radioButton.length; i++) {
                   2943: 		    if (radioButton[i].checked) {
                   2944: 			textbox.value = i;
                   2945: 			resetbox = true;
                   2946: 		    }
                   2947: 		}
                   2948: 		if (!resetbox) {
                   2949: 		    textbox.value = "";
                   2950: 		}
                   2951: 		return;
                   2952: 	    }
1.109     matthew  2953: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2954: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2955: 				   ") greater than the weight for the part. Accept?");
                   2956: 		if (resp == false) {
                   2957: 		    textbox.value = "";
                   2958: 		    return;
                   2959: 		}
                   2960: 	    }
1.42      ng       2961: 	    for (var i=0; i<radioButton.length; i++) {
                   2962: 		radioButton[i].checked=false;
1.109     matthew  2963: 		if (parseFloat(point) == i) {
1.42      ng       2964: 		    radioButton[i].checked=true;
                   2965: 		}
                   2966: 	    }
1.41      ng       2967: 
1.42      ng       2968: 	} else {
1.125     ng       2969: 	    textbox.value = parseFloat(point);
1.42      ng       2970: 	}
1.41      ng       2971: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2972: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2973: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2974: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2975: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2976: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2977: 	    if (saveval != "correct") {
                   2978: 		scorename.value = point;
1.43      ng       2979: 		if (selname[0].selected != true) {
                   2980: 		    selname[0].selected = true;
                   2981: 		}
1.42      ng       2982: 	    }
                   2983: 	}
1.125     ng       2984: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2985:     }
                   2986: 
                   2987:     function writeRadText(partid,weight) {
1.125     ng       2988: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2989: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2990:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2991: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2992: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2993: 	    for (var i=0; i<radioButton.length; i++) {
                   2994: 		radioButton[i].checked=false;
                   2995: 
                   2996: 	    }
                   2997: 	    textbox.value = "";
                   2998: 
                   2999: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3000: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3001: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3002: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3003: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3004: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3005: 		if ((saveval != "correct") || override) {
1.42      ng       3006: 		    scorename.value = "";
1.125     ng       3007: 		    if (selval[1].selected) {
                   3008: 			selname[1].selected = true;
                   3009: 		    } else {
                   3010: 			selname[2].selected = true;
                   3011: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3012: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3013: 		    }
1.42      ng       3014: 		}
                   3015: 	    }
1.43      ng       3016: 	} else {
                   3017: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3018: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3019: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3020: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3021: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3022: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3023: 		if ((saveval != "correct") || override) {
1.125     ng       3024: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3025: 		    selname[0].selected = true;
                   3026: 		}
                   3027: 	    }
                   3028: 	}	    
1.42      ng       3029:     }
                   3030: 
                   3031:     function changeSelect(partid,user) {
1.125     ng       3032: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3033: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3034: 	var point  = textbox.value;
1.125     ng       3035: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3036: 
1.109     matthew  3037: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3038: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3039: 	    textbox.value = "";
                   3040: 	    return;
                   3041: 	}
1.109     matthew  3042: 	if (parseFloat(point) > parseFloat(weight)) {
                   3043: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3044: 			       ") greater than the weight of the part. Accept?");
                   3045: 	    if (resp == false) {
                   3046: 		textbox.value = "";
                   3047: 		return;
                   3048: 	    }
                   3049: 	}
1.42      ng       3050: 	selval[0].selected = true;
                   3051:     }
                   3052: 
                   3053:     function changeOneScore(partid,user) {
1.125     ng       3054: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3055: 	if (selval[1].selected || selval[2].selected) {
                   3056: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3057: 	    if (selval[2].selected) {
                   3058: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3059: 	    }
1.269     raeburn  3060:         }
1.42      ng       3061:     }
                   3062: 
                   3063:     function resetEntry(numpart) {
                   3064: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3065: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3066: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3067: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3068: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3069: 	    for (var i=0; i<radioButton.length; i++) {
                   3070: 		radioButton[i].checked=false;
                   3071: 
                   3072: 	    }
                   3073: 	    textbox.value = "";
                   3074: 	    selval[0].selected = true;
                   3075: 
                   3076: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3077: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3078: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3079: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3080: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3081: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3082: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3083: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3084: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3085: 		if (saveselval == "excused") {
1.43      ng       3086: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3087: 		} else {
1.43      ng       3088: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3089: 		}
                   3090: 	    }
1.41      ng       3091: 	}
1.42      ng       3092:     }
                   3093: 
1.41      ng       3094: </script>
                   3095: VIEWJAVASCRIPT
1.42      ng       3096: }
                   3097: 
1.44      ng       3098: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3099: sub viewgrades {
                   3100:     my ($request) = shift;
                   3101:     &viewgrades_js($request);
1.41      ng       3102: 
1.324     albertel 3103:     my ($symb) = &get_symb($request);
1.168     albertel 3104:     #need to make sure we have the correct data for later EXT calls, 
                   3105:     #thus invalidate the cache
                   3106:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3107:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3108:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3109:     &Apache::lonnet::clear_EXT_cache_status();
                   3110: 
1.398     albertel 3111:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3112:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3113: 
                   3114:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3115:     $result.=&jscriptNform($symb);
1.41      ng       3116: 
1.44      ng       3117:     #beginning of class grading form
1.442     banghart 3118:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3119:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3120: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3121: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3122: 	&build_section_inputs().
1.257     albertel 3123: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3124: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3125: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3126: 
1.126     ng       3127:     my $sectionClass;
1.430     banghart 3128:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3129:     if ($env{'form.section'} eq 'all') {
1.126     ng       3130: 	$sectionClass='Class </h3>';
1.257     albertel 3131:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3132: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3133:     } else {
1.431     banghart 3134: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3135:     }
1.431     banghart 3136:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3137:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3138: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3139:     #radio buttons/text box for assigning points for a section or class.
                   3140:     #handles different parts of a problem
1.375     albertel 3141:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3142:     my %weight = ();
                   3143:     my $ctsparts = 0;
1.41      ng       3144:     $result.='<table border="0">';
1.45      ng       3145:     my %seen = ();
1.375     albertel 3146:     my @part_response_id = &flatten_responseType($responseType);
                   3147:     foreach my $part_response_id (@part_response_id) {
                   3148:     	my ($partid,$respid) = @{ $part_response_id };
                   3149: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3150: 	next if $seen{$partid};
                   3151: 	$seen{$partid}++;
1.375     albertel 3152: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3153: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3154: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3155: 
1.44      ng       3156: 	$result.='<input type="hidden" name="partid_'.
                   3157: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3158: 	$result.='<input type="hidden" name="weight_'.
                   3159: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3160: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3161: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3162: 	$result.='<table border="0"><tr>';  
1.41      ng       3163: 	my $ctr = 0;
1.42      ng       3164: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3165: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3166: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3167: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3168: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3169: 	    $ctr++;
                   3170: 	}
                   3171: 	$result.='</tr></table>';
1.44      ng       3172: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3173: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3174: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3175: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3176: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3177: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3178: 		$weight{$partid}.')"> '.
1.401     albertel 3179: 	    '<option selected="selected"> </option>'.
1.125     ng       3180: 	    '<option>excused</option>'.
1.265     www      3181: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3182:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3183: 	$ctsparts++;
1.41      ng       3184:     }
1.52      albertel 3185:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3186: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3187:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3188: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3189: 
1.44      ng       3190:     #table listing all the students in a section/class
                   3191:     #header of table
1.126     ng       3192:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3193:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3194: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3195: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3196:     my (@parts) = sort(&getpartlist($symb));
                   3197:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3198:     my @partids = ();
1.41      ng       3199:     foreach my $part (@parts) {
                   3200: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3201: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3202: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3203: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3204:         push(@partids, $partid);
1.324     albertel 3205: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3206: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3207: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3208: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3209: 	    next;
1.207     albertel 3210: 	} else {
                   3211: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3212: 	}
1.53      albertel 3213: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3214: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3215:     }
                   3216:     $result.='</tr>';
1.44      ng       3217: 
1.270     albertel 3218:     my %last_resets = 
                   3219: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3220: 
1.41      ng       3221:     #get info for each student
1.44      ng       3222:     #list all the students - with points and grade status
1.257     albertel 3223:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3224:     my $ctr = 0;
1.294     albertel 3225:     foreach (sort 
                   3226: 	     {
                   3227: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3228: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3229: 		 }
                   3230: 		 return $a cmp $b;
                   3231: 	     } (keys(%$fullname))) {
1.126     ng       3232: 	$ctr++;
1.324     albertel 3233: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3234: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3235:     }
                   3236:     $result.='</table></td></tr></table>';
                   3237:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3238:     $result.='<input type="button" value="Save" '.
1.417     albertel 3239: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3240:     if (scalar(%$fullname) eq 0) {
                   3241: 	my $colspan=3+scalar(@parts);
1.433     banghart 3242: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3243:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3244: 	$result='<span class="LC_warning">'.
                   3245: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3246: 	        $section_display, $stu_status).
1.433     banghart 3247: 	    '</span>';
1.96      albertel 3248:     }
1.324     albertel 3249:     $result.=&show_grading_menu_form($symb);
1.41      ng       3250:     return $result;
                   3251: }
                   3252: 
1.44      ng       3253: #--- call by previous routine to display each student
1.41      ng       3254: sub viewstudentgrade {
1.324     albertel 3255:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3256:     my ($uname,$udom) = split(/:/,$student);
                   3257:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3258:     my %aggregates = (); 
1.233     albertel 3259:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3260: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3261: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3262: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3263: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3264: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3265:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3266:     foreach my $apart (@$parts) {
                   3267: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3268: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3269:         $result.='<td align="center">';
1.269     raeburn  3270:         my ($aggtries,$totaltries);
                   3271:         unless (exists($aggregates{$part})) {
1.270     albertel 3272: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3273: 
                   3274: 	    $aggtries = $totaltries;
1.269     raeburn  3275:             if ($$last_resets{$part}) {  
1.270     albertel 3276:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3277: 					   $part);
                   3278:             }
1.269     raeburn  3279:             $result.='<input type="hidden" name="'.
                   3280:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3281:             $result.='<input type="hidden" name="'.
                   3282:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3283:             $aggregates{$part} = 1;
                   3284:         }
1.41      ng       3285: 	if ($type eq 'awarded') {
1.320     albertel 3286: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3287: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3288: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3289: 	    $result.='<input type="text" name="'.
1.89      albertel 3290: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3291: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3292: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3293: 	} elsif ($type eq 'solved') {
                   3294: 	    my ($status,$foo)=split(/_/,$score,2);
                   3295: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3296: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3297: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3298: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3299: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3300: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3301: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3302: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3303: 	    $result.='<option>reset status</option>';
1.126     ng       3304: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3305: 	} else {
                   3306: 	    $result.='<input type="hidden" name="'.
                   3307: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3308: 		    "\n";
1.233     albertel 3309: 	    $result.='<input type="text" name="'.
1.122     ng       3310: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3311: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3312: 	}
                   3313:     }
                   3314:     $result.='</tr>';
                   3315:     return $result;
1.38      ng       3316: }
                   3317: 
1.44      ng       3318: #--- change scores for all the students in a section/class
                   3319: #    record does not get update if unchanged
1.38      ng       3320: sub editgrades {
1.41      ng       3321:     my ($request) = @_;
                   3322: 
1.324     albertel 3323:     my $symb=&get_symb($request);
1.433     banghart 3324:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3325:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3326:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3327:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3328: 
1.44      ng       3329:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3330:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3331: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3332: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3333: 
                   3334:     my %scoreptr = (
                   3335: 		    'correct'  =>'correct_by_override',
                   3336: 		    'incorrect'=>'incorrect_by_override',
                   3337: 		    'excused'  =>'excused',
                   3338: 		    'ungraded' =>'ungraded_attempted',
                   3339: 		    'nothing'  => '',
                   3340: 		    );
1.257     albertel 3341:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3342: 
1.44      ng       3343:     my (@partid);
                   3344:     my %weight = ();
1.54      albertel 3345:     my %columns = ();
1.44      ng       3346:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3347: 
1.324     albertel 3348:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3349:     my $header;
1.257     albertel 3350:     while ($ctr < $env{'form.totalparts'}) {
                   3351: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3352: 	push @partid,$partid;
1.257     albertel 3353: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3354: 	$ctr++;
1.54      albertel 3355:     }
1.324     albertel 3356:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3357:     foreach my $partid (@partid) {
                   3358: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3359: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3360: 	$columns{$partid}=2;
                   3361: 	foreach my $stores (@parts) {
                   3362: 	    my ($part,$type) = &split_part_type($stores);
                   3363: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3364: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3365: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3366: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3367: 	    $display =~ s/Number of Attempts/Tries/;
                   3368: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3369: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3370: 	    $columns{$partid}+=2;
                   3371: 	}
                   3372:     }
                   3373:     foreach my $partid (@partid) {
1.324     albertel 3374: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3375: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3376: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3377: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3378: 
1.44      ng       3379:     }
                   3380:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3381:     $result .= $header;
1.44      ng       3382:     $result .= '</tr>'."\n";
1.93      albertel 3383:     my $noupdate;
1.126     ng       3384:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3385:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3386: 	my $line;
1.257     albertel 3387: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3388: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3389: 	my %newrecord;
                   3390: 	my $updateflag = 0;
1.281     albertel 3391: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3392: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3393: 	if (!&canmodify($usec)) {
1.126     ng       3394: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3395: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3396: 	    next;
                   3397: 	}
1.269     raeburn  3398:         my %aggregate = ();
                   3399:         my $aggregateflag = 0;
1.281     albertel 3400: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3401: 	foreach (@partid) {
1.257     albertel 3402: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3403: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3404: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3405: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3406: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3407: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3408: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3409: 	    my $score;
                   3410: 	    if ($partial eq '') {
1.257     albertel 3411: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3412: 	    } elsif ($partial > 0) {
                   3413: 		$score = 'correct_by_override';
                   3414: 	    } elsif ($partial == 0) {
                   3415: 		$score = 'incorrect_by_override';
                   3416: 	    }
1.257     albertel 3417: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3418: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3419: 
1.292     albertel 3420: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3421: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3422: 	    if ($dropMenu eq 'reset status' &&
                   3423: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3424: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3425: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3426: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3427: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3428: 		$updateflag = 1;
1.269     raeburn  3429:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3430:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3431:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3432:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3433:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3434:                     $aggregateflag = 1;
                   3435:                 }
1.139     albertel 3436: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3437: 		$updateflag = 1;
                   3438: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3439: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3440: 		$rec_update++;
1.125     ng       3441: 	    }
                   3442: 
1.93      albertel 3443: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3444: 		'<td align="center">'.$awarded.
                   3445: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3446: 
1.54      albertel 3447: 
                   3448: 	    my $partid=$_;
                   3449: 	    foreach my $stores (@parts) {
                   3450: 		my ($part,$type) = &split_part_type($stores);
                   3451: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3452: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3453: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3454: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3455: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3456: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3457: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3458: 		    $updateflag=1;
                   3459: 		}
1.93      albertel 3460: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3461: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3462: 	    }
1.44      ng       3463: 	}
1.93      albertel 3464: 	$line.='</tr>'."\n";
1.301     albertel 3465: 
                   3466: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3467: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3468: 
1.44      ng       3469: 	if ($updateflag) {
                   3470: 	    $count++;
1.257     albertel 3471: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3472: 				    $udom,$uname);
1.301     albertel 3473: 
                   3474: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3475: 					      $cnum,$udom,$uname)) {
                   3476: 		# need to figure out if should be in queue.
                   3477: 		my %record =  
                   3478: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3479: 					     $udom,$uname);
                   3480: 		my $all_graded = 1;
                   3481: 		my $none_graded = 1;
                   3482: 		foreach my $part (@parts) {
                   3483: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3484: 			$all_graded = 0;
                   3485: 		    } else {
                   3486: 			$none_graded = 0;
                   3487: 		    }
                   3488: 		}
                   3489: 
                   3490: 		if ($all_graded || $none_graded) {
                   3491: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3492: 							   $symb,$cdom,$cnum,
                   3493: 							   $udom,$uname);
                   3494: 		}
                   3495: 	    }
                   3496: 
1.126     ng       3497: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3498: 	    $updateCtr++;
1.93      albertel 3499: 	} else {
1.126     ng       3500: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3501: 	    $noupdateCtr++;
1.44      ng       3502: 	}
1.269     raeburn  3503:         if ($aggregateflag) {
                   3504:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3505: 				  $cdom,$cnum);
1.269     raeburn  3506:         }
1.93      albertel 3507:     }
                   3508:     if ($noupdate) {
1.126     ng       3509: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3510: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3511: 	$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       3512:     }
1.72      ng       3513:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3514: 	&show_grading_menu_form ($symb);
1.125     ng       3515:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3516: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3517: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3518:     return $title.$msg.$result;
1.5       albertel 3519: }
1.54      albertel 3520: 
                   3521: sub split_part_type {
                   3522:     my ($partstr) = @_;
                   3523:     my ($temp,@allparts)=split(/_/,$partstr);
                   3524:     my $type=pop(@allparts);
1.439     albertel 3525:     my $part=join('_',@allparts);
1.54      albertel 3526:     return ($part,$type);
                   3527: }
                   3528: 
1.44      ng       3529: #------------- end of section for handling grading by section/class ---------
                   3530: #
                   3531: #----------------------------------------------------------------------------
                   3532: 
1.5       albertel 3533: 
1.44      ng       3534: #----------------------------------------------------------------------------
                   3535: #
                   3536: #-------------------------- Next few routines handles grading by csv upload
                   3537: #
                   3538: #--- Javascript to handle csv upload
1.27      albertel 3539: sub csvupload_javascript_reverse_associate {
1.246     albertel 3540:     my $error1=&mt('You need to specify the username or ID');
                   3541:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3542:   return(<<ENDPICK);
                   3543:   function verify(vf) {
                   3544:     var foundsomething=0;
                   3545:     var founduname=0;
1.243     albertel 3546:     var foundID=0;
1.27      albertel 3547:     for (i=0;i<=vf.nfields.value;i++) {
                   3548:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3549:       if (i==0 && tw!=0) { foundID=1; }
                   3550:       if (i==1 && tw!=0) { founduname=1; }
                   3551:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3552:     }
1.246     albertel 3553:     if (founduname==0 && foundID==0) {
                   3554: 	alert('$error1');
                   3555: 	return;
1.27      albertel 3556:     }
                   3557:     if (foundsomething==0) {
1.246     albertel 3558: 	alert('$error2');
                   3559: 	return;
1.27      albertel 3560:     }
                   3561:     vf.submit();
                   3562:   }
                   3563:   function flip(vf,tf) {
                   3564:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3565:     var i;
                   3566:     for (i=0;i<=vf.nfields.value;i++) {
                   3567:       //can not pick the same destination field for both name and domain
                   3568:       if (((i ==0)||(i ==1)) && 
                   3569:           ((tf==0)||(tf==1)) && 
                   3570:           (i!=tf) &&
                   3571:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3572:         eval('vf.f'+i+'.selectedIndex=0;')
                   3573:       }
                   3574:     }
                   3575:   }
                   3576: ENDPICK
                   3577: }
                   3578: 
                   3579: sub csvupload_javascript_forward_associate {
1.246     albertel 3580:     my $error1=&mt('You need to specify the username or ID');
                   3581:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3582:   return(<<ENDPICK);
                   3583:   function verify(vf) {
                   3584:     var foundsomething=0;
                   3585:     var founduname=0;
1.243     albertel 3586:     var foundID=0;
1.27      albertel 3587:     for (i=0;i<=vf.nfields.value;i++) {
                   3588:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3589:       if (tw==1) { foundID=1; }
                   3590:       if (tw==2) { founduname=1; }
                   3591:       if (tw>3) { foundsomething=1; }
1.27      albertel 3592:     }
1.246     albertel 3593:     if (founduname==0 && foundID==0) {
                   3594: 	alert('$error1');
                   3595: 	return;
1.27      albertel 3596:     }
                   3597:     if (foundsomething==0) {
1.246     albertel 3598: 	alert('$error2');
                   3599: 	return;
1.27      albertel 3600:     }
                   3601:     vf.submit();
                   3602:   }
                   3603:   function flip(vf,tf) {
                   3604:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3605:     var i;
                   3606:     //can not pick the same destination field twice
                   3607:     for (i=0;i<=vf.nfields.value;i++) {
                   3608:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3609:         eval('vf.f'+i+'.selectedIndex=0;')
                   3610:       }
                   3611:     }
                   3612:   }
                   3613: ENDPICK
                   3614: }
                   3615: 
1.26      albertel 3616: sub csvuploadmap_header {
1.324     albertel 3617:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3618:     my $javascript;
1.257     albertel 3619:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3620: 	$javascript=&csvupload_javascript_reverse_associate();
                   3621:     } else {
                   3622: 	$javascript=&csvupload_javascript_forward_associate();
                   3623:     }
1.45      ng       3624: 
1.324     albertel 3625:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3626:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3627:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3628:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3629:     $request->print(<<ENDPICK);
1.26      albertel 3630: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3631: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3632: $result
1.326     albertel 3633: <hr />
1.26      albertel 3634: <h3>Identify fields</h3>
                   3635: Total number of records found in file: $distotal <hr />
                   3636: Enter as many fields as you can. The system will inform you and bring you back
                   3637: to this page if the data selected is insufficient to run your class.<hr />
                   3638: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3639: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3640: <input type="hidden" name="associate"  value="" />
                   3641: <input type="hidden" name="phase"      value="three" />
                   3642: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3643: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3644: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3645: <input type="hidden" name="upfile_associate" 
1.257     albertel 3646:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3647: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3648: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3649: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3650: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3651: <hr />
                   3652: <script type="text/javascript" language="Javascript">
                   3653: $javascript
                   3654: </script>
                   3655: ENDPICK
1.118     ng       3656:     return '';
1.26      albertel 3657: 
                   3658: }
                   3659: 
                   3660: sub csvupload_fields {
1.324     albertel 3661:     my ($symb) = @_;
                   3662:     my (@parts) = &getpartlist($symb);
1.243     albertel 3663:     my @fields=(['ID','Student ID'],
                   3664: 		['username','Student Username'],
                   3665: 		['domain','Student Domain']);
1.324     albertel 3666:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3667:     foreach my $part (sort(@parts)) {
                   3668: 	my @datum;
                   3669: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3670: 	my $name=$part;
                   3671: 	if  (!$display) { $display = $name; }
                   3672: 	@datum=($name,$display);
1.244     albertel 3673: 	if ($name=~/^stores_(.*)_awarded/) {
                   3674: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3675: 	}
1.41      ng       3676: 	push(@fields,\@datum);
                   3677:     }
                   3678:     return (@fields);
1.26      albertel 3679: }
                   3680: 
                   3681: sub csvuploadmap_footer {
1.41      ng       3682:     my ($request,$i,$keyfields) =@_;
                   3683:     $request->print(<<ENDPICK);
1.26      albertel 3684: </table>
                   3685: <input type="hidden" name="nfields" value="$i" />
                   3686: <input type="hidden" name="keyfields" value="$keyfields" />
                   3687: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3688: </form>
                   3689: ENDPICK
                   3690: }
                   3691: 
1.283     albertel 3692: sub checkforfile_js {
1.86      ng       3693:     my $result =<<CSVFORMJS;
                   3694: <script type="text/javascript" language="javascript">
                   3695:     function checkUpload(formname) {
                   3696: 	if (formname.upfile.value == "") {
                   3697: 	    alert("Please use the browse button to select a file from your local directory.");
                   3698: 	    return false;
                   3699: 	}
                   3700: 	formname.submit();
                   3701:     }
                   3702:     </script>
                   3703: CSVFORMJS
1.283     albertel 3704:     return $result;
                   3705: }
                   3706: 
                   3707: sub upcsvScores_form {
                   3708:     my ($request) = shift;
1.324     albertel 3709:     my ($symb)=&get_symb($request);
1.283     albertel 3710:     if (!$symb) {return '';}
                   3711:     my $result=&checkforfile_js();
1.257     albertel 3712:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3713:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3714:     $result.=$table;
1.326     albertel 3715:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3716:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3717:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3718: 	'.</b></td></tr>'."\n";
                   3719:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3720:     my $upload=&mt("Upload Scores");
1.86      ng       3721:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3722:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3723:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3724:     $result.=<<ENDUPFORM;
1.106     albertel 3725: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3726: <input type="hidden" name="symb" value="$symb" />
                   3727: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3728: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3729: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3730: $upfile_select
1.370     www      3731: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3732: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3733: </form>
                   3734: ENDUPFORM
1.370     www      3735:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3736:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3737:     .'</td></tr></table>'."\n";
1.86      ng       3738:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3739:     $result.=&show_grading_menu_form($symb);
1.86      ng       3740:     return $result;
                   3741: }
                   3742: 
                   3743: 
1.26      albertel 3744: sub csvuploadmap {
1.41      ng       3745:     my ($request)= @_;
1.324     albertel 3746:     my ($symb)=&get_symb($request);
1.41      ng       3747:     if (!$symb) {return '';}
1.72      ng       3748: 
1.41      ng       3749:     my $datatoken;
1.257     albertel 3750:     if (!$env{'form.datatoken'}) {
1.41      ng       3751: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3752:     } else {
1.257     albertel 3753: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3754: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3755:     }
1.41      ng       3756:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3757:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3758:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3759:     my ($i,$keyfields);
                   3760:     if (@records) {
1.324     albertel 3761: 	my @fields=&csvupload_fields($symb);
1.45      ng       3762: 
1.257     albertel 3763: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3764: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3765: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3766: 							  \@fields);
                   3767: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3768: 	    chop($keyfields);
                   3769: 	} else {
                   3770: 	    unshift(@fields,['none','']);
                   3771: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3772: 							    \@fields);
1.311     banghart 3773:             foreach my $rec (@records) {
                   3774:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3775:                 if (%temp) {
                   3776:                     $keyfields=join(',',sort(keys(%temp)));
                   3777:                     last;
                   3778:                 }
                   3779:             }
1.41      ng       3780: 	}
                   3781:     }
                   3782:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3783:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3784: 
1.41      ng       3785:     return '';
1.27      albertel 3786: }
                   3787: 
1.246     albertel 3788: sub csvuploadoptions {
1.41      ng       3789:     my ($request)= @_;
1.324     albertel 3790:     my ($symb)=&get_symb($request);
1.257     albertel 3791:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3792:     my $ignore=&mt('Ignore First Line');
                   3793:     $request->print(<<ENDPICK);
                   3794: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3795: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3796: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3797: <!--
1.246     albertel 3798: <p>
                   3799: <label>
                   3800:    <input type="checkbox" name="show_full_results" />
                   3801:    Show a table of all changes
                   3802: </label>
                   3803: </p>
1.302     albertel 3804: -->
1.246     albertel 3805: <p>
                   3806: <label>
                   3807:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3808:    Overwrite any existing score
                   3809: </label>
                   3810: </p>
                   3811: ENDPICK
                   3812:     my %fields=&get_fields();
                   3813:     if (!defined($fields{'domain'})) {
1.257     albertel 3814: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3815: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3816:     }
1.257     albertel 3817:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3818: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3819: 	my $cleankey=$1;
                   3820: 	if ($cleankey eq 'command') { next; }
                   3821: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3822: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3823:     }
                   3824:     # FIXME do a check for any duplicated user ids...
                   3825:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3826:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3827: <hr /></form>'."\n");
1.324     albertel 3828:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3829:     return '';
                   3830: }
                   3831: 
                   3832: sub get_fields {
                   3833:     my %fields;
1.257     albertel 3834:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3835:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3836: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3837: 	    if ($env{'form.f'.$i} ne 'none') {
                   3838: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3839: 	    }
                   3840: 	} else {
1.257     albertel 3841: 	    if ($env{'form.f'.$i} ne 'none') {
                   3842: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3843: 	    }
                   3844: 	}
1.27      albertel 3845:     }
1.246     albertel 3846:     return %fields;
                   3847: }
                   3848: 
                   3849: sub csvuploadassign {
                   3850:     my ($request)= @_;
1.324     albertel 3851:     my ($symb)=&get_symb($request);
1.246     albertel 3852:     if (!$symb) {return '';}
1.345     bowersj2 3853:     my $error_msg = '';
1.246     albertel 3854:     &Apache::loncommon::load_tmp_file($request);
                   3855:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3856:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3857:     my %fields=&get_fields();
1.41      ng       3858:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3859:     my $courseid=$env{'request.course.id'};
1.97      albertel 3860:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3861:     my @notallowed;
1.41      ng       3862:     my @skipped;
                   3863:     my $countdone=0;
                   3864:     foreach my $grade (@gradedata) {
                   3865: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3866: 	my $domain;
                   3867: 	if ($entries{$fields{'domain'}}) {
                   3868: 	    $domain=$entries{$fields{'domain'}};
                   3869: 	} else {
1.257     albertel 3870: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3871: 	}
1.243     albertel 3872: 	$domain=~s/\s//g;
1.41      ng       3873: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3874: 	$username=~s/\s//g;
1.243     albertel 3875: 	if (!$username) {
                   3876: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3877: 	    $id=~s/\s//g;
1.243     albertel 3878: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3879: 	    $username=$ids{$id};
                   3880: 	}
1.41      ng       3881: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3882: 	    my $id=$entries{$fields{'ID'}};
                   3883: 	    $id=~s/\s//g;
                   3884: 	    if ($id) {
                   3885: 		push(@skipped,"$id:$domain");
                   3886: 	    } else {
                   3887: 		push(@skipped,"$username:$domain");
                   3888: 	    }
1.41      ng       3889: 	    next;
                   3890: 	}
1.108     albertel 3891: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3892: 	if (!&canmodify($usec)) {
                   3893: 	    push(@notallowed,"$username:$domain");
                   3894: 	    next;
                   3895: 	}
1.244     albertel 3896: 	my %points;
1.41      ng       3897: 	my %grades;
                   3898: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3899: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3900: 		$dest eq 'domain') { next; }
                   3901: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3902: 	    if ($dest=~/stores_(.*)_points/) {
                   3903: 		my $part=$1;
                   3904: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3905: 					      $symb,$domain,$username);
1.345     bowersj2 3906:                 if ($wgt) {
                   3907:                     $entries{$fields{$dest}}=~s/\s//g;
                   3908:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3909:                     my $award='correct_by_override';
                   3910:                     $grades{"resource.$part.awarded"}=$pcr;
                   3911:                     $grades{"resource.$part.solved"}=$award;
                   3912:                     $points{$part}=1;
                   3913:                 } else {
                   3914:                     $error_msg = "<br />" .
                   3915:                         &mt("Some point values were assigned"
                   3916:                             ." for problems with a weight "
                   3917:                             ."of zero. These values were "
                   3918:                             ."ignored.");
                   3919:                 }
1.244     albertel 3920: 	    } else {
                   3921: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3922: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3923: 		my $store_key=$dest;
                   3924: 		$store_key=~s/^stores/resource/;
                   3925: 		$store_key=~s/_/\./g;
                   3926: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3927: 	    }
1.41      ng       3928: 	}
1.398     albertel 3929: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3930: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3931: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3932: 					   $env{'request.course.id'},
                   3933: 					   $domain,$username);
                   3934: 	if ($result eq 'ok') {
                   3935: 	    $request->print('.');
                   3936: 	} else {
                   3937: 	    $request->print("<p>
1.398     albertel 3938:                               <span class=\"LC_error\">
                   3939:                                  Failed to save student $username:$domain.
                   3940:                                  Message when trying to save was ($result)
                   3941:                               </span>
1.302     albertel 3942:                              </p>" );
                   3943: 	}
1.41      ng       3944: 	$request->rflush();
                   3945: 	$countdone++;
                   3946:     }
1.398     albertel 3947:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3948:     if (@skipped) {
1.398     albertel 3949: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3950: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3951:     }
                   3952:     if (@notallowed) {
1.398     albertel 3953: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3954: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3955:     }
1.106     albertel 3956:     $request->print("<br />\n");
1.324     albertel 3957:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3958:     return $error_msg;
1.26      albertel 3959: }
1.44      ng       3960: #------------- end of section for handling csv file upload ---------
                   3961: #
                   3962: #-------------------------------------------------------------------
                   3963: #
1.122     ng       3964: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3965: #
                   3966: #--- Select a page/sequence and a student to grade
1.68      ng       3967: sub pickStudentPage {
                   3968:     my ($request) = shift;
                   3969: 
                   3970:     $request->print(<<LISTJAVASCRIPT);
                   3971: <script type="text/javascript" language="javascript">
                   3972: 
                   3973: function checkPickOne(formname) {
1.76      ng       3974:     if (radioSelection(formname.student) == null) {
1.68      ng       3975: 	alert("Please select the student you wish to grade.");
                   3976: 	return;
                   3977:     }
1.125     ng       3978:     ptr = pullDownSelection(formname.selectpage);
                   3979:     formname.page.value = formname["page"+ptr].value;
                   3980:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3981:     formname.submit();
                   3982: }
                   3983: 
                   3984: </script>
                   3985: LISTJAVASCRIPT
1.118     ng       3986:     &commonJSfunctions($request);
1.324     albertel 3987:     my ($symb) = &get_symb($request);
1.257     albertel 3988:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3989:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3990:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3991: 
1.398     albertel 3992:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3993: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3994: 
1.80      ng       3995:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3996:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3997:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3998:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3999: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4000: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4001:     my $ctr=0;
1.68      ng       4002:     foreach (@$titles) {
                   4003: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4004: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4005: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4006: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4007: 	$ctr++;
1.68      ng       4008:     }
1.326     albertel 4009:     $result.= '</select>'."<br />\n";
1.70      ng       4010:     $ctr=0;
                   4011:     foreach (@$titles) {
                   4012: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4013: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4014: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4015: 	$ctr++;
                   4016:     }
1.72      ng       4017:     $result.='<input type="hidden" name="page" />'."\n".
                   4018: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4019: 
1.401     albertel 4020:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4021: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4022: 
1.71      ng       4023:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4024: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4025: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4026: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4027:     
                   4028:     $result.=&build_section_inputs();
1.442     banghart 4029:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4030:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4031: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4032: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4033: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4034: 
1.382     albertel 4035:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4036: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4037: 
1.80      ng       4038:     $result.='&nbsp;<input type="button" '.
1.126     ng       4039: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4040: 
1.68      ng       4041:     $request->print($result);
                   4042: 
1.326     albertel 4043:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4044: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4045: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4046: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4047: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4048: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4049: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4050:  
1.76      ng       4051:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4052:     my $ptr = 1;
1.294     albertel 4053:     foreach my $student (sort 
                   4054: 			 {
                   4055: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4056: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4057: 			     }
                   4058: 			     return $a cmp $b;
                   4059: 			 } (keys(%$fullname))) {
1.68      ng       4060: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4061: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4062: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4063: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4064: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4065: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4066: 	$ptr++;
                   4067:     }
1.381     albertel 4068:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4069:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4070:     $studentTable.='<input type="button" '.
                   4071: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4072: 
1.324     albertel 4073:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4074:     $request->print($studentTable);
                   4075: 
                   4076:     return '';
                   4077: }
                   4078: 
                   4079: sub getSymbMap {
1.132     bowersj2 4080:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4081: 
                   4082:     my %symbx = ();
                   4083:     my @titles = ();
1.117     bowersj2 4084:     my $minder = 0;
                   4085: 
                   4086:     # Gather every sequence that has problems.
1.240     albertel 4087:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4088: 					       1,0,1);
1.117     bowersj2 4089:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4090: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4091: 	    my $title = $minder.'.'.
                   4092: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4093: 	    push(@titles, $title); # minder in case two titles are identical
                   4094: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4095: 	    $minder++;
1.241     albertel 4096: 	}
1.68      ng       4097:     }
                   4098:     return \@titles,\%symbx;
                   4099: }
                   4100: 
1.72      ng       4101: #
                   4102: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4103: sub displayPage {
                   4104:     my ($request) = shift;
                   4105: 
1.324     albertel 4106:     my ($symb) = &get_symb($request);
1.257     albertel 4107:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4108:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4109:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4110:     my $pageTitle = $env{'form.page'};
1.103     albertel 4111:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4112:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4113:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4114: 
                   4115:     #need to make sure we have the correct data for later EXT calls, 
                   4116:     #thus invalidate the cache
                   4117:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4118:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4119:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4120:     &Apache::lonnet::clear_EXT_cache_status();
                   4121: 
1.103     albertel 4122:     if (!&canview($usec)) {
1.398     albertel 4123: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4124: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4125: 	return;
                   4126:     }
1.398     albertel 4127:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4128:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4129: 	'</h3>'."\n";
1.382     albertel 4130:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4131: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4132:     } else {
                   4133: 	delete($env{'form.CODE'});
                   4134:     }
1.71      ng       4135:     &sub_page_js($request);
                   4136:     $request->print($result);
                   4137: 
1.132     bowersj2 4138:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4139:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4140:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4141:     if (!$map) {
1.398     albertel 4142: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4143: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4144: 	return; 
                   4145:     }
1.68      ng       4146:     my $iterator = $navmap->getIterator($map->map_start(),
                   4147: 					$map->map_finish());
                   4148: 
1.71      ng       4149:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4150: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4151: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4152: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4153: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4154: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4155: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4156: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4157: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4158: 
1.382     albertel 4159:     if (defined($env{'form.CODE'})) {
                   4160: 	$studentTable.=
                   4161: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4162:     }
1.381     albertel 4163:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4164: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4165: 	'/check.gif" height="16" border="0" />';
                   4166: 
1.118     ng       4167:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4168: 	' symbol.'."\n".
1.71      ng       4169: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4170: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4171: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4172: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4173: 
1.329     albertel 4174:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4175:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4176:     $iterator->next(); # skip the first BEGIN_MAP
                   4177:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4178:     while ($depth > 0) {
1.68      ng       4179:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4180:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4181: 
1.385     albertel 4182:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4183: 	    my $parts = $curRes->parts();
1.68      ng       4184:             my $title = $curRes->compTitle();
1.71      ng       4185: 	    my $symbx = $curRes->symb();
1.196     albertel 4186: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4187: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4188: 	    $studentTable.='<td valign="top">';
1.382     albertel 4189: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4190: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4191: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4192: 					     undef,'both',\%form);
1.71      ng       4193: 	    } else {
1.382     albertel 4194: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4195: 		$companswer =~ s|<form(.*?)>||g;
                   4196: 		$companswer =~ s|</form>||g;
1.71      ng       4197: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4198: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4199: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4200: #		}
1.116     ng       4201: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4202: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4203: 	    }
                   4204: 
1.257     albertel 4205: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4206: 
1.257     albertel 4207: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4208: 		if ($record{'version'} eq '') {
1.398     albertel 4209: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4210: 		} else {
1.116     ng       4211: 		    my %responseType = ();
                   4212: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4213: 			my @responseIds =$curRes->responseIds($partid);
                   4214: 			my @responseType =$curRes->responseType($partid);
                   4215: 			my %responseIds;
                   4216: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4217: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4218: 			}
                   4219: 			$responseType{$partid} = \%responseIds;
1.116     ng       4220: 		    }
1.148     albertel 4221: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4222: 
1.71      ng       4223: 		}
1.257     albertel 4224: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4225: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4226: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4227: 									$env{'request.course.id'},
1.71      ng       4228: 									'','.submission');
                   4229:  
                   4230: 	    }
1.103     albertel 4231: 	    if (&canmodify($usec)) {
                   4232: 		foreach my $partid (@{$parts}) {
                   4233: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4234: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4235: 		    $question++;
                   4236: 		}
1.196     albertel 4237: 		$prob++;
1.71      ng       4238: 	    }
                   4239: 	    $studentTable.='</td></tr>';
1.68      ng       4240: 
1.103     albertel 4241: 	}
1.68      ng       4242:         $curRes = $iterator->next();
                   4243:     }
                   4244: 
1.381     albertel 4245:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4246: 	'<input type="button" value="Save" '.
1.381     albertel 4247: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4248: 	'</form>'."\n";
1.324     albertel 4249:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4250:     $request->print($studentTable);
                   4251: 
                   4252:     return '';
1.119     ng       4253: }
                   4254: 
                   4255: sub displaySubByDates {
1.148     albertel 4256:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4257:     my $isCODE=0;
1.335     albertel 4258:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4259:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4260:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4261: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4262: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4263: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4264: 	'<td><b>Submission</b></td>'.
                   4265: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4266:     my ($version);
                   4267:     my %mark;
1.148     albertel 4268:     my %orders;
1.119     ng       4269:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4270:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4271: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4272:     }
1.335     albertel 4273: 
                   4274:     my $interaction;
1.119     ng       4275:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4276: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4277: 	if (exists($$record{$version.':resource.0.version'})) {
                   4278: 	    $interaction = $$record{$version.':resource.0.version'};
                   4279: 	}
                   4280: 
                   4281: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4282: 		             : "$version:resource");
1.119     ng       4283: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4284: 	if ($isCODE) {
                   4285: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4286: 	}
1.119     ng       4287: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4288: 	my @displaySub = ();
                   4289: 	foreach my $partid (@{$parts}) {
1.335     albertel 4290: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4291: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4292: 	    
                   4293: 
1.122     ng       4294: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4295: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4296: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4297: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4298: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4299: 
                   4300: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4301: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4302: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4303: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4304: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4305: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4306: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4307: 		    } else {
                   4308: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4309: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4310: 		    }
1.335     albertel 4311: 		    my $responseType=($isTask ? 'Task'
                   4312:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4313: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4314: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4315: 			$orders{$partid}->{$responseId}=
                   4316: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4317: 		    }
1.147     albertel 4318: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4319: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4320: 		}
                   4321: 	    }
1.335     albertel 4322: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4323: 		$displaySub[1].='Checked in by '.
                   4324: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4325: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4326: 		    '<br />';
                   4327: 	    }
                   4328: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4329: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4330: 		    lc($$record{"$where.$partid.award"}).' '.
                   4331: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4332: 		    '<br />';
                   4333: 	    }
1.335     albertel 4334: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4335: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4336: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4337: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4338: 		$displaySub[2].=
                   4339: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4340: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4341: 	    }
                   4342: 	}
                   4343: 	# needed because old essay regrader has not parts info
                   4344: 	if (exists $$record{"$version:resource.regrader"}) {
                   4345: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4346: 	}
                   4347: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4348: 	if ($displaySub[2]) {
                   4349: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4350: 	}
1.382     albertel 4351: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4352:     
1.119     ng       4353:     }
                   4354:     $studentTable.='</table></td></tr></table>';
                   4355:     return $studentTable;
1.71      ng       4356: }
                   4357: 
                   4358: sub updateGradeByPage {
                   4359:     my ($request) = shift;
                   4360: 
1.257     albertel 4361:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4362:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4363:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4364:     my $pageTitle = $env{'form.page'};
1.103     albertel 4365:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4366:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4367:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4368:     if (!&canmodify($usec)) {
1.398     albertel 4369: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4370: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4371: 	return;
                   4372:     }
1.398     albertel 4373:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4374:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4375: 	'</h3>'."\n";
1.70      ng       4376: 
1.68      ng       4377:     $request->print($result);
                   4378: 
1.132     bowersj2 4379:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4380:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4381:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4382:     if (!$map) {
1.398     albertel 4383: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4384: 	my ($symb)=&get_symb($request);
                   4385: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4386: 	return; 
                   4387:     }
1.71      ng       4388:     my $iterator = $navmap->getIterator($map->map_start(),
                   4389: 					$map->map_finish());
1.70      ng       4390: 
1.71      ng       4391:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4392: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4393: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4394: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4395: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4396: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4397: 
                   4398:     $iterator->next(); # skip the first BEGIN_MAP
                   4399:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4400:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4401:     while ($depth > 0) {
1.71      ng       4402:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4403:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4404: 
1.385     albertel 4405:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4406: 	    my $parts = $curRes->parts();
1.71      ng       4407:             my $title = $curRes->compTitle();
                   4408: 	    my $symbx = $curRes->symb();
1.196     albertel 4409: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4410: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4411: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4412: 
                   4413: 	    my %newrecord=();
                   4414: 	    my @displayPts=();
1.269     raeburn  4415:             my %aggregate = ();
                   4416:             my $aggregateflag = 0;
1.71      ng       4417: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4418: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4419: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4420: 
1.257     albertel 4421: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4422: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4423: 		my $partial = $newpts/$wgt;
                   4424: 		my $score;
                   4425: 		if ($partial > 0) {
                   4426: 		    $score = 'correct_by_override';
1.125     ng       4427: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4428: 		    $score = 'incorrect_by_override';
                   4429: 		}
1.257     albertel 4430: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4431: 		if ($dropMenu eq 'excused') {
1.71      ng       4432: 		    $partial = '';
                   4433: 		    $score = 'excused';
1.125     ng       4434: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4435: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4436: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4437: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4438: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4439: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4440: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4441: 		    $changeflag++;
                   4442: 		    $newpts = '';
1.269     raeburn  4443:                     
                   4444:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4445:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4446:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4447:                     if ($aggtries > 0) {
                   4448:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4449:                         $aggregateflag = 1;
                   4450:                     }
1.71      ng       4451: 		}
1.324     albertel 4452: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4453: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4454: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4455: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4456: 		    '&nbsp;<br />';
1.207     albertel 4457: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4458: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4459: 		    '&nbsp;<br />';
1.71      ng       4460: 		$question++;
1.380     albertel 4461: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4462: 
1.71      ng       4463: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4464: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4465: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4466: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4467: 
                   4468: 		$changeflag++;
                   4469: 	    }
                   4470: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4471: 		my %record = 
                   4472: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4473: 					     $udom,$uname);
                   4474: 
                   4475: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4476: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4477: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4478: 		    $newrecord{'resource.CODE'} = '';
                   4479: 		}
1.257     albertel 4480: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4481: 					$udom,$uname);
1.382     albertel 4482: 		%record = &Apache::lonnet::restore($symbx,
                   4483: 						   $env{'request.course.id'},
                   4484: 						   $udom,$uname);
1.380     albertel 4485: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4486: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4487: 	    }
1.380     albertel 4488: 	    
1.269     raeburn  4489:             if ($aggregateflag) {
                   4490:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4491:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4492:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4493:             }
1.125     ng       4494: 
1.71      ng       4495: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4496: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4497: 		'</tr>';
1.68      ng       4498: 
1.196     albertel 4499: 	    $prob++;
1.68      ng       4500: 	}
1.71      ng       4501:         $curRes = $iterator->next();
1.68      ng       4502:     }
1.98      albertel 4503: 
1.71      ng       4504:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4505:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4506:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4507: 		  'The scores were changed for '.
                   4508: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4509:     $request->print($grademsg.$studentTable);
1.68      ng       4510: 
1.70      ng       4511:     return '';
                   4512: }
                   4513: 
1.72      ng       4514: #-------- end of section for handling grading by page/sequence ---------
                   4515: #
                   4516: #-------------------------------------------------------------------
                   4517: 
1.75      albertel 4518: #--------------------Scantron Grading-----------------------------------
                   4519: #
                   4520: #------ start of section for handling grading by page/sequence ---------
                   4521: 
1.423     albertel 4522: =pod
                   4523: 
                   4524: =head1 Bubble sheet grading routines
                   4525: 
1.424     albertel 4526:   For this documentation:
                   4527: 
                   4528:    'scanline' refers to the full line of characters
                   4529:    from the file that we are parsing that represents one entire sheet
                   4530: 
                   4531:    'bubble line' refers to the data
                   4532:    representing the line of bubbles that are on the physical bubble sheet
                   4533: 
                   4534: 
                   4535: The overall process is that a scanned in bubble sheet data is uploaded
                   4536: into a course. When a user wants to grade, they select a
                   4537: sequence/folder of resources, a file of bubble sheet info, and pick
                   4538: one of the predefined configurations for what each scanline looks
                   4539: like.
                   4540: 
                   4541: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4542: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4543: because too light bubbling), 'double bubble' (each bubble line should
                   4544: have no more that one letter picked), invalid or duplicated CODE,
                   4545: invalid student ID
                   4546: 
                   4547: If the CODE option is used that determines the randomization of the
                   4548: homework problems, either way the student ID is looked up into a
                   4549: username:domain.
                   4550: 
                   4551: During the validation phase the instructor can choose to skip scanlines. 
                   4552: 
1.435     foxr     4553: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4554: 
                   4555:   scantron_original_filename (unmodified original file)
                   4556:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4557:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4558: 
                   4559: Also there is a separate hash nohist_scantrondata that contains extra
                   4560: correction information that isn't representable in the bubble sheet
                   4561: file (see &scantron_getfile() for more information)
                   4562: 
                   4563: After all scanlines are either valid, marked as valid or skipped, then
                   4564: foreach line foreach problem in the picked sequence, an ssi request is
                   4565: made that simulates a user submitting their selected letter(s) against
                   4566: the homework problem.
1.423     albertel 4567: 
                   4568: =over 4
                   4569: 
                   4570: 
                   4571: 
                   4572: =item defaultFormData
                   4573: 
                   4574:   Returns html hidden inputs used to hold context/default values.
                   4575: 
                   4576:  Arguments:
                   4577:   $symb - $symb of the current resource 
                   4578: 
                   4579: =cut
1.422     foxr     4580: 
1.81      albertel 4581: sub defaultFormData {
1.324     albertel 4582:     my ($symb)=@_;
1.447     foxr     4583:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4584:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4585:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4586: }
                   4587: 
1.447     foxr     4588: 
1.423     albertel 4589: =pod 
                   4590: 
                   4591: =item getSequenceDropDown
                   4592: 
                   4593:    Return html dropdown of possible sequences to grade
                   4594:  
                   4595:  Arguments:
                   4596:    $symb - $symb of the current resource 
                   4597: 
                   4598: =cut
1.422     foxr     4599: 
1.75      albertel 4600: sub getSequenceDropDown {
1.423     albertel 4601:     my ($symb)=@_;
1.75      albertel 4602:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4603:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4604:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4605:     my $ctr=0;
                   4606:     foreach (@$titles) {
                   4607: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4608: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4609: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4610: 	    '>'.$showtitle.'</option>'."\n";
                   4611: 	$ctr++;
                   4612:     }
                   4613:     $result.= '</select>';
                   4614:     return $result;
                   4615: }
                   4616: 
1.423     albertel 4617: 
                   4618: =pod 
                   4619: 
                   4620: =item scantron_filenames
                   4621: 
                   4622:    Returns a list of the scantron files in the current course 
                   4623: 
                   4624: =cut
1.422     foxr     4625: 
1.202     albertel 4626: sub scantron_filenames {
1.257     albertel 4627:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4628:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4629:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4630: 				    &propath($cdom,$cname));
1.202     albertel 4631:     my @possiblenames;
1.201     albertel 4632:     foreach my $filename (sort(@files)) {
1.157     albertel 4633: 	($filename)=split(/&/,$filename);
                   4634: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4635: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4636: 	push(@possiblenames,$filename);
                   4637:     }
                   4638:     return @possiblenames;
                   4639: }
                   4640: 
1.423     albertel 4641: =pod 
                   4642: 
                   4643: =item scantron_uploads
                   4644: 
                   4645:    Returns  html drop-down list of scantron files in current course.
                   4646: 
                   4647:  Arguments:
                   4648:    $file2grade - filename to set as selected in the dropdown
                   4649: 
                   4650: =cut
1.422     foxr     4651: 
1.202     albertel 4652: sub scantron_uploads {
1.209     ng       4653:     my ($file2grade) = @_;
1.202     albertel 4654:     my $result=	'<select name="scantron_selectfile">';
                   4655:     $result.="<option></option>";
                   4656:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4657: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4658:     }
                   4659:     $result.="</select>";
                   4660:     return $result;
                   4661: }
                   4662: 
1.423     albertel 4663: =pod 
                   4664: 
                   4665: =item scantron_scantab
                   4666: 
                   4667:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4668:   file.
                   4669: 
                   4670: =cut
1.422     foxr     4671: 
1.82      albertel 4672: sub scantron_scantab {
                   4673:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4674:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4675:     $result.='<option></option>'."\n";
1.82      albertel 4676:     foreach my $line (<$fh>) {
                   4677: 	my ($name,$descrip)=split(/:/,$line);
                   4678: 	if ($name =~ /^\#/) { next; }
                   4679: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4680:     }
                   4681:     $result.='</select>'."\n";
                   4682: 
                   4683:     return $result;
                   4684: }
                   4685: 
1.423     albertel 4686: =pod 
                   4687: 
                   4688: =item scantron_CODElist
                   4689: 
                   4690:   Returns html drop down of the saved CODE lists from current course,
                   4691:   generated from earlier printings.
                   4692: 
                   4693: =cut
1.422     foxr     4694: 
1.186     albertel 4695: sub scantron_CODElist {
1.257     albertel 4696:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4697:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4698:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4699:     my $namechoice='<option></option>';
1.225     albertel 4700:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4701: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4702: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4703: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4704:     }
                   4705:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4706:     return $namechoice;
                   4707: }
                   4708: 
1.423     albertel 4709: =pod 
                   4710: 
                   4711: =item scantron_CODEunique
                   4712: 
                   4713:   Returns the html for "Each CODE to be used once" radio.
                   4714: 
                   4715: =cut
1.422     foxr     4716: 
1.186     albertel 4717: sub scantron_CODEunique {
1.381     albertel 4718:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4719:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4720:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4721:                 </span>
                   4722:                 <span style="white-space: nowrap;">
1.272     albertel 4723:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4724:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4725:                 </span>';
1.186     albertel 4726:     return $result;
                   4727: }
1.423     albertel 4728: 
                   4729: =pod 
                   4730: 
                   4731: =item scantron_selectphase
                   4732: 
                   4733:   Generates the initial screen to start the bubble sheet process.
                   4734:   Allows for - starting a grading run.
1.424     albertel 4735:              - downloading existing scan data (original, corrected
1.423     albertel 4736:                                                 or skipped info)
                   4737: 
                   4738:              - uploading new scan data
                   4739: 
                   4740:  Arguments:
                   4741:   $r          - The Apache request object
                   4742:   $file2grade - name of the file that contain the scanned data to score
                   4743: 
                   4744: =cut
1.186     albertel 4745: 
1.75      albertel 4746: sub scantron_selectphase {
1.209     ng       4747:     my ($r,$file2grade) = @_;
1.324     albertel 4748:     my ($symb)=&get_symb($r);
1.75      albertel 4749:     if (!$symb) {return '';}
1.423     albertel 4750:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4751:     my $default_form_data=&defaultFormData($symb);
                   4752:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4753:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4754:     my $format_selector=&scantron_scantab();
1.186     albertel 4755:     my $CODE_selector=&scantron_CODElist();
                   4756:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4757:     my $result;
1.422     foxr     4758: 
                   4759:     # Chunk of form to prompt for a file to grade and how:
                   4760: 
1.75      albertel 4761:     $result.= <<SCANTRONFORM;
1.162     albertel 4762:     <table width="100%" border="0">
1.75      albertel 4763:     <tr>
1.226     albertel 4764:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4765:       <td bgcolor="#777777">
1.203     albertel 4766:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4767:         $default_form_data
1.75      albertel 4768:         <table width="100%" border="0">
                   4769:           <tr bgcolor="#e6ffff">
1.174     albertel 4770:             <td colspan="2">
                   4771:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4772:             </td>
                   4773:           </tr>
                   4774:           <tr bgcolor="#ffffe6">
1.174     albertel 4775:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4776:           </tr>
                   4777:           <tr bgcolor="#ffffe6">
1.174     albertel 4778:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4779:           </tr>
1.82      albertel 4780:           <tr bgcolor="#ffffe6">
1.174     albertel 4781:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4782:           </tr>
1.157     albertel 4783:           <tr bgcolor="#ffffe6">
1.186     albertel 4784:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4785:           </tr>
                   4786:           <tr bgcolor="#ffffe6">
                   4787:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4788:           </tr>
                   4789:           <tr bgcolor="#ffffe6">
1.187     albertel 4790: 	    <td> Options: </td>
                   4791:             <td>
1.272     albertel 4792: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4793:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4794:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4795: 	    </td>
                   4796:           </tr>
                   4797:           <tr bgcolor="#ffffe6">
1.174     albertel 4798:             <td colspan="2">
1.265     www      4799:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4800:             </td>
                   4801:           </tr>
                   4802:         </table>
1.226     albertel 4803:        </td>
                   4804:      </form>
1.162     albertel 4805:     </tr>
                   4806: SCANTRONFORM
                   4807:    
                   4808:     $r->print($result);
                   4809: 
1.257     albertel 4810:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4811:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4812: 
1.422     foxr     4813: 	# Chunk of form to prompt for a scantron file upload.
                   4814: 
1.162     albertel 4815:         $r->print(<<SCANTRONFORM);
                   4816:     <tr>
                   4817:       <td bgcolor="#777777">
                   4818:         <table width="100%" border="0">
                   4819:           <tr bgcolor="#e6ffff">
                   4820:             <td>
1.174     albertel 4821:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4822:             </td>
                   4823:           </tr>
                   4824:           <tr bgcolor="#ffffe6">
                   4825:             <td>
                   4826: SCANTRONFORM
1.324     albertel 4827:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4828:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4829:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4830:     $r->print(<<UPLOAD);
                   4831:               <script type="text/javascript" language="javascript">
                   4832:     function checkUpload(formname) {
                   4833: 	if (formname.upfile.value == "") {
                   4834: 	    alert("Please use the browse button to select a file from your local directory.");
                   4835: 	    return false;
                   4836: 	}
                   4837: 	formname.submit();
                   4838:     }
                   4839:               </script>
                   4840: 
                   4841:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4842:                 $default_form_data
                   4843:                 <input name='courseid' type='hidden' value='$cnum' />
                   4844:                 <input name='domainid' type='hidden' value='$cdom' />
                   4845:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4846:                 File to upload:<input type="file" name="upfile" size="50" />
                   4847:                 <br />
                   4848:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4849:               </form>
                   4850: UPLOAD
1.162     albertel 4851: 
                   4852:         $r->print(<<SCANTRONFORM);
                   4853:             </td>
                   4854:           </tr>
1.75      albertel 4855:         </table>
                   4856:       </td>
                   4857:     </tr>
1.162     albertel 4858: SCANTRONFORM
                   4859:     }
1.422     foxr     4860: 
                   4861:     # Chunk of the form that prompts to view a scoring office file,
                   4862:     # corrected file, skipped records in a file.
                   4863: 
1.187     albertel 4864:     $r->print(<<SCANTRONFORM);
                   4865:     <tr>
1.226     albertel 4866:       <form action='/adm/grades' name='scantron_download'>
                   4867:         <td bgcolor="#777777">
1.379     albertel 4868: 	  $default_form_data
1.187     albertel 4869:           <input type="hidden" name="command" value="scantron_download" />
                   4870:           <table width="100%" border="0">
                   4871:             <tr bgcolor="#e6ffff">
                   4872:               <td colspan="2">
                   4873:                 &nbsp;<b>Download a scoring office file</b>
                   4874:               </td>
                   4875:             </tr>
                   4876:             <tr bgcolor="#ffffe6">
                   4877:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4878:             </tr>
                   4879:             <tr bgcolor="#ffffe6">
                   4880:               <td colspan="2">
1.293     www      4881:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4882:               </td>
                   4883:             </tr>
                   4884:           </table>
1.226     albertel 4885:         </td>
                   4886:       </form>
1.187     albertel 4887:     </tr>
                   4888: SCANTRONFORM
1.162     albertel 4889: 
                   4890:     $r->print(<<SCANTRONFORM);
1.75      albertel 4891:   </table>
1.81      albertel 4892: $grading_menu_button
1.75      albertel 4893: SCANTRONFORM
                   4894: 
1.162     albertel 4895:     return
1.75      albertel 4896: }
                   4897: 
1.423     albertel 4898: =pod
                   4899: 
                   4900: =item get_scantron_config
                   4901: 
                   4902:    Parse and return the scantron configuration line selected as a
                   4903:    hash of configuration file fields.
                   4904: 
                   4905:  Arguments:
                   4906:     which - the name of the configuration to parse from the file.
                   4907: 
                   4908: 
                   4909:  Returns:
                   4910:             If the named configuration is not in the file, an empty
                   4911:             hash is returned.
                   4912:     a hash with the fields
                   4913:       name         - internal name for the this configuration setup
                   4914:       description  - text to display to operator that describes this config
                   4915:       CODElocation - if 0 or the string 'none'
                   4916:                           - no CODE exists for this config
                   4917:                      if -1 || the string 'letter'
                   4918:                           - a CODE exists for this config and is
                   4919:                             a string of letters
                   4920:                      Unsupported value (but planned for future support)
                   4921:                           if a positive integer
                   4922:                                - The CODE exists as the first n items from
                   4923:                                  the question section of the form
                   4924:                           if the string 'number'
                   4925:                                - The CODE exists for this config and is
                   4926:                                  a string of numbers
                   4927:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4928:                      the CODE starts
                   4929:       CODElength  - length of the CODE
                   4930:       IDstart     - column where the student ID number starts
                   4931:       IDlength    - length of the student ID info
                   4932:       Qstart      - column where the information from the bubbled
                   4933:                     'questions' start
                   4934:       Qlength     - number of columns comprising a single bubble line from
                   4935:                     the sheet. (usually either 1 or 10)
1.424     albertel 4936:       Qon         - either a single character representing the character used
1.423     albertel 4937:                     to signal a bubble was chosen in the positional setup, or
                   4938:                     the string 'letter' if the letter of the chosen bubble is
                   4939:                     in the final, or 'number' if a number representing the
                   4940:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4941:       Qoff        - the character used to represent that a bubble was
                   4942:                     left blank
1.423     albertel 4943:       PaperID     - if the scanning process generates a unique number for each
                   4944:                     sheet scanned the column that this ID number starts in
                   4945:       PaperIDlength - number of columns that comprise the unique ID number
                   4946:                       for the sheet of paper
1.424     albertel 4947:       FirstName   - column that the first name starts in
1.423     albertel 4948:       FirstNameLength - number of columns that the first name spans
                   4949:  
                   4950:       LastName    - column that the last name starts in
                   4951:       LastNameLength - number of columns that the last name spans
                   4952: 
                   4953: =cut
1.422     foxr     4954: 
1.82      albertel 4955: sub get_scantron_config {
                   4956:     my ($which) = @_;
                   4957:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4958:     my %config;
1.157     albertel 4959:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4960:     foreach my $line (<$fh>) {
                   4961: 	my ($name,$descrip)=split(/:/,$line);
                   4962: 	if ($name ne $which ) { next; }
                   4963: 	chomp($line);
                   4964: 	my @config=split(/:/,$line);
                   4965: 	$config{'name'}=$config[0];
                   4966: 	$config{'description'}=$config[1];
                   4967: 	$config{'CODElocation'}=$config[2];
                   4968: 	$config{'CODEstart'}=$config[3];
                   4969: 	$config{'CODElength'}=$config[4];
                   4970: 	$config{'IDstart'}=$config[5];
                   4971: 	$config{'IDlength'}=$config[6];
                   4972: 	$config{'Qstart'}=$config[7];
                   4973: 	$config{'Qlength'}=$config[8];
                   4974: 	$config{'Qoff'}=$config[9];
                   4975: 	$config{'Qon'}=$config[10];
1.157     albertel 4976: 	$config{'PaperID'}=$config[11];
                   4977: 	$config{'PaperIDlength'}=$config[12];
                   4978: 	$config{'FirstName'}=$config[13];
                   4979: 	$config{'FirstNamelength'}=$config[14];
                   4980: 	$config{'LastName'}=$config[15];
                   4981: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4982: 	last;
                   4983:     }
                   4984:     return %config;
                   4985: }
                   4986: 
1.423     albertel 4987: =pod 
                   4988: 
                   4989: =item username_to_idmap
                   4990: 
                   4991:     creates a hash keyed by student id with values of the corresponding
                   4992:     student username:domain.
                   4993: 
                   4994:   Arguments:
                   4995: 
                   4996:     $classlist - reference to the class list hash. This is a hash
                   4997:                  keyed by student name:domain  whose elements are references
1.424     albertel 4998:                  to arrays containing various chunks of information
1.423     albertel 4999:                  about the student. (See loncoursedata for more info).
                   5000: 
                   5001:   Returns
                   5002:     %idmap - the constructed hash
                   5003: 
                   5004: =cut
                   5005: 
1.82      albertel 5006: sub username_to_idmap {
                   5007:     my ($classlist)= @_;
                   5008:     my %idmap;
                   5009:     foreach my $student (keys(%$classlist)) {
                   5010: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5011: 	    $student;
                   5012:     }
                   5013:     return %idmap;
                   5014: }
1.423     albertel 5015: 
                   5016: =pod
                   5017: 
1.424     albertel 5018: =item scantron_fixup_scanline
1.423     albertel 5019: 
                   5020:    Process a requested correction to a scanline.
                   5021: 
                   5022:   Arguments:
                   5023:     $scantron_config   - hash from &get_scantron_config()
                   5024:     $scan_data         - hash of correction information 
                   5025:                           (see &scantron_getfile())
                   5026:     $line              - existing scanline
                   5027:     $whichline         - line number of the passed in scanline
                   5028:     $field             - type of change to process 
                   5029:                          (either 
                   5030:                           'ID'     -> correct the student ID number
                   5031:                           'CODE'   -> correct the CODE
                   5032:                           'answer' -> fixup the submitted answers)
                   5033:     
                   5034:    $args               - hash of additional info,
                   5035:                           - 'ID' 
                   5036:                                'newid' -> studentID to use in replacement
1.424     albertel 5037:                                           of existing one
1.423     albertel 5038:                           - 'CODE' 
                   5039:                                'CODE_ignore_dup' - set to true if duplicates
                   5040:                                                    should be ignored.
                   5041: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5042:                                         if the existing unfound code should
1.423     albertel 5043:                                         be used as is
                   5044:                           - 'answer'
                   5045:                                'response' - new answer or 'none' if blank
                   5046:                                'question' - the bubble line to change
                   5047: 
                   5048:   Returns:
                   5049:     $line - the modified scanline
                   5050: 
                   5051:   Side effects: 
                   5052:     $scan_data - may be updated
                   5053: 
                   5054: =cut
                   5055: 
1.82      albertel 5056: 
1.157     albertel 5057: sub scantron_fixup_scanline {
                   5058:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5059: 
1.157     albertel 5060:     if ($field eq 'ID') {
                   5061: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5062: 	    return ($line,1,'New value too large');
1.157     albertel 5063: 	}
                   5064: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5065: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5066: 				     $args->{'newid'});
                   5067: 	}
                   5068: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5069: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5070: 	if ($args->{'newid'}=~/^\s*$/) {
                   5071: 	    &scan_data($scan_data,"$whichline.user",
                   5072: 		       $args->{'username'}.':'.$args->{'domain'});
                   5073: 	}
1.186     albertel 5074:     } elsif ($field eq 'CODE') {
1.192     albertel 5075: 	if ($args->{'CODE_ignore_dup'}) {
                   5076: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5077: 	}
                   5078: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5079: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5080: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5081: 		return ($line,1,'New CODE value too large');
                   5082: 	    }
                   5083: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5084: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5085: 	    }
                   5086: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5087: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5088: 	}
1.157     albertel 5089:     } elsif ($field eq 'answer') {
                   5090: 	my $length=$scantron_config->{'Qlength'};
                   5091: 	my $off=$scantron_config->{'Qoff'};
                   5092: 	my $on=$scantron_config->{'Qon'};
                   5093: 	my $answer=${off}x$length;
                   5094: 	if ($args->{'response'} eq 'none') {
                   5095: 	    &scan_data($scan_data,
                   5096: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5097: 	} else {
1.274     albertel 5098: 	    if ($on eq 'letter') {
                   5099: 		my @alphabet=('A'..'Z');
                   5100: 		$answer=$alphabet[$args->{'response'}];
                   5101: 	    } elsif ($on eq 'number') {
                   5102: 		$answer=$args->{'response'}+1;
1.389     albertel 5103: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5104: 	    } else {
                   5105: 		substr($answer,$args->{'response'},1)=$on;
                   5106: 	    }
1.157     albertel 5107: 	    &scan_data($scan_data,
                   5108: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5109: 	}
                   5110: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5111: 	substr($line,$where-1,$length)=$answer;
                   5112:     }
                   5113:     return $line;
                   5114: }
1.423     albertel 5115: 
                   5116: =pod
                   5117: 
                   5118: =item scan_data
                   5119: 
                   5120:     Edit or look up  an item in the scan_data hash.
                   5121: 
                   5122:   Arguments:
                   5123:     $scan_data  - The hash (see scantron_getfile)
                   5124:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5125:                   scantronfilename_key).
1.423     albertel 5126:     $data        - New value of the hash entry.
                   5127:     $delete      - If true, the entry is removed from the hash.
                   5128: 
                   5129:   Returns:
                   5130:     The new value of the hash table field (undefined if deleted).
                   5131: 
                   5132: =cut
                   5133: 
                   5134: 
1.157     albertel 5135: sub scan_data {
                   5136:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5137:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5138:     if (defined($value)) {
                   5139: 	$scan_data->{$filename.'_'.$key} = $value;
                   5140:     }
                   5141:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5142:     return $scan_data->{$filename.'_'.$key};
                   5143: }
1.423     albertel 5144: 
                   5145: =pod 
                   5146: 
                   5147: =item scantron_parse_scanline
                   5148: 
                   5149:   Decodes a scanline from the selected scantron file
                   5150: 
                   5151:  Arguments:
                   5152:     line             - The text of the scantron file line to process
                   5153:     whichline        - Line number
                   5154:     scantron_config  - Hash describing the format of the scantron lines.
                   5155:     scan_data        - Hash of extra information about the scanline
                   5156:                        (see scantron_getfile for more information)
                   5157:     just_header      - True if should not process question answers but only
                   5158:                        the stuff to the left of the answers.
                   5159:  Returns:
                   5160:    Hash containing the result of parsing the scanline
                   5161: 
                   5162:    Keys are all proceeded by the string 'scantron.'
                   5163: 
                   5164:        CODE    - the CODE in use for this scanline
                   5165:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5166:                  by the operator
                   5167:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5168:                             CODEs were selected, but the usage has been
                   5169:                             forced by the operator
                   5170:        ID  - student ID
                   5171:        PaperID - if used, the ID number printed on the sheet when the 
                   5172:                  paper was scanned
                   5173:        FirstName - first name from the sheet
                   5174:        LastName  - last name from the sheet
                   5175: 
                   5176:      if just_header was not true these key may also exist
                   5177: 
1.447     foxr     5178:        missingerror - a list of bubble ranges that are considered to be answers
                   5179:                       to a single question that don't have any bubbles filled in.
                   5180:                       Of the form questionnumber:firstbubblenumber:count.
                   5181:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5182:                       to a single question that have more than one bubble filled in.
                   5183:                       Of the form questionnumber::firstbubblenumber:count
                   5184:    
                   5185:                 In the above, count is the number of bubble responses in the
                   5186:                 input line needed to represent the possible answers to the question.
                   5187:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5188:                 per line would have count = 2.
                   5189: 
1.423     albertel 5190:        maxquest     - the number of the last bubble line that was parsed
                   5191: 
                   5192:        (<number> starts at 1)
                   5193:        <number>.answer - zero or more letters representing the selected
                   5194:                          letters from the scanline for the bubble line 
                   5195:                          <number>.
                   5196:                          if blank there was either no bubble or there where
                   5197:                          multiple bubbles, (consult the keys missingerror and
                   5198:                          doubleerror if this is an error condition)
                   5199: 
                   5200: =cut
                   5201: 
1.82      albertel 5202: sub scantron_parse_scanline {
1.423     albertel 5203:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5204:     my %record;
1.422     foxr     5205:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5206:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5207:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5208: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5209: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5210: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5211: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5212: 	    $record{'scantron.CODE'}=substr($data,
                   5213: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5214: 					    $$scantron_config{'CODElength'});
1.191     albertel 5215: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5216: 		$record{'scantron.useCODE'}=1;
                   5217: 	    }
1.192     albertel 5218: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5219: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5220: 	    }
1.82      albertel 5221: 	} else {
                   5222: 	    #FIXME interpret first N questions
                   5223: 	}
                   5224:     }
1.83      albertel 5225:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5226: 				  $$scantron_config{'IDlength'});
1.157     albertel 5227:     $record{'scantron.PaperID'}=
                   5228: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5229: 	       $$scantron_config{'PaperIDlength'});
                   5230:     $record{'scantron.FirstName'}=
                   5231: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5232: 	       $$scantron_config{'FirstNamelength'});
                   5233:     $record{'scantron.LastName'}=
                   5234: 	substr($data,$$scantron_config{'LastName'}-1,
                   5235: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5236:     if ($just_header) { return \%record; }
1.194     albertel 5237: 
1.82      albertel 5238:     my @alphabet=('A'..'Z');
                   5239:     my $questnum=0;
1.447     foxr     5240:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5241: 
1.82      albertel 5242:     while ($questions) {
1.447     foxr     5243: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5244: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5245: 
                   5246: 
                   5247: 
1.82      albertel 5248: 	$questnum++;
1.447     foxr     5249: 	my $currentquest = substr($questions,0,$answer_length);
                   5250: 	$questions       = substr($questions,0,$answer_length)='';
                   5251: 	if (length($currentquest) < $answer_length) { next; }
                   5252: 
                   5253: 	# Qon letter implies for each slot in currentquest we have:
                   5254: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5255:         #    about anything else (esp. a value of Qoff for missing
                   5256: 	#    bubbles.
                   5257: 
                   5258: 
1.239     albertel 5259: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5260: 
                   5261: 	    if ($currentquest =~ /\?/
                   5262: 		|| $currentquest =~ /\*/
                   5263: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5264: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5265: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5266: 		    $record{"scantron.$ansnum.answer"}='';
                   5267: 		    $ansnum++;
                   5268: 		}
                   5269: 
1.389     albertel 5270: 	    } elsif (!defined($currentquest)
1.447     foxr     5271: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5272: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5273: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5274: 		    $record{"scantron.$ansnum.answer"}='';
                   5275: 		    $ansnum++;
                   5276: 
                   5277: 		}
1.239     albertel 5278: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5279: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5280: 		    $ansnum += $answers_needed;
1.239     albertel 5281: 		}
1.447     foxr     5282: 
1.239     albertel 5283: 	    } else {
1.447     foxr     5284: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5285: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5286: 		    $ansnum++;
                   5287: 		}
1.239     albertel 5288: 	    }
1.447     foxr     5289: 
                   5290: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5291: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5292:         #    and *? for double bubbles on a line.
                   5293: 	#    these answers are also stored as letters.
                   5294: 
1.239     albertel 5295: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5296: 	    if ($currentquest =~ /\?/
                   5297: 		|| $currentquest =~ /\*/
                   5298: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5299: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5300: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5301: 		    $record{"scantron.$ansnum.answer"}='';
                   5302: 		    $ansnum++;
                   5303: 		}
                   5304: 
1.389     albertel 5305: 	    } elsif (!defined($currentquest)
1.447     foxr     5306: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5307: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5308: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5309: 		    $record{"scantron.$ansnum.answer"}='';
                   5310: 		    $ansnum++;
                   5311: 
                   5312: 		}
1.239     albertel 5313: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5314: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5315: 		    $ansnum += $answers_needed;
1.239     albertel 5316: 		}
1.447     foxr     5317: 
1.239     albertel 5318: 	    } else {
1.447     foxr     5319: 		$currentquest = &digits_to_letters($currentquest);
                   5320: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5321: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5322: 		    $ansnum++;
1.371     albertel 5323: 		}
1.239     albertel 5324: 	    }
1.82      albertel 5325: 	} else {
1.447     foxr     5326: 
                   5327: 	    # Otherwise there's a positional notation;
                   5328: 	    # each bubble line requires Qlength items, and there are filled in
                   5329: 	    # bubbles for each case where there 'Qon' characters.
                   5330: 	    #
                   5331: 
1.239     albertel 5332: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5333: 
                   5334: 	    # If the split only  giveas us one element.. the full length of the
                   5335: 	    # answser string, no bubbles are filled in:
                   5336: 
                   5337: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5338: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5339: 		    $record{"scantron.$ansnum.answer"}='';
                   5340: 		    $ansnum++;
                   5341: 
                   5342: 		}
1.239     albertel 5343: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5344: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5345: 		}
1.447     foxr     5346: 	    } elsif (scalar(@array) lt 2) {
                   5347: 
                   5348: 		my $location      = [length($array[0])];
                   5349: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5350: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5351: 
                   5352: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5353: 		    if ($ans eq $line_num) {
                   5354: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5355: 		    } else {
                   5356: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5357: 		    }
                   5358: 		    $ansnum++;
                   5359: 		}
1.239     albertel 5360: 	    }
1.447     foxr     5361: 	    #  If there's more than one instance of a bubble character
                   5362: 	    #  That's a double bubble; with positional notation we can
                   5363: 	    #  record all the bubbles filled in as well as the 
                   5364: 	    #  fact this response consists of multiple bubbles.
                   5365: 	    #
                   5366: 	    else {
1.239     albertel 5367: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5368: 
                   5369: 		my $first_answer = $ansnum;
                   5370: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5371: 		    $record{"scantron.$ansnum.answer"} = '';
                   5372: 		    $ans++;
                   5373: 		}
                   5374: 
1.239     albertel 5375: 		my @ans=@array;
                   5376: 		my $i=length($ans[0]);shift(@ans);
                   5377: 		while ($#ans) {
                   5378: 		    $i+=length($ans[0])+1;
1.447     foxr     5379: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5380: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5381: 
                   5382: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5383: 		    shift(@ans);
                   5384: 		}
                   5385: 	    }
1.82      albertel 5386: 	}
                   5387:     }
1.83      albertel 5388:     $record{'scantron.maxquest'}=$questnum;
                   5389:     return \%record;
1.82      albertel 5390: }
                   5391: 
1.423     albertel 5392: =pod
                   5393: 
                   5394: =item scantron_add_delay
                   5395: 
                   5396:    Adds an error message that occurred during the grading phase to a
                   5397:    queue of messages to be shown after grading pass is complete
                   5398: 
                   5399:  Arguments:
1.424     albertel 5400:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5401:    $scanline    - the scanline that caused the error
                   5402:    $errormesage - the error message
                   5403:    $errorcode   - a numeric code for the error
                   5404: 
                   5405:  Side Effects:
1.424     albertel 5406:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5407: 
                   5408: =cut
                   5409: 
1.82      albertel 5410: sub scantron_add_delay {
1.140     albertel 5411:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5412:     push(@$delayqueue,
                   5413: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5414: 	  'ecode' => $errorcode }
                   5415: 	 );
1.82      albertel 5416: }
                   5417: 
1.423     albertel 5418: =pod
                   5419: 
                   5420: =item scantron_find_student
                   5421: 
1.424     albertel 5422:    Finds the username for the current scanline
                   5423: 
                   5424:   Arguments:
                   5425:    $scantron_record - hash result from scantron_parse_scanline
                   5426:    $scan_data       - hash of correction information 
                   5427:                       (see &scantron_getfile() form more information)
                   5428:    $idmap           - hash from &username_to_idmap()
                   5429:    $line            - number of current scanline
                   5430:  
                   5431:   Returns:
                   5432:    Either 'username:domain' or undef if unknown
                   5433: 
1.423     albertel 5434: =cut
                   5435: 
1.82      albertel 5436: sub scantron_find_student {
1.157     albertel 5437:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5438:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5439:     if ($scanID =~ /^\s*$/) {
                   5440:  	return &scan_data($scan_data,"$line.user");
                   5441:     }
1.83      albertel 5442:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5443:  	if (lc($id) eq lc($scanID)) {
                   5444:  	    return $$idmap{$id};
                   5445:  	}
1.83      albertel 5446:     }
                   5447:     return undef;
                   5448: }
                   5449: 
1.423     albertel 5450: =pod
                   5451: 
                   5452: =item scantron_filter
                   5453: 
1.424     albertel 5454:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5455:    hidden resources was selected
                   5456: 
1.423     albertel 5457: =cut
                   5458: 
1.83      albertel 5459: sub scantron_filter {
                   5460:     my ($curres)=@_;
1.331     albertel 5461: 
                   5462:     if (ref($curres) && $curres->is_problem()) {
                   5463: 	# if the user has asked to not have either hidden
                   5464: 	# or 'randomout' controlled resources to be graded
                   5465: 	# don't include them
                   5466: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5467: 	    && $curres->randomout) {
                   5468: 	    return 0;
                   5469: 	}
1.83      albertel 5470: 	return 1;
                   5471:     }
                   5472:     return 0;
1.82      albertel 5473: }
                   5474: 
1.423     albertel 5475: =pod
                   5476: 
                   5477: =item scantron_process_corrections
                   5478: 
1.424     albertel 5479:    Gets correction information out of submitted form data and corrects
                   5480:    the scanline
                   5481: 
1.423     albertel 5482: =cut
                   5483: 
1.157     albertel 5484: sub scantron_process_corrections {
                   5485:     my ($r) = @_;
1.257     albertel 5486:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5487:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5488:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5489:     my $which=$env{'form.scantron_line'};
1.200     albertel 5490:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5491:     my ($skip,$err,$errmsg);
1.257     albertel 5492:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5493: 	$skip=1;
1.257     albertel 5494:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5495: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5496: 	    $env{'form.scantron_domain'};
1.157     albertel 5497: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5498: 	($line,$err,$errmsg)=
                   5499: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5500: 				     'ID',{'newid'=>$newid,
1.257     albertel 5501: 				    'username'=>$env{'form.scantron_username'},
                   5502: 				    'domain'=>$env{'form.scantron_domain'}});
                   5503:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5504: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5505: 	my $newCODE;
1.192     albertel 5506: 	my %args;
1.190     albertel 5507: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5508: 	    $newCODE='use_unfound';
1.190     albertel 5509: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5510: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5511: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5512: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5513: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5514: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5515: 	}
1.257     albertel 5516: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5517: 	    $args{'CODE_ignore_dup'}=1;
                   5518: 	}
                   5519: 	$args{'CODE'}=$newCODE;
1.186     albertel 5520: 	($line,$err,$errmsg)=
                   5521: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5522: 				     'CODE',\%args);
1.257     albertel 5523:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5524: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5525: 	    ($line,$err,$errmsg)=
                   5526: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5527: 					 $which,'answer',
                   5528: 					 { 'question'=>$question,
1.257     albertel 5529: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5530: 	    if ($err) { last; }
                   5531: 	}
                   5532:     }
                   5533:     if ($err) {
1.398     albertel 5534: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5535:     } else {
1.200     albertel 5536: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5537: 	&scantron_putfile($scanlines,$scan_data);
                   5538:     }
                   5539: }
                   5540: 
1.423     albertel 5541: =pod
                   5542: 
                   5543: =item reset_skipping_status
                   5544: 
1.424     albertel 5545:    Forgets the current set of remember skipped scanlines (and thus
                   5546:    reverts back to considering all lines in the
                   5547:    scantron_skipped_<filename> file)
                   5548: 
1.423     albertel 5549: =cut
                   5550: 
1.200     albertel 5551: sub reset_skipping_status {
                   5552:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5553:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5554:     &scantron_putfile(undef,$scan_data);
                   5555: }
                   5556: 
1.423     albertel 5557: =pod
                   5558: 
                   5559: =item start_skipping
                   5560: 
1.424     albertel 5561:    Marks a scanline to be skipped. 
                   5562: 
1.423     albertel 5563: =cut
                   5564: 
1.376     albertel 5565: sub start_skipping {
1.200     albertel 5566:     my ($scan_data,$i)=@_;
                   5567:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5568:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5569: 	$remembered{$i}=2;
                   5570:     } else {
                   5571: 	$remembered{$i}=1;
                   5572:     }
1.200     albertel 5573:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5574: }
                   5575: 
1.423     albertel 5576: =pod
                   5577: 
                   5578: =item should_be_skipped
                   5579: 
1.424     albertel 5580:    Checks whether a scanline should be skipped.
                   5581: 
1.423     albertel 5582: =cut
                   5583: 
1.200     albertel 5584: sub should_be_skipped {
1.376     albertel 5585:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5586:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5587: 	# not redoing old skips
1.376     albertel 5588: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5589: 	return 0;
                   5590:     }
                   5591:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5592: 
                   5593:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5594: 	return 0;
                   5595:     }
1.200     albertel 5596:     return 1;
                   5597: }
                   5598: 
1.423     albertel 5599: =pod
                   5600: 
                   5601: =item remember_current_skipped
                   5602: 
1.424     albertel 5603:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5604:    file and remembers them into scan_data for later use.
                   5605: 
1.423     albertel 5606: =cut
                   5607: 
1.200     albertel 5608: sub remember_current_skipped {
                   5609:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5610:     my %to_remember;
                   5611:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5612: 	if ($scanlines->{'skipped'}[$i]) {
                   5613: 	    $to_remember{$i}=1;
                   5614: 	}
                   5615:     }
1.376     albertel 5616: 
1.200     albertel 5617:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5618:     &scantron_putfile(undef,$scan_data);
                   5619: }
                   5620: 
1.423     albertel 5621: =pod
                   5622: 
                   5623: =item check_for_error
                   5624: 
1.424     albertel 5625:     Checks if there was an error when attempting to remove a specific
                   5626:     scantron_.. bubble sheet data file. Prints out an error if
                   5627:     something went wrong.
                   5628: 
1.423     albertel 5629: =cut
                   5630: 
1.200     albertel 5631: sub check_for_error {
                   5632:     my ($r,$result)=@_;
                   5633:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5634: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5635:     }
                   5636: }
1.157     albertel 5637: 
1.423     albertel 5638: =pod
                   5639: 
                   5640: =item scantron_warning_screen
                   5641: 
1.424     albertel 5642:    Interstitial screen to make sure the operator has selected the
                   5643:    correct options before we start the validation phase.
                   5644: 
1.423     albertel 5645: =cut
                   5646: 
1.203     albertel 5647: sub scantron_warning_screen {
                   5648:     my ($button_text)=@_;
1.257     albertel 5649:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5650:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5651:     my $CODElist;
1.284     albertel 5652:     if ($scantron_config{'CODElocation'} &&
                   5653: 	$scantron_config{'CODEstart'} &&
                   5654: 	$scantron_config{'CODElength'}) {
                   5655: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5656: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5657: 	$CODElist=
                   5658: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5659: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5660:     }
1.203     albertel 5661:     return (<<STUFF);
                   5662: <p>
1.398     albertel 5663: <span class="LC_warning">Please double check the information
                   5664:                  below before clicking on '$button_text'</span>
1.203     albertel 5665: </p>
                   5666: <table>
1.284     albertel 5667: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5668: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5669: $CODElist
1.203     albertel 5670: </table>
                   5671: <br />
                   5672: <p> If this information is correct, please click on '$button_text'.</p>
                   5673: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5674: 
                   5675: <br />
                   5676: STUFF
                   5677: }
                   5678: 
1.423     albertel 5679: =pod
                   5680: 
                   5681: =item scantron_do_warning
                   5682: 
1.424     albertel 5683:    Check if the operator has picked something for all required
                   5684:    fields. Error out if something is missing.
                   5685: 
1.423     albertel 5686: =cut
                   5687: 
1.203     albertel 5688: sub scantron_do_warning {
                   5689:     my ($r)=@_;
1.324     albertel 5690:     my ($symb)=&get_symb($r);
1.203     albertel 5691:     if (!$symb) {return '';}
1.324     albertel 5692:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5693:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5694:     if ( $env{'form.selectpage'} eq '' ||
                   5695: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5696: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5697: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5698: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5699: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5700: 	} 
1.257     albertel 5701: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5702: 	    $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 5703: 	} 
1.257     albertel 5704: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5705: 	    $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 5706: 	} 
                   5707:     } else {
1.265     www      5708: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5709: 	$r->print(<<STUFF);
1.203     albertel 5710: $warning
1.265     www      5711: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5712: <input type="hidden" name="command" value="scantron_validate" />
                   5713: STUFF
1.237     albertel 5714:     }
1.352     albertel 5715:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5716:     return '';
                   5717: }
                   5718: 
1.423     albertel 5719: =pod
                   5720: 
                   5721: =item scantron_form_start
                   5722: 
1.424     albertel 5723:     html hidden input for remembering all selected grading options
                   5724: 
1.423     albertel 5725: =cut
                   5726: 
1.203     albertel 5727: sub scantron_form_start {
                   5728:     my ($max_bubble)=@_;
                   5729:     my $result= <<SCANTRONFORM;
                   5730: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5731:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5732:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5733:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5734:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5735:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5736:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5737:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5738:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5739:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5740: SCANTRONFORM
1.447     foxr     5741: 
                   5742:   my $line = 0;
                   5743:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448     foxr     5744: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5745:        my $chunk =
                   5746: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5747:        $chunk .=
                   5748: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5749:        $result .= $chunk;
                   5750:        $line++;
                   5751:    }
1.203     albertel 5752:     return $result;
                   5753: }
                   5754: 
1.423     albertel 5755: =pod
                   5756: 
                   5757: =item scantron_validate_file
                   5758: 
1.424     albertel 5759:     Dispatch routine for doing validation of a bubble sheet data file.
                   5760: 
                   5761:     Also processes any necessary information resets that need to
                   5762:     occur before validation begins (ignore previous corrections,
                   5763:     restarting the skipped records processing)
                   5764: 
1.423     albertel 5765: =cut
                   5766: 
1.157     albertel 5767: sub scantron_validate_file {
                   5768:     my ($r) = @_;
1.324     albertel 5769:     my ($symb)=&get_symb($r);
1.157     albertel 5770:     if (!$symb) {return '';}
1.324     albertel 5771:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5772:     
                   5773:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5774:     # them when doing the corrections reset
1.257     albertel 5775:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5776: 	&reset_skipping_status();
                   5777:     }
1.257     albertel 5778:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5779: 	&remember_current_skipped();
1.257     albertel 5780: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5781:     }
                   5782: 
1.257     albertel 5783:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5784: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5785: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5786: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5787: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5788:     }
1.200     albertel 5789: 
1.257     albertel 5790:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5791: 	&scantron_process_corrections($r);
                   5792:     }
1.424     albertel 5793:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5794:     #get the student pick code ready
                   5795:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5796:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5797:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5798:     $r->print($result);
                   5799:     
1.334     albertel 5800:     my @validate_phases=( 'sequence',
                   5801: 			  'ID',
1.157     albertel 5802: 			  'CODE',
                   5803: 			  'doublebubble',
                   5804: 			  'missingbubbles');
1.257     albertel 5805:     if (!$env{'form.validatepass'}) {
                   5806: 	$env{'form.validatepass'} = 0;
1.157     albertel 5807:     }
1.257     albertel 5808:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5809: 
1.448     foxr     5810:     &Apache::lonnet::logthis("Phase: $currentphase");
                   5811: 
1.157     albertel 5812:     my $stop=0;
                   5813:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5814: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5815: 	$r->rflush();
                   5816: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5817: 	{
                   5818: 	    no strict 'refs';
                   5819: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5820: 	}
                   5821:     }
                   5822:     if (!$stop) {
1.203     albertel 5823: 	my $warning=&scantron_warning_screen('Start Grading');
                   5824: 	$r->print(<<STUFF);
                   5825: Validation process complete.<br />
                   5826: $warning
                   5827: <input type="submit" name="submit" value="Start Grading" />
                   5828: <input type="hidden" name="command" value="scantron_process" />
                   5829: STUFF
                   5830: 
1.157     albertel 5831:     } else {
                   5832: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5833: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5834:     }
                   5835:     if ($stop) {
1.334     albertel 5836: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5837: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5838: 	    $r->print(' this error <br />');
                   5839: 
                   5840: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5841: 	} else {
                   5842: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5843: 	    $r->print(' using corrected info <br />');
                   5844: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5845: 	    $r->print(" this scanline saving it for later.");
                   5846: 	}
1.157     albertel 5847:     }
1.352     albertel 5848:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5849:     return '';
                   5850: }
                   5851: 
1.423     albertel 5852: 
                   5853: =pod
                   5854: 
                   5855: =item scantron_remove_file
                   5856: 
1.424     albertel 5857:    Removes the requested bubble sheet data file, makes sure that
                   5858:    scantron_original_<filename> is never removed
                   5859: 
                   5860: 
1.423     albertel 5861: =cut
                   5862: 
1.200     albertel 5863: sub scantron_remove_file {
1.192     albertel 5864:     my ($which)=@_;
1.257     albertel 5865:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5866:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5867:     my $file='scantron_';
1.200     albertel 5868:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5869: 	$file.=$which.'_';
1.192     albertel 5870:     } else {
                   5871: 	return 'refused';
                   5872:     }
1.257     albertel 5873:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5874:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5875: }
                   5876: 
1.423     albertel 5877: 
                   5878: =pod
                   5879: 
                   5880: =item scantron_remove_scan_data
                   5881: 
1.424     albertel 5882:    Removes all scan_data correction for the requested bubble sheet
                   5883:    data file.  (In the case that both the are doing skipped records we need
                   5884:    to remember the old skipped lines for the time being so that element
                   5885:    persists for a while.)
                   5886: 
1.423     albertel 5887: =cut
                   5888: 
1.200     albertel 5889: sub scantron_remove_scan_data {
1.257     albertel 5890:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5891:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5892:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5893:     my @todelete;
1.257     albertel 5894:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5895:     foreach my $key (@keys) {
                   5896: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5897: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5898: 		$key=~/remember_skipping/) {
                   5899: 		next;
                   5900: 	    }
1.192     albertel 5901: 	    push(@todelete,$key);
                   5902: 	}
                   5903:     }
1.200     albertel 5904:     my $result;
1.192     albertel 5905:     if (@todelete) {
1.200     albertel 5906: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5907:     }
                   5908:     return $result;
                   5909: }
                   5910: 
1.423     albertel 5911: 
                   5912: =pod
                   5913: 
                   5914: =item scantron_getfile
                   5915: 
1.424     albertel 5916:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5917:     the scan_data hash
                   5918:   
                   5919:   Arguments:
                   5920:     None
                   5921: 
                   5922:   Returns:
                   5923:     2 hash references
                   5924: 
                   5925:      - first one has 
                   5926:          orig      -
                   5927:          corrected -
                   5928:          skipped   -  each of which points to an array ref of the specified
                   5929:                       file broken up into individual lines
                   5930:          count     - number of scanlines
                   5931:  
                   5932:      - second is the scan_data hash possible keys are
1.425     albertel 5933:        ($number refers to scanline numbered $number and thus the key affects
                   5934:         only that scanline
                   5935:         $bubline refers to the specific bubble line element and the aspects
                   5936:         refers to that specific bubble line element)
                   5937: 
                   5938:        $number.user - username:domain to use
                   5939:        $number.CODE_ignore_dup 
                   5940:                     - ignore the duplicate CODE error 
                   5941:        $number.useCODE
                   5942:                     - use the CODE in the scanline as is
                   5943:        $number.no_bubble.$bubline
                   5944:                     - it is valid that there is no bubbled in bubble
                   5945:                       at $number $bubline
                   5946:        remember_skipping
                   5947:                     - a frozen hash containing keys of $number and values
                   5948:                       of either 
                   5949:                         1 - we are on a 'do skipped records pass' and plan
                   5950:                             on processing this line
                   5951:                         2 - we are on a 'do skipped records pass' and this
                   5952:                             scanline has been marked to skip yet again
1.424     albertel 5953: 
1.423     albertel 5954: =cut
                   5955: 
1.157     albertel 5956: sub scantron_getfile {
1.200     albertel 5957:     #FIXME really would prefer a scantron directory
1.257     albertel 5958:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5960:     my $lines;
                   5961:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5962: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5963:     my %scanlines;
                   5964:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5965:     my $temp=$scanlines{'orig'};
                   5966:     $scanlines{'count'}=$#$temp;
                   5967: 
                   5968:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5969: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5970:     if ($lines eq '-1') {
                   5971: 	$scanlines{'corrected'}=[];
                   5972:     } else {
                   5973: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5974:     }
                   5975:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5976: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5977:     if ($lines eq '-1') {
                   5978: 	$scanlines{'skipped'}=[];
                   5979:     } else {
                   5980: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5981:     }
1.175     albertel 5982:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5983:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5984:     my %scan_data = @tmp;
                   5985:     return (\%scanlines,\%scan_data);
                   5986: }
                   5987: 
1.423     albertel 5988: =pod
                   5989: 
                   5990: =item lonnet_putfile
                   5991: 
1.424     albertel 5992:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5993: 
                   5994:  Arguments:
                   5995:    $contents - data to store
                   5996:    $filename - filename to store $contents into
                   5997: 
                   5998:  Returns:
                   5999:    result value from &Apache::lonnet::finishuserfileupload
                   6000: 
1.423     albertel 6001: =cut
                   6002: 
1.157     albertel 6003: sub lonnet_putfile {
                   6004:     my ($contents,$filename)=@_;
1.257     albertel 6005:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6006:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6007:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6008:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6009: 
                   6010: }
                   6011: 
1.423     albertel 6012: =pod
                   6013: 
                   6014: =item scantron_putfile
                   6015: 
1.424     albertel 6016:     Stores the current version of the bubble sheet data files, and the
                   6017:     scan_data hash. (Does not modify the original version only the
                   6018:     corrected and skipped versions.
                   6019: 
                   6020:  Arguments:
                   6021:     $scanlines - hash ref that looks like the first return value from
                   6022:                  &scantron_getfile()
                   6023:     $scan_data - hash ref that looks like the second return value from
                   6024:                  &scantron_getfile()
                   6025: 
1.423     albertel 6026: =cut
                   6027: 
1.157     albertel 6028: sub scantron_putfile {
                   6029:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6030:     #FIXME really would prefer a scantron directory
1.257     albertel 6031:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6033:     if ($scanlines) {
                   6034: 	my $prefix='scantron_';
1.157     albertel 6035: # no need to update orig, shouldn't change
                   6036: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6037: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6038: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6039: 			$prefix.'corrected_'.
1.257     albertel 6040: 			$env{'form.scantron_selectfile'});
1.200     albertel 6041: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6042: 			$prefix.'skipped_'.
1.257     albertel 6043: 			$env{'form.scantron_selectfile'});
1.200     albertel 6044:     }
1.175     albertel 6045:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6046: }
                   6047: 
1.423     albertel 6048: =pod
                   6049: 
                   6050: =item scantron_get_line
                   6051: 
1.424     albertel 6052:    Returns the correct version of the scanline
                   6053: 
                   6054:  Arguments:
                   6055:     $scanlines - hash ref that looks like the first return value from
                   6056:                  &scantron_getfile()
                   6057:     $scan_data - hash ref that looks like the second return value from
                   6058:                  &scantron_getfile()
                   6059:     $i         - number of the requested line (starts at 0)
                   6060: 
                   6061:  Returns:
                   6062:    A scanline, (either the original or the corrected one if it
                   6063:    exists), or undef if the requested scanline should be
                   6064:    skipped. (Either because it's an skipped scanline, or it's an
                   6065:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6066:    pass.
                   6067: 
1.423     albertel 6068: =cut
                   6069: 
1.157     albertel 6070: sub scantron_get_line {
1.200     albertel 6071:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6072:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6073:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6074:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6075:     return $scanlines->{'orig'}[$i]; 
                   6076: }
                   6077: 
1.423     albertel 6078: =pod
                   6079: 
                   6080: =item scantron_todo_count
                   6081: 
1.424     albertel 6082:     Counts the number of scanlines that need processing.
                   6083: 
                   6084:  Arguments:
                   6085:     $scanlines - hash ref that looks like the first return value from
                   6086:                  &scantron_getfile()
                   6087:     $scan_data - hash ref that looks like the second return value from
                   6088:                  &scantron_getfile()
                   6089: 
                   6090:  Returns:
                   6091:     $count - number of scanlines to process
                   6092: 
1.423     albertel 6093: =cut
                   6094: 
1.200     albertel 6095: sub get_todo_count {
                   6096:     my ($scanlines,$scan_data)=@_;
                   6097:     my $count=0;
                   6098:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6099: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6100: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6101: 	$count++;
                   6102:     }
                   6103:     return $count;
                   6104: }
                   6105: 
1.423     albertel 6106: =pod
                   6107: 
                   6108: =item scantron_put_line
                   6109: 
1.424     albertel 6110:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6111:     data file.
                   6112: 
                   6113:  Arguments:
                   6114:     $scanlines - hash ref that looks like the first return value from
                   6115:                  &scantron_getfile()
                   6116:     $scan_data - hash ref that looks like the second return value from
                   6117:                  &scantron_getfile()
                   6118:     $i         - line number to update
                   6119:     $newline   - contents of the updated scanline
                   6120:     $skip      - if true make the line for skipping and update the
                   6121:                  'skipped' file
                   6122: 
1.423     albertel 6123: =cut
                   6124: 
1.157     albertel 6125: sub scantron_put_line {
1.200     albertel 6126:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6127:     if ($skip) {
                   6128: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6129: 	&start_skipping($scan_data,$i);
1.157     albertel 6130: 	return;
                   6131:     }
                   6132:     $scanlines->{'corrected'}[$i]=$newline;
                   6133: }
                   6134: 
1.423     albertel 6135: =pod
                   6136: 
                   6137: =item scantron_clear_skip
                   6138: 
1.424     albertel 6139:    Remove a line from the 'skipped' file
                   6140: 
                   6141:  Arguments:
                   6142:     $scanlines - hash ref that looks like the first return value from
                   6143:                  &scantron_getfile()
                   6144:     $scan_data - hash ref that looks like the second return value from
                   6145:                  &scantron_getfile()
                   6146:     $i         - line number to update
                   6147: 
1.423     albertel 6148: =cut
                   6149: 
1.376     albertel 6150: sub scantron_clear_skip {
                   6151:     my ($scanlines,$scan_data,$i)=@_;
                   6152:     if (exists($scanlines->{'skipped'}[$i])) {
                   6153: 	undef($scanlines->{'skipped'}[$i]);
                   6154: 	return 1;
                   6155:     }
                   6156:     return 0;
                   6157: }
                   6158: 
1.423     albertel 6159: =pod
                   6160: 
                   6161: =item scantron_filter_not_exam
                   6162: 
1.424     albertel 6163:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6164:    filter out resources that are not marked as 'exam' mode
                   6165: 
1.423     albertel 6166: =cut
                   6167: 
1.334     albertel 6168: sub scantron_filter_not_exam {
                   6169:     my ($curres)=@_;
                   6170:     
                   6171:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6172: 	# if the user has asked to not have either hidden
                   6173: 	# or 'randomout' controlled resources to be graded
                   6174: 	# don't include them
                   6175: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6176: 	    && $curres->randomout) {
                   6177: 	    return 0;
                   6178: 	}
                   6179: 	return 1;
                   6180:     }
                   6181:     return 0;
                   6182: }
                   6183: 
1.423     albertel 6184: =pod
                   6185: 
                   6186: =item scantron_validate_sequence
                   6187: 
1.424     albertel 6188:     Validates the selected sequence, checking for resource that are
                   6189:     not set to exam mode.
                   6190: 
1.423     albertel 6191: =cut
                   6192: 
1.334     albertel 6193: sub scantron_validate_sequence {
                   6194:     my ($r,$currentphase) = @_;
                   6195: 
                   6196:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6197:     my (undef,undef,$sequence)=
                   6198: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6199: 
                   6200:     my $map=$navmap->getResourceByUrl($sequence);
                   6201: 
                   6202:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6203:                                     value="ignore" />');
                   6204:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6205: 	my @resources=
                   6206: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6207: 	if (@resources) {
1.357     banghart 6208: 	    $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 6209: 	    return (1,$currentphase);
                   6210: 	}
                   6211:     }
                   6212: 
                   6213:     return (0,$currentphase+1);
                   6214: }
                   6215: 
1.423     albertel 6216: =pod
                   6217: 
                   6218: =item scantron_validate_ID
                   6219: 
1.424     albertel 6220:    Validates all scanlines in the selected file to not have any
                   6221:    invalid or underspecified student IDs
                   6222: 
1.423     albertel 6223: =cut
                   6224: 
1.157     albertel 6225: sub scantron_validate_ID {
                   6226:     my ($r,$currentphase) = @_;
                   6227:     
                   6228:     #get student info
                   6229:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6230:     my %idmap=&username_to_idmap($classlist);
                   6231: 
                   6232:     #get scantron line setup
1.257     albertel 6233:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6234:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6235:     
                   6236:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6237: 
                   6238:     my %found=('ids'=>{},'usernames'=>{});
                   6239:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6240: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6241: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6242: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6243: 						 $scan_data);
                   6244: 	my $id=$$scan_record{'scantron.ID'};
                   6245: 	my $found;
                   6246: 	foreach my $checkid (keys(%idmap)) {
                   6247: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6248: 	}
                   6249: 	if ($found) {
                   6250: 	    my $username=$idmap{$found};
                   6251: 	    if ($found{'ids'}{$found}) {
                   6252: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6253: 					 $line,'duplicateID',$found);
1.194     albertel 6254: 		return(1,$currentphase);
1.157     albertel 6255: 	    } elsif ($found{'usernames'}{$username}) {
                   6256: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6257: 					 $line,'duplicateID',$username);
1.194     albertel 6258: 		return(1,$currentphase);
1.157     albertel 6259: 	    }
1.186     albertel 6260: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6261: 	    $found{'ids'}{$found}++;
                   6262: 	    $found{'usernames'}{$username}++;
                   6263: 	} else {
                   6264: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6265: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6266: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6267: 		    &scantron_get_correction($r,$i,$scan_record,
                   6268: 					     \%scantron_config,
                   6269: 					     $line,'duplicateID',$username);
1.194     albertel 6270: 		    return(1,$currentphase);
1.157     albertel 6271: 		} elsif (!defined($username)) {
                   6272: 		    &scantron_get_correction($r,$i,$scan_record,
                   6273: 					     \%scantron_config,
                   6274: 					     $line,'incorrectID');
1.194     albertel 6275: 		    return(1,$currentphase);
1.157     albertel 6276: 		}
                   6277: 		$found{'usernames'}{$username}++;
                   6278: 	    } else {
                   6279: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6280: 					 $line,'incorrectID');
1.194     albertel 6281: 		return(1,$currentphase);
1.157     albertel 6282: 	    }
                   6283: 	}
                   6284:     }
                   6285: 
                   6286:     return (0,$currentphase+1);
                   6287: }
                   6288: 
1.423     albertel 6289: =pod
                   6290: 
                   6291: =item scantron_get_correction
                   6292: 
1.424     albertel 6293:    Builds the interface screen to interact with the operator to fix a
                   6294:    specific error condition in a specific scanline
                   6295: 
                   6296:  Arguments:
                   6297:     $r           - Apache request object
                   6298:     $i           - number of the current scanline
                   6299:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6300:     $scan_config - hash ref as returned from &get_scantron_config()
                   6301:     $line        - full contents of the current scanline
                   6302:     $error       - error condition, valid values are
                   6303:                    'incorrectCODE', 'duplicateCODE',
                   6304:                    'doublebubble', 'missingbubble',
                   6305:                    'duplicateID', 'incorrectID'
                   6306:     $arg         - extra information needed
                   6307:        For errors:
                   6308:          - duplicateID   - paper number that this studentID was seen before on
                   6309:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6310:                            seen on before
                   6311:          - incorrectCODE - current incorrect CODE 
                   6312:          - doublebubble  - array ref of the bubble lines that have double
                   6313:                            bubble errors
                   6314:          - missingbubble - array ref of the bubble lines that have missing
                   6315:                            bubble errors
                   6316: 
1.423     albertel 6317: =cut
                   6318: 
1.157     albertel 6319: sub scantron_get_correction {
                   6320:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6321: 
                   6322: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6323: #to show both the current line and the previous one and allow skipping
                   6324: #the previous one or the current one
                   6325: 
1.161     albertel 6326:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6327:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6328: 	$r->print(" for PaperID <tt>".
                   6329: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6330:     } else {
                   6331: 	$r->print(" in scanline $i <pre>".
                   6332: 		  $line."</pre> \n");
                   6333:     }
1.242     albertel 6334:     my $message="<p>The ID on the form is  <tt>".
                   6335: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6336: 	"The name on the paper is ".
                   6337: 	$$scan_record{'scantron.LastName'}.",".
                   6338: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6339: 
1.157     albertel 6340:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6341:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6342:     if ($error =~ /ID$/) {
1.186     albertel 6343: 	if ($error eq 'incorrectID') {
1.157     albertel 6344: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6345: 	} elsif ($error eq 'duplicateID') {
                   6346: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6347: 	}
1.242     albertel 6348: 	$r->print($message);
1.157     albertel 6349: 	$r->print("<p>How should I handle this? <br /> \n");
                   6350: 	$r->print("\n<ul><li> ");
                   6351: 	#FIXME it would be nice if this sent back the user ID and
                   6352: 	#could do partial userID matches
                   6353: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6354: 				       'scantron_username','scantron_domain'));
                   6355: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6356: 	$r->print("\n@".
1.257     albertel 6357: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6358: 
                   6359: 	$r->print('</li>');
1.186     albertel 6360:     } elsif ($error =~ /CODE$/) {
                   6361: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6362: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6363: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6364: 	    $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 6365: 	}
1.224     albertel 6366: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6367: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6368: 	$r->print($message);
1.186     albertel 6369: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6370: 	$r->print("\n<br /> ");
1.194     albertel 6371: 	my $i=0;
1.273     albertel 6372: 	if ($error eq 'incorrectCODE' 
                   6373: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6374: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6375: 	    if ($closest > 0) {
                   6376: 		foreach my $testcode (@{$closest}) {
                   6377: 		    my $checked='';
1.401     albertel 6378: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6379: 		    $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' />");
                   6380: 		    $r->print("\n<br />");
                   6381: 		    $i++;
                   6382: 		}
1.194     albertel 6383: 	    }
                   6384: 	}
1.273     albertel 6385: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6386: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6387: 	    $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>");
                   6388: 	    $r->print("\n<br />");
                   6389: 	}
1.194     albertel 6390: 
1.188     albertel 6391: 	$r->print(<<ENDSCRIPT);
                   6392: <script type="text/javascript">
                   6393: function change_radio(field) {
1.190     albertel 6394:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6395:     var i;
                   6396:     for (i=0;i<slct.length;i++) {
                   6397:         if (slct[i].value==field) { slct[i].checked=true; }
                   6398:     }
                   6399: }
                   6400: </script>
                   6401: ENDSCRIPT
1.187     albertel 6402: 	my $href="/adm/pickcode?".
1.359     www      6403: 	   "form=".&escape("scantronupload").
                   6404: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6405: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6406: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6407: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6408: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6409: 	    $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')\" />");
                   6410: 	    $r->print("\n<br />");
                   6411: 	}
1.272     albertel 6412: 	$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 6413: 	$r->print("\n<br /><br />");
1.157     albertel 6414:     } elsif ($error eq 'doublebubble') {
                   6415: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6416: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6417: 		  join(',',@{$arg}).'" />');
1.242     albertel 6418: 	$r->print($message);
1.157     albertel 6419: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6420: 	foreach my $question (@{$arg}) {
1.447     foxr     6421: 
                   6422: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6423: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6424: 				      split('',$selected));
1.157     albertel 6425: 	}
                   6426:     } elsif ($error eq 'missingbubble') {
                   6427: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6428: 	$r->print($message);
1.157     albertel 6429: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6430: 	$r->print("Some questions have no scanned bubbles\n");
                   6431: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6432: 		  join(',',@{$arg}).'" />');
                   6433: 	foreach my $question (@{$arg}) {
1.448     foxr     6434: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6435: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6436: 	}
                   6437:     } else {
                   6438: 	$r->print("\n<ul>");
                   6439:     }
                   6440:     $r->print("\n</li></ul>");
                   6441: 
                   6442: }
1.423     albertel 6443: 
                   6444: =pod
                   6445: 
                   6446: =item scantron_bubble_selector
                   6447:   
                   6448:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6449:    possibly showing the existing the selected bubbles if known
1.423     albertel 6450: 
                   6451:  Arguments:
                   6452:     $r           - Apache request object
                   6453:     $scan_config - hash from &get_scantron_config()
                   6454:     $quest       - number of the bubble line to make a corrector for
                   6455:     $selected    - array of letters of previously selected bubbles
                   6456: 
                   6457: =cut
                   6458: 
1.157     albertel 6459: sub scantron_bubble_selector {
1.447     foxr     6460:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6461:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6462: 
                   6463:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6464: 
                   6465: 
1.274     albertel 6466:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6467: 
1.448     foxr     6468:     my $response = $quest-1;
                   6469:     my $lines = $bubble_lines_per_response{$response};
                   6470:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6471: 
1.422     foxr     6472:     my $total_lines = $lines*2;
1.157     albertel 6473:     my @alphabet=('A'..'Z');
1.422     foxr     6474:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6475: 
                   6476:     for (my $l = 0; $l < $lines; $l++) {
                   6477: 	if ($l != 0) {
                   6478: 	    $r->print('<tr>');
                   6479: 	}
                   6480: 
                   6481: 	# FIXME:  This loop probably has to be considerably more clever for
                   6482: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6483: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6484: 
                   6485: 	for (my $i=0;$i<$max;$i++) {
                   6486: 	    $r->print("\n".'<td align="center">');
                   6487: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6488: 		$r->print('X'); 
                   6489: 		shift(@selected) ;
                   6490: 	    } else { 
                   6491: 		$r->print('&nbsp;'); 
                   6492: 	    }
                   6493: 	    $r->print('</td>');
                   6494: 	    
                   6495: 	}
                   6496: 
                   6497: 	if ($l == 0) {
                   6498: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6499: 
                   6500: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6501: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6502: 	
                   6503: 	}
                   6504: 
                   6505: 	$r->print('</tr><tr>');
                   6506: 
                   6507: 	# FIXME: This may have to be a bit more clever for
                   6508: 	#        multiline questions (different values e.g..).
                   6509: 
                   6510: 	for (my $i=0;$i<$max;$i++) {
                   6511: 	    $r->print("\n".
                   6512: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6513: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6514: 	}
                   6515: 	$r->print('</tr>');
                   6516: 
                   6517: 	    
1.157     albertel 6518:     }
1.422     foxr     6519:     $r->print('</table>');
1.157     albertel 6520: }
                   6521: 
1.423     albertel 6522: =pod
                   6523: 
                   6524: =item num_matches
                   6525: 
1.424     albertel 6526:    Counts the number of characters that are the same between the two arguments.
                   6527: 
                   6528:  Arguments:
                   6529:    $orig - CODE from the scanline
                   6530:    $code - CODE to match against
                   6531: 
                   6532:  Returns:
                   6533:    $count - integer count of the number of same characters between the
                   6534:             two arguments
                   6535: 
1.423     albertel 6536: =cut
                   6537: 
1.194     albertel 6538: sub num_matches {
                   6539:     my ($orig,$code) = @_;
                   6540:     my @code=split(//,$code);
                   6541:     my @orig=split(//,$orig);
                   6542:     my $same=0;
                   6543:     for (my $i=0;$i<scalar(@code);$i++) {
                   6544: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6545:     }
                   6546:     return $same;
                   6547: }
                   6548: 
1.423     albertel 6549: =pod
                   6550: 
                   6551: =item scantron_get_closely_matching_CODEs
                   6552: 
1.424     albertel 6553:    Cycles through all CODEs and finds the set that has the greatest
                   6554:    number of same characters as the provided CODE
                   6555: 
                   6556:  Arguments:
                   6557:    $allcodes - hash ref returned by &get_codes()
                   6558:    $CODE     - CODE from the current scanline
                   6559: 
                   6560:  Returns:
                   6561:    2 element list
                   6562:     - first elements is number of how closely matching the best fit is 
                   6563:       (5 means best set has 5 matching characters)
                   6564:     - second element is an arrary ref containing the set of valid CODEs
                   6565:       that best fit the passed in CODE
                   6566: 
1.423     albertel 6567: =cut
                   6568: 
1.194     albertel 6569: sub scantron_get_closely_matching_CODEs {
                   6570:     my ($allcodes,$CODE)=@_;
                   6571:     my @CODEs;
                   6572:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6573: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6574:     }
                   6575: 
                   6576:     return ($#CODEs,$CODEs[-1]);
                   6577: }
                   6578: 
1.423     albertel 6579: =pod
                   6580: 
                   6581: =item get_codes
                   6582: 
1.424     albertel 6583:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6584:    set of remembered CODEs.
                   6585: 
                   6586:  Arguments:
                   6587:   $old_name - name of the set of remembered CODEs
                   6588:   $cdom     - domain of the course
                   6589:   $cnum     - internal course name
                   6590: 
                   6591:  Returns:
                   6592:   %allcodes - keys are the valid CODEs, values are all 1
                   6593: 
1.423     albertel 6594: =cut
                   6595: 
1.194     albertel 6596: sub get_codes {
1.280     foxr     6597:     my ($old_name, $cdom, $cnum) = @_;
                   6598:     if (!$old_name) {
                   6599: 	$old_name=$env{'form.scantron_CODElist'};
                   6600:     }
                   6601:     if (!$cdom) {
                   6602: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6603:     }
                   6604:     if (!$cnum) {
                   6605: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6606:     }
1.278     albertel 6607:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6608: 				    $cdom,$cnum);
                   6609:     my %allcodes;
                   6610:     if ($result{"type\0$old_name"} eq 'number') {
                   6611: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6612:     } else {
                   6613: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6614:     }
1.194     albertel 6615:     return %allcodes;
                   6616: }
                   6617: 
1.423     albertel 6618: =pod
                   6619: 
                   6620: =item scantron_validate_CODE
                   6621: 
1.424     albertel 6622:    Validates all scanlines in the selected file to not have any
                   6623:    invalid or underspecified CODEs and that none of the codes are
                   6624:    duplicated if this was requested.
                   6625: 
1.423     albertel 6626: =cut
                   6627: 
1.157     albertel 6628: sub scantron_validate_CODE {
                   6629:     my ($r,$currentphase) = @_;
1.257     albertel 6630:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6631:     if ($scantron_config{'CODElocation'} &&
                   6632: 	$scantron_config{'CODEstart'} &&
                   6633: 	$scantron_config{'CODElength'}) {
1.257     albertel 6634: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6635: 	    &FIXME_blow_up()
                   6636: 	}
                   6637:     } else {
                   6638: 	return (0,$currentphase+1);
                   6639:     }
                   6640:     
                   6641:     my %usedCODEs;
                   6642: 
1.194     albertel 6643:     my %allcodes=&get_codes();
1.186     albertel 6644: 
1.447     foxr     6645:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6646: 
1.186     albertel 6647:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6648:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6649: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6650: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6651: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6652: 						 $scan_data);
                   6653: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6654: 	my $error=0;
1.224     albertel 6655: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6656: 	    &scantron_get_correction($r,$i,$scan_record,
                   6657: 				     \%scantron_config,
                   6658: 				     $line,'incorrectCODE',\%allcodes);
                   6659: 	    return(1,$currentphase);
                   6660: 	}
1.221     albertel 6661: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6662: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6663: 	    &scantron_get_correction($r,$i,$scan_record,
                   6664: 				     \%scantron_config,
1.194     albertel 6665: 				     $line,'incorrectCODE',\%allcodes);
                   6666: 	    return(1,$currentphase);
1.186     albertel 6667: 	}
1.214     albertel 6668: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6669: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6670: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6671: 	    &scantron_get_correction($r,$i,$scan_record,
                   6672: 				     \%scantron_config,
1.194     albertel 6673: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6674: 	    return(1,$currentphase);
1.186     albertel 6675: 	}
1.194     albertel 6676: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6677:     }
1.157     albertel 6678:     return (0,$currentphase+1);
                   6679: }
                   6680: 
1.423     albertel 6681: =pod
                   6682: 
                   6683: =item scantron_validate_doublebubble
                   6684: 
1.424     albertel 6685:    Validates all scanlines in the selected file to not have any
                   6686:    bubble lines with multiple bubbles marked.
                   6687: 
1.423     albertel 6688: =cut
                   6689: 
1.157     albertel 6690: sub scantron_validate_doublebubble {
                   6691:     my ($r,$currentphase) = @_;
                   6692:     #get student info
                   6693:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6694:     my %idmap=&username_to_idmap($classlist);
                   6695: 
                   6696:     #get scantron line setup
1.257     albertel 6697:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6698:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6699: 
                   6700:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6701: 
1.157     albertel 6702:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6703: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6704: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6705: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6706: 						 $scan_data);
                   6707: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6708: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6709: 				 'doublebubble',
                   6710: 				 $$scan_record{'scantron.doubleerror'});
                   6711:     	return (1,$currentphase);
                   6712:     }
                   6713:     return (0,$currentphase+1);
                   6714: }
                   6715: 
1.423     albertel 6716: =pod
                   6717: 
                   6718: =item scantron_get_maxbubble
                   6719: 
1.424     albertel 6720:    Returns the maximum number of bubble lines that are expected to
                   6721:    occur. Does this by walking the selected sequence rendering the
                   6722:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6723:    for what the current value of the problem counter is.
                   6724: 
1.447     foxr     6725:    Caches the results to $env{'form.scantron_maxbubble'},
                   6726:    $env{'form.scantron.bubble_lines.n'} and 
                   6727:    $env{'form.scantron.first_bubble_line.n'}
                   6728:    which are the total number of bubble, lines, the number of bubble
                   6729:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6730: 
1.423     albertel 6731: =cut
                   6732: 
1.330     albertel 6733: sub scantron_get_maxbubble {    
1.448     foxr     6734:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6735:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6736: 	$env{'form.scantron_maxbubble'}) {
1.448     foxr     6737: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6738: 	&restore_bubble_lines();
1.257     albertel 6739: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6740:     }
1.448     foxr     6741:     &Apache::lonnet::logthis("computing");
1.330     albertel 6742: 
1.447     foxr     6743:     my (undef, undef, $sequence) =
1.257     albertel 6744: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6745: 
1.447     foxr     6746:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6747:     my $map=$navmap->getResourceByUrl($sequence);
                   6748:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6749: 
                   6750:     &Apache::lonxml::clear_problem_counter();
                   6751: 
1.435     foxr     6752:     my $uname       = $env{'form.student'};
                   6753:     my $udom        = $env{'form.userdom'};
                   6754:     my $cid         = $env{'request.course.id'};
                   6755:     my $total_lines = 0;
                   6756:     %bubble_lines_per_response = ();
1.447     foxr     6757:     %first_bubble_line         = ();
1.435     foxr     6758: 
1.447     foxr     6759:   
                   6760:     my $response_number = 0;
                   6761:     my $bubble_line     = 0;
1.191     albertel 6762:     foreach my $resource (@resources) {
1.435     foxr     6763: 	my $symb = $resource->symb();
1.447     foxr     6764: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6765: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6766: 					('symb' => $resource->symb()),
                   6767: 					('grade_target' => 'analyze'),
                   6768: 					('grade_courseid' => $cid),
                   6769: 					('grade_domain' => $udom),
                   6770: 					('grade_username' => $uname));
1.436     albertel 6771: 	my (undef, $an) =
1.435     foxr     6772: 	    split(/_HASH_REF__/,$result, 2);
                   6773: 
                   6774: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6775: 
                   6776: 
                   6777: 
                   6778: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6779: 	    my ($trash, $part) = split(/\./, $part_id);
                   6780: 
                   6781: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6782: 
                   6783: 	    # TODO - make this a persistent hash not an array.
                   6784: 
                   6785: 
                   6786: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6787: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6788: 	    $response_number++;
                   6789: 
                   6790: 	    $bubble_line +=  $lines;
                   6791: 	    $total_lines +=  $lines;
1.435     foxr     6792: 	}
                   6793: 
1.191     albertel 6794:     }
                   6795:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6796: 
                   6797:     &save_bubble_lines();
1.330     albertel 6798:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6799: 	$total_lines;
1.257     albertel 6800:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6801: }
                   6802: 
1.423     albertel 6803: =pod
                   6804: 
                   6805: =item scantron_validate_missingbubbles
                   6806: 
1.424     albertel 6807:    Validates all scanlines in the selected file to not have any
1.447     foxr     6808:     answers that don't have bubbles that have not been verified
                   6809:     to be bubble free.
1.424     albertel 6810: 
1.423     albertel 6811: =cut
                   6812: 
1.157     albertel 6813: sub scantron_validate_missingbubbles {
                   6814:     my ($r,$currentphase) = @_;
                   6815:     #get student info
                   6816:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6817:     my %idmap=&username_to_idmap($classlist);
                   6818: 
                   6819:     #get scantron line setup
1.257     albertel 6820:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6821:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6822:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6823:     if (!$max_bubble) { $max_bubble=2**31; }
                   6824:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6825: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6826: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6827: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6828: 						 $scan_data);
                   6829: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6830: 	my @to_correct;
                   6831: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6832: 	    if ($missing > $max_bubble) { next; }
                   6833: 	    push(@to_correct,$missing);
                   6834: 	}
                   6835: 	if (@to_correct) {
                   6836: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6837: 				     $line,'missingbubble',\@to_correct);
                   6838: 	    return (1,$currentphase);
                   6839: 	}
                   6840: 
                   6841:     }
                   6842:     return (0,$currentphase+1);
                   6843: }
                   6844: 
1.423     albertel 6845: =pod
                   6846: 
                   6847: =item scantron_process_students
                   6848: 
                   6849:    Routine that does the actual grading of the bubble sheet information.
                   6850: 
                   6851:    The parsed scanline hash is added to %env 
                   6852: 
                   6853:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6854:    foreach resource , with the form data of
                   6855: 
                   6856: 	'submitted'     =>'scantron' 
                   6857: 	'grade_target'  =>'grade',
                   6858: 	'grade_username'=> username of student
                   6859: 	'grade_domain'  => domain of student
                   6860: 	'grade_courseid'=> of course
                   6861: 	'grade_symb'    => symb of resource to grade
                   6862: 
                   6863:     This triggers a grading pass. The problem grading code takes care
                   6864:     of converting the bubbled letter information (now in %env) into a
                   6865:     valid submission.
                   6866: 
                   6867: =cut
                   6868: 
1.82      albertel 6869: sub scantron_process_students {
1.75      albertel 6870:     my ($r) = @_;
1.257     albertel 6871:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6872:     my ($symb)=&get_symb($r);
1.81      albertel 6873:     if (!$symb) {return '';}
1.324     albertel 6874:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6875: 
1.257     albertel 6876:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6877:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6878:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6879:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6880:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6881:     my $map=$navmap->getResourceByUrl($sequence);
                   6882:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6883: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6884:     my $result= <<SCANTRONFORM;
1.81      albertel 6885: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6886:   <input type="hidden" name="command" value="scantron_configphase" />
                   6887:   $default_form_data
                   6888: SCANTRONFORM
1.82      albertel 6889:     $r->print($result);
                   6890: 
                   6891:     my @delayqueue;
1.140     albertel 6892:     my %completedstudents;
                   6893:     
1.200     albertel 6894:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6895:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6896:  				    'Scantron Progress',$count,
1.195     albertel 6897: 				    'inline',undef,'scantronupload');
1.140     albertel 6898:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6899: 					  'Processing first student');
                   6900:     my $start=&Time::HiRes::time();
1.158     albertel 6901:     my $i=-1;
1.200     albertel 6902:     my ($uname,$udom,$started);
1.447     foxr     6903: 
                   6904:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6905: 
1.157     albertel 6906:     while ($i<$scanlines->{'count'}) {
                   6907:  	($uname,$udom)=('','');
                   6908:  	$i++;
1.200     albertel 6909:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6910:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6911: 	if ($started) {
                   6912: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6913: 						     'last student');
                   6914: 	}
                   6915: 	$started=1;
1.157     albertel 6916:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6917:  						 $scan_data);
                   6918:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6919:  					      \%idmap,$i)) {
                   6920:   	    &scantron_add_delay(\@delayqueue,$line,
                   6921:  				'Unable to find a student that matches',1);
                   6922:  	    next;
                   6923:   	}
                   6924:  	if (exists $completedstudents{$uname}) {
                   6925:  	    &scantron_add_delay(\@delayqueue,$line,
                   6926:  				'Student '.$uname.' has multiple sheets',2);
                   6927:  	    next;
                   6928:  	}
                   6929:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6930: 
                   6931: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6932:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6933: 
                   6934: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6935: 	    &scantron_putfile($scanlines,$scan_data);
                   6936: 	}
1.161     albertel 6937: 	
                   6938: 	my $i=0;
1.83      albertel 6939: 	foreach my $resource (@resources) {
1.85      albertel 6940: 	    $i++;
1.193     albertel 6941: 	    my %form=('submitted'     =>'scantron',
                   6942: 		      'grade_target'  =>'grade',
                   6943: 		      'grade_username'=>$uname,
                   6944: 		      'grade_domain'  =>$udom,
1.257     albertel 6945: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6946: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6947: 	    if (exists($scan_record->{'scantron.CODE'})
                   6948: 		&& 
                   6949: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6950: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6951: 	    } else {
                   6952: 		$form{'CODE'}='';
1.193     albertel 6953: 	    }
                   6954: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6955: 	    if ($result ne '') {
                   6956: 	    }
1.213     albertel 6957: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6958: 	}
1.140     albertel 6959: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6960: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6961:     } continue {
1.330     albertel 6962: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6963: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6964:     }
1.140     albertel 6965:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6966: #    my $lasttime = &Time::HiRes::time()-$start;
                   6967: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6968: 
1.200     albertel 6969:     $r->print("</form>");
1.324     albertel 6970:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6971:     return '';
1.75      albertel 6972: }
1.157     albertel 6973: 
1.423     albertel 6974: =pod
                   6975: 
                   6976: =item scantron_upload_scantron_data
                   6977: 
                   6978:     Creates the screen for adding a new bubble sheet data file to a course.
                   6979: 
                   6980: =cut
                   6981: 
1.157     albertel 6982: sub scantron_upload_scantron_data {
                   6983:     my ($r)=@_;
1.257     albertel 6984:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6985:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6986: 							  'domainid',
                   6987: 							  'coursename');
1.257     albertel 6988:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6989: 						   'domainid');
1.324     albertel 6990:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6991:     $r->print(<<UPLOAD);
                   6992: <script type="text/javascript" language="javascript">
                   6993:     function checkUpload(formname) {
                   6994: 	if (formname.upfile.value == "") {
                   6995: 	    alert("Please use the browse button to select a file from your local directory.");
                   6996: 	    return false;
                   6997: 	}
                   6998: 	formname.submit();
                   6999:     }
                   7000: </script>
                   7001: 
                   7002: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7003: $default_form_data
1.181     albertel 7004: <table>
                   7005: <tr><td>$select_link </td></tr>
                   7006: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7007: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7008: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7009: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7010: </table>
1.157     albertel 7011: <input name='command' value='scantronupload_save' type='hidden' />
                   7012: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7013: </form>
                   7014: UPLOAD
                   7015:     return '';
                   7016: }
                   7017: 
1.423     albertel 7018: =pod
                   7019: 
                   7020: =item scantron_upload_scantron_data_save
                   7021: 
                   7022:    Adds a provided bubble information data file to the course if user
                   7023:    has the correct privileges to do so.  
                   7024: 
                   7025: =cut
                   7026: 
1.157     albertel 7027: sub scantron_upload_scantron_data_save {
                   7028:     my($r)=@_;
1.324     albertel 7029:     my ($symb)=&get_symb($r,1);
1.182     albertel 7030:     my $doanotherupload=
                   7031: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7032: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7033: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7034: 	'</form>'."\n";
1.257     albertel 7035:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7036: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7037: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7038: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7039: 	if ($symb) {
1.324     albertel 7040: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7041: 	} else {
                   7042: 	    $r->print($doanotherupload);
                   7043: 	}
1.162     albertel 7044: 	return '';
                   7045:     }
1.257     albertel 7046:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7047:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7048:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7049:     #FIXME
                   7050:     #copied from lonnet::userfileupload()
                   7051:     #make that function able to target a specified course
                   7052:     # Replace Windows backslashes by forward slashes
                   7053:     $fname=~s/\\/\//g;
                   7054:     # Get rid of everything but the actual filename
                   7055:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7056:     # Replace spaces by underscores
                   7057:     $fname=~s/\s+/\_/g;
                   7058:     # Replace all other weird characters by nothing
                   7059:     $fname=~s/[^\w\.\-]//g;
                   7060:     # See if there is anything left
                   7061:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7062:     my $uploadedfile=$fname;
1.157     albertel 7063:     $fname='scantron_orig_'.$fname;
1.257     albertel 7064:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7065: 	$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 7066:     } else {
1.275     albertel 7067: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7068: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7069: 	    $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 7070: 	} else {
1.398     albertel 7071: 	    $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 7072: 	}
                   7073:     }
1.174     albertel 7074:     if ($symb) {
1.209     ng       7075: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7076:     } else {
1.182     albertel 7077: 	$r->print($doanotherupload);
1.174     albertel 7078:     }
1.157     albertel 7079:     return '';
                   7080: }
                   7081: 
1.423     albertel 7082: =pod
                   7083: 
                   7084: =item valid_file
                   7085: 
1.424     albertel 7086:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7087: 
                   7088: =cut
                   7089: 
1.202     albertel 7090: sub valid_file {
                   7091:     my ($requested_file)=@_;
                   7092:     foreach my $filename (sort(&scantron_filenames())) {
                   7093: 	if ($requested_file eq $filename) { return 1; }
                   7094:     }
                   7095:     return 0;
                   7096: }
                   7097: 
1.423     albertel 7098: =pod
                   7099: 
                   7100: =item scantron_download_scantron_data
                   7101: 
                   7102:    Shows a list of the three internal files (original, corrected,
                   7103:    skipped) for a specific bubble sheet data file that exists in the
                   7104:    course.
                   7105: 
                   7106: =cut
                   7107: 
1.202     albertel 7108: sub scantron_download_scantron_data {
                   7109:     my ($r)=@_;
1.324     albertel 7110:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7111:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7112:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7113:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7114:     if (! &valid_file($file)) {
                   7115: 	$r->print(<<ERROR);
                   7116: 	<p>
                   7117: 	    The requested file name was invalid.
                   7118:         </p>
                   7119: ERROR
1.324     albertel 7120: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7121: 	return;
                   7122:     }
                   7123:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7124:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7125:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7126:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7127:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7128:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7129:     $r->print(<<DOWNLOAD);
                   7130:     <p>
                   7131: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7132:     </p>
                   7133:     <p>
                   7134: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7135:     </p>
                   7136:     <p>
                   7137: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7138:     </p>
                   7139: DOWNLOAD
1.324     albertel 7140:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7141:     return '';
                   7142: }
1.157     albertel 7143: 
1.423     albertel 7144: =pod
                   7145: 
                   7146: =back
                   7147: 
                   7148: =cut
                   7149: 
1.75      albertel 7150: #-------- end of section for handling grading scantron forms -------
                   7151: #
                   7152: #-------------------------------------------------------------------
                   7153: 
1.72      ng       7154: #-------------------------- Menu interface -------------------------
                   7155: #
                   7156: #--- Show a Grading Menu button - Calls the next routine ---
                   7157: sub show_grading_menu_form {
1.324     albertel 7158:     my ($symb)=@_;
1.125     ng       7159:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7160: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7161: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7162: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7163: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7164: 	'</form>'."\n";
                   7165:     return $result;
                   7166: }
                   7167: 
1.77      ng       7168: # -- Retrieve choices for grading form
                   7169: sub savedState {
                   7170:     my %savedState = ();
1.257     albertel 7171:     if ($env{'form.saveState'}) {
                   7172: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7173: 	    my ($key,$value) = split(/=/,$_,2);
                   7174: 	    $savedState{$key} = $value;
                   7175: 	}
                   7176:     }
                   7177:     return \%savedState;
                   7178: }
1.76      ng       7179: 
1.443     banghart 7180: sub grading_menu {
                   7181:     my ($request) = @_;
                   7182:     my ($symb)=&get_symb($request);
                   7183:     if (!$symb) {return '';}
                   7184:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7185:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7186: 
                   7187:     #
                   7188:     # Define menu data
1.444     banghart 7189:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7190:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7191:     $request->print($table);
1.443     banghart 7192:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7193:                   'handgrade'=>$hdgrade,
                   7194:                   'probTitle'=>$probTitle,
                   7195:                   'command'=>'submit_options',
                   7196:                   'saveState'=>"",
                   7197:                   'gradingMenu'=>1,
                   7198:                   'showgrading'=>"yes");
                   7199:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7200:     my @menu = ({ url => $url,
                   7201:                      name => &mt('Manual Grading/View Submissions'),
                   7202:                      short_description => 
                   7203:     &mt('Start the process of hand grading submissions.'),
                   7204:                  });
                   7205:     $fields{'command'} = 'csvform';
                   7206:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7207:     push (@menu, { url => $url,
                   7208:                    name => &mt('Upload Scores'),
                   7209:                    short_description => 
                   7210:             &mt('Specify a file containing the class scores for current resource.')});
                   7211:     $fields{'command'} = 'processclicker';
                   7212:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7213:     push (@menu, { url => $url,
                   7214:                    name => &mt('Process Clicker'),
                   7215:                    short_description => 
                   7216:             &mt('Specify a file containing the clicker information for this resource.')});
                   7217:     $fields{'command'} = 'scantron_selectphase';
                   7218:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7219:     push (@menu, { url => $url,
                   7220:                    name => &mt('Grade Scantron Forms'),
                   7221:                    short_description => 
                   7222:             &mt('')});
                   7223:     $fields{'command'} = 'verify';
                   7224:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7225:     push (@menu, { url => "",
                   7226:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7227:                    name => &mt('Verify Receipt'),
                   7228:                    short_description => 
                   7229:             &mt('')});
                   7230:     $fields{'command'} = 'manage';
                   7231:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7232:     push (@menu, { url => $url,
                   7233:                    name => &mt('Manage Access Times'),
                   7234:                    short_description => 
                   7235:             &mt('')});
                   7236:     $fields{'command'} = 'view';
                   7237:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7238:     push (@menu, { url => $url,
                   7239:                    name => &mt('View Saved CODEs'),
                   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.447     foxr     8033: 
1.434     albertel 8034:     &reset_caches();
1.257     albertel 8035:     if ($env{'browser.mathml'}) {
1.141     www      8036: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8037:     } else {
1.141     www      8038: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8039:     }
                   8040:     $request->send_http_header;
1.44      ng       8041:     return '' if $request->header_only;
1.41      ng       8042:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8043:     my $symb=&get_symb($request,1);
1.160     albertel 8044:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8045:     my $command=$commands[0];
1.447     foxr     8046: 
1.160     albertel 8047:     if ($#commands > 0) {
                   8048: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8049:     }
1.447     foxr     8050: 
                   8051: 
1.353     albertel 8052:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8053:     if ($symb eq '' && $command eq '') {
1.257     albertel 8054: 	if ($env{'user.adv'}) {
                   8055: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8056: 		($env{'form.codethree'})) {
                   8057: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8058: 		    $env{'form.codethree'};
1.41      ng       8059: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8060: 		    &Apache::lonnet::checkin($token);
                   8061: 		if ($tsymb) {
1.137     albertel 8062: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8063: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8064: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8065: 					  ('grade_username' => $tuname,
                   8066: 					   'grade_domain' => $tudom,
                   8067: 					   'grade_courseid' => $tcrsid,
                   8068: 					   'grade_symb' => $tsymb)));
1.41      ng       8069: 		    } else {
1.45      ng       8070: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8071: 		    }
1.41      ng       8072: 		} else {
1.45      ng       8073: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8074: 		}
1.14      www      8075: 	    } else {
1.41      ng       8076: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8077: 	    }
                   8078: 	}
                   8079:     } else {
1.285     albertel 8080: 	&init_perm();
1.104     albertel 8081: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8082: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8083: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8084: 	    &pickStudentPage($request);
1.103     albertel 8085: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8086: 	    &displayPage($request);
1.104     albertel 8087: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8088: 	    &updateGradeByPage($request);
1.104     albertel 8089: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8090: 	    &processGroup($request);
1.104     albertel 8091: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8092: 	    $request->print(&grading_menu($request));
                   8093: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8094: 	    $request->print(&submit_options($request));
1.104     albertel 8095: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8096: 	    $request->print(&viewgrades($request));
1.104     albertel 8097: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8098: 	    $request->print(&processHandGrade($request));
1.106     albertel 8099: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8100: 	    $request->print(&editgrades($request));
1.106     albertel 8101: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8102: 	    $request->print(&verifyreceipt($request));
1.400     www      8103:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8104:             $request->print(&process_clicker($request));
                   8105:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8106:             $request->print(&process_clicker_file($request));
1.414     www      8107:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8108:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8109: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8110: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8111: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8112: 	    $request->print(&csvupload($request));
1.106     albertel 8113: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8114: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8115: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8116: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8117: 		$request->print(&csvuploadoptions($request));
1.41      ng       8118: 	    } else {
1.257     albertel 8119: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8120: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8121: 		} else {
1.257     albertel 8122: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8123: 		}
                   8124: 		$request->print(&csvuploadmap($request));
                   8125: 	    }
1.246     albertel 8126: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8127: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8128: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8129: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8130: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8131:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8132:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8133: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8134: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8135: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8136: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8137:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8138:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8139: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8140:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8141:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8142:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8143: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8144:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8145:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8146: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8147:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8148: 	} elsif ($command) {
1.157     albertel 8149: 	    $request->print("Access Denied ($command)");
1.26      albertel 8150: 	}
1.2       albertel 8151:     }
1.353     albertel 8152:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8153:     &reset_caches();
1.44      ng       8154:     return '';
                   8155: }
                   8156: 
1.1       albertel 8157: 1;
                   8158: 
1.13      albertel 8159: __END__;

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