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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.448   ! foxr        4: # $Id: grades.pm,v 1.447 2007/10/09 09:16:04 foxr Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
1.447     foxr       50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       51:                                    # index is "symb.part_id"
                     52: 
1.447     foxr       53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     54: 
                     55: # Save and restore the bubble lines array to the form env.
                     56: 
                     57: 
                     58: sub save_bubble_lines {
1.448   ! foxr       59:     &Apache::lonnet::logthis("Saving bubble_lines...");
1.447     foxr       60:     foreach my $line (keys(%bubble_lines_per_response)) {
1.448   ! foxr       61: 	&Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
1.447     foxr       62: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     63: 	$env{"form.scantron.first_bubble_line.$line"} =
                     64: 	    $first_bubble_line{$line};
                     65:     }
                     66: }
                     67: 
                     68: 
                     69: sub restore_bubble_lines {
                     70:     my $line = 0;
                     71:     %bubble_lines_per_response = ();
                     72:     while ($env{"form.scantron.bubblelines.$line"}) {
                     73: 	my $value = $env{"form.scantron.bubblelines.$line"};
1.448   ! foxr       74: 	&Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
1.447     foxr       75: 	$bubble_lines_per_response{$line} = $value;
                     76: 	$first_bubble_line{$line}  =
                     77: 	    $env{"form.scantron.first_bubble_line.$line"};
                     78: 	$line++;
                     79:     }
                     80: 
                     81: }
                     82: 
                     83: #  Given the parsed scanline, get the response for 
                     84: #  'answer' number n:
                     85: 
                     86: sub get_response_bubbles {
                     87:     my ($parsed_line, $response)  = @_;
                     88: 
                     89:     my $bubble_line = $first_bubble_line{$response};
1.448   ! foxr       90:     my $bubble_lines= $bubble_lines_per_response{$response};
1.447     foxr       91:     my $selected = "";
                     92: 
                     93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                     94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
                     95: 	$bubble_line++;
                     96:     }
                     97:     return $selected;
                     98: }
                     99: 
1.1       albertel  100: 
1.68      ng        101: # ----- These first few routines are general use routines.----
1.447     foxr      102: 
                    103: # Return the number of occurences of a pattern in a string.
                    104: 
                    105: sub occurence_count {
                    106:     my ($string, $pattern) = @_;
                    107: 
                    108:     my @matches = ($string =~ /$pattern/g);
                    109: 
                    110:     return scalar(@matches);
                    111: }
                    112: 
                    113: 
                    114: # Take a string known to have digits and convert all the
                    115: # digits into letters in the range J,A..I.
                    116: 
                    117: sub digits_to_letters {
                    118:     my ($input) = @_;
                    119: 
                    120:     my @alphabet = ('J', 'A'..'I');
                    121: 
                    122:     my @input    = split(//, $input);
                    123:     my $output ='';
                    124:     for (my $i = 0; $i < scalar(@input); $i++) {
                    125: 	if ($input[$i] =~ /\d/) {
                    126: 	    $output .= $alphabet[$input[$i]];
                    127: 	} else {
                    128: 	    $output .= $input[$i];
                    129: 	}
                    130:     }
                    131:     return $output;
                    132: }
                    133: 
1.44      ng        134: #
1.146     albertel  135: # --- Retrieve the parts from the metadata file.---
1.44      ng        136: sub getpartlist {
1.324     albertel  137:     my ($symb) = @_;
1.439     albertel  138: 
                    139:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    140:     my $res      = $navmap->getBySymb($symb);
                    141:     my $partlist = $res->parts();
                    142:     my $url      = $res->src();
                    143:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    144: 
1.146     albertel  145:     my @stores;
1.439     albertel  146:     foreach my $part (@{ $partlist }) {
1.146     albertel  147: 	foreach my $key (@metakeys) {
                    148: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    149: 	}
                    150:     }
                    151:     return @stores;
1.2       albertel  152: }
                    153: 
1.44      ng        154: # --- Get the symbolic name of a problem and the url
1.324     albertel  155: sub get_symb {
1.173     albertel  156:     my ($request,$silent) = @_;
1.257     albertel  157:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  159:     if ($symb eq '') { 
                    160: 	if (!$silent) {
                    161: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    162: 	    return ();
                    163: 	}
                    164:     }
1.418     albertel  165:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  166:     return ($symb);
1.32      ng        167: }
                    168: 
1.129     ng        169: #--- Format fullname, username:domain if different for display
                    170: #--- Use anywhere where the student names are listed
                    171: sub nameUserString {
                    172:     my ($type,$fullname,$uname,$udom) = @_;
                    173:     if ($type eq 'header') {
1.398     albertel  174: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        175:     } else {
1.398     albertel  176: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    177: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        178:     }
                    179: }
                    180: 
1.44      ng        181: #--- Get the partlist and the response type for a given problem. ---
                    182: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        183: sub response_type {
1.324     albertel  184:     my ($symb) = shift;
1.377     albertel  185: 
                    186:     my $navmap = Apache::lonnavmaps::navmap->new();
                    187:     my $res = $navmap->getBySymb($symb);
                    188:     my $partlist = $res->parts();
1.392     albertel  189:     my %vPart = 
                    190: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  191:     my (%response_types,%handgrade);
                    192:     foreach my $part (@{ $partlist }) {
1.392     albertel  193: 	next if (%vPart && !exists($vPart{$part}));
                    194: 
1.377     albertel  195: 	my @types = $res->responseType($part);
                    196: 	my @ids = $res->responseIds($part);
                    197: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    198: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    199: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    200: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    201: 				     '.handgrade',$symb);
1.41      ng        202: 	}
                    203:     }
1.377     albertel  204:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        205: }
                    206: 
1.375     albertel  207: sub flatten_responseType {
                    208:     my ($responseType) = @_;
                    209:     my @part_response_id =
                    210: 	map { 
                    211: 	    my $part = $_;
                    212: 	    map {
                    213: 		[$part,$_]
                    214: 		} sort(keys(%{ $responseType->{$part} }));
                    215: 	} sort(keys(%$responseType));
                    216:     return @part_response_id;
                    217: }
                    218: 
1.207     albertel  219: sub get_display_part {
1.324     albertel  220:     my ($partID,$symb)=@_;
1.207     albertel  221:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    222:     if (defined($display) and $display ne '') {
1.398     albertel  223: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  224:     } else {
                    225: 	$display=$partID;
                    226:     }
                    227:     return $display;
                    228: }
1.269     raeburn   229: 
1.118     ng        230: #--- Show resource title
                    231: #--- and parts and response type
                    232: sub showResourceInfo {
1.324     albertel  233:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  234:     my $col=3;
                    235:     if ($checkboxes) { $col=4; }
1.398     albertel  236:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    237:     $result .='<table border="0">';
1.324     albertel  238:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        239:     my %resptype = ();
1.122     ng        240:     my $hdgrade='no';
1.154     albertel  241:     my %partsseen;
1.375     albertel  242:     foreach my $partID (sort keys(%$responseType)) {
                    243: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    244: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    245: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    246: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    247: 	    $result.='<tr>';
                    248: 	    if ($checkboxes) {
                    249: 		if (exists($partsseen{$partID})) {
                    250: 		    $result.="<td>&nbsp;</td>";
                    251: 		} else {
1.401     albertel  252: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  253: 		}
                    254: 		$partsseen{$partID}=1;
1.154     albertel  255: 	    }
1.375     albertel  256: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  257: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    258: 		$resID.'</span></td>'.
1.375     albertel  259: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    260: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  261: 	}
1.118     ng        262:     }
                    263:     $result.='</table>'."\n";
1.147     albertel  264:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        265: }
                    266: 
1.434     albertel  267: sub reset_caches {
                    268:     &reset_analyze_cache();
                    269:     &reset_perm();
                    270: }
                    271: 
                    272: {
                    273:     my %analyze_cache;
1.148     albertel  274: 
1.434     albertel  275:     sub reset_analyze_cache {
                    276: 	undef(%analyze_cache);
                    277:     }
                    278: 
                    279:     sub get_analyze {
                    280: 	my ($symb,$uname,$udom)=@_;
                    281: 	my $key = "$symb\0$uname\0$udom";
                    282: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    283: 
                    284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    285: 	$url=&Apache::lonnet::clutter($url);
                    286: 	my $subresult=&Apache::lonnet::ssi($url,
                    287: 					   ('grade_target' => 'analyze'),
                    288: 					   ('grade_domain' => $udom),
                    289: 					   ('grade_symb' => $symb),
                    290: 					   ('grade_courseid' => 
                    291: 					    $env{'request.course.id'}),
                    292: 					   ('grade_username' => $uname));
                    293: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    294: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    295: 	return $analyze_cache{$key} = \%analyze;
                    296:     }
                    297: 
                    298:     sub get_order {
                    299: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    300: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    301: 	return $analyze->{"$partid.$respid.shown"};
                    302:     }
                    303: 
                    304:     sub get_radiobutton_correct_foil {
                    305: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    306: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    307: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    308: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    309: 		return $foil;
                    310: 	    }
                    311: 	}
                    312:     }
1.148     albertel  313: }
1.434     albertel  314: 
1.118     ng        315: #--- Clean response type for display
1.335     albertel  316: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    317: #        response types only.
1.118     ng        318: sub cleanRecord {
1.336     albertel  319:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    320: 	$uname,$udom) = @_;
1.398     albertel  321:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  322:     if ($response =~ /^(option|rank)$/) {
                    323: 	my %answer=&Apache::lonnet::str2hash($answer);
                    324: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    325: 	my ($toprow,$bottomrow);
                    326: 	foreach my $foil (@$order) {
                    327: 	    if ($grading{$foil} == 1) {
                    328: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    329: 	    } else {
                    330: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    331: 	    }
1.398     albertel  332: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  333: 	}
                    334: 	return '<blockquote><table border="1">'.
                    335: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  336: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  337: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    338:     } elsif ($response eq 'match') {
                    339: 	my %answer=&Apache::lonnet::str2hash($answer);
                    340: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    341: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    342: 	my ($toprow,$middlerow,$bottomrow);
                    343: 	foreach my $foil (@$order) {
                    344: 	    my $item=shift(@items);
                    345: 	    if ($grading{$foil} == 1) {
                    346: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  347: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  348: 	    } else {
                    349: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  350: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  351: 	    }
1.398     albertel  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        353: 	}
1.126     ng        354: 	return '<blockquote><table border="1">'.
1.148     albertel  355: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  356: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  357: 	    $middlerow.'</tr>'.
1.398     albertel  358: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  359: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    360:     } elsif ($response eq 'radiobutton') {
                    361: 	my %answer=&Apache::lonnet::str2hash($answer);
                    362: 	my ($toprow,$bottomrow);
1.434     albertel  363: 	my $correct = 
                    364: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    365: 	foreach my $foil (@$order) {
1.148     albertel  366: 	    if (exists($answer{$foil})) {
1.434     albertel  367: 		if ($foil eq $correct) {
1.148     albertel  368: 		    $toprow.='<td><b>true</b></td>';
                    369: 		} else {
                    370: 		    $toprow.='<td><i>true</i></td>';
                    371: 		}
                    372: 	    } else {
                    373: 		$toprow.='<td>false</td>';
                    374: 	    }
1.398     albertel  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  376: 	}
                    377: 	return '<blockquote><table border="1">'.
                    378: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  379: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    381:     } elsif ($response eq 'essay') {
1.257     albertel  382: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        386: 
1.257     albertel  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    392: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        393: 	}
1.166     albertel  394: 	$answer =~ s-\n-<br />-g;
                    395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  396:     } elsif ( $response eq 'organic') {
                    397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    400: 	return $result;
1.335     albertel  401:     } elsif ( $response eq 'Task') {
                    402: 	if ( $answer eq 'SUBMITTED') {
                    403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  405: 	    return $result;
                    406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    408: 			       keys(%{$record}));
                    409: 	    return join('<br />',($version,@matches));
                    410: 			       
                    411: 			       
                    412: 	} else {
                    413: 	    my $result =
                    414: 		'<p>'
                    415: 		.&mt('Overall result: [_1]',
                    416: 		     $record->{$version."resource.$respid.$partid.status"})
                    417: 		.'</p>';
                    418: 	    
                    419: 	    $result .= '<ul>';
                    420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    421: 			     keys(%{$record}));
                    422: 	    foreach my $grade (sort(@grade)) {
                    423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    425: 				     $dim, $record->{$grade}).
                    426: 			  '</li>';
                    427: 	    }
                    428: 	    $result.='</ul>';
                    429: 	    return $result;
                    430: 	}
1.440     albertel  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    432: 	$answer = 
                    433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    434: 							      $answer);
1.122     ng        435:     }
1.118     ng        436:     return $answer;
                    437: }
                    438: 
                    439: #-- A couple of common js functions
                    440: sub commonJSfunctions {
                    441:     my $request = shift;
                    442:     $request->print(<<COMMONJSFUNCTIONS);
                    443: <script type="text/javascript" language="javascript">
                    444:     function radioSelection(radioButton) {
                    445: 	var selection=null;
                    446: 	if (radioButton.length > 1) {
                    447: 	    for (var i=0; i<radioButton.length; i++) {
                    448: 		if (radioButton[i].checked) {
                    449: 		    return radioButton[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
                    453: 	    if (radioButton.checked) return radioButton.value;
                    454: 	}
                    455: 	return selection;
                    456:     }
                    457: 
                    458:     function pullDownSelection(selectOne) {
                    459: 	var selection="";
                    460: 	if (selectOne.length > 1) {
                    461: 	    for (var i=0; i<selectOne.length; i++) {
                    462: 		if (selectOne[i].selected) {
                    463: 		    return selectOne[i].value;
                    464: 		}
                    465: 	    }
                    466: 	} else {
1.138     albertel  467:             // only one value it must be the selected one
                    468: 	    return selectOne.value;
1.118     ng        469: 	}
                    470:     }
                    471: </script>
                    472: COMMONJSFUNCTIONS
                    473: }
                    474: 
1.44      ng        475: #--- Dumps the class list with usernames,list of sections,
                    476: #--- section, ids and fullnames for each user.
                    477: sub getclasslist {
1.76      ng        478:     my ($getsec,$filterlist) = @_;
1.291     albertel  479:     my @getsec;
1.442     banghart  480:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  481:     if (!ref($getsec)) {
                    482: 	if ($getsec ne '' && $getsec ne 'all') {
                    483: 	    @getsec=($getsec);
                    484: 	}
                    485:     } else {
                    486: 	@getsec=@{$getsec};
                    487:     }
                    488:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    489: 
1.56      matthew   490:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  491:     # Bail out if we were unable to get the classlist
1.56      matthew   492:     return if (! defined($classlist));
                    493:     #
                    494:     my %sections;
                    495:     my %fullnames;
1.205     matthew   496:     foreach my $student (keys(%$classlist)) {
                    497:         my $end      = 
                    498:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    499:         my $start    = 
                    500:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    501:         my $id       = 
                    502:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    503:         my $section  = 
                    504:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    505:         my $fullname = 
                    506:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    507:         my $status   = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        509: 	# filter students according to status selected
1.442     banghart  510: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    511: 	    if (!($stu_status =~ $status)) {
1.205     matthew   512: 		delete ($classlist->{$student});
1.76      ng        513: 		next;
                    514: 	    }
                    515: 	}
1.205     matthew   516: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  517: 	if (&canview($section)) {
1.291     albertel  518: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  519: 		$sections{$section}++;
1.205     matthew   520: 		$fullnames{$student}=$fullname;
1.103     albertel  521: 	    } else {
1.205     matthew   522: 		delete($classlist->{$student});
1.103     albertel  523: 	    }
                    524: 	} else {
1.205     matthew   525: 	    delete($classlist->{$student});
1.103     albertel  526: 	}
1.44      ng        527:     }
                    528:     my %seen = ();
1.56      matthew   529:     my @sections = sort(keys(%sections));
                    530:     return ($classlist,\@sections,\%fullnames);
1.44      ng        531: }
                    532: 
1.103     albertel  533: sub canmodify {
                    534:     my ($sec)=@_;
                    535:     if ($perm{'mgr'}) {
                    536: 	if (!defined($perm{'mgr_section'})) {
                    537: 	    # can modify whole class
                    538: 	    return 1;
                    539: 	} else {
                    540: 	    if ($sec eq $perm{'mgr_section'}) {
                    541: 		#can modify the requested section
                    542: 		return 1;
                    543: 	    } else {
                    544: 		# can't modify the request section
                    545: 		return 0;
                    546: 	    }
                    547: 	}
                    548:     }
                    549:     #can't modify
                    550:     return 0;
                    551: }
                    552: 
                    553: sub canview {
                    554:     my ($sec)=@_;
                    555:     if ($perm{'vgr'}) {
                    556: 	if (!defined($perm{'vgr_section'})) {
                    557: 	    # can modify whole class
                    558: 	    return 1;
                    559: 	} else {
                    560: 	    if ($sec eq $perm{'vgr_section'}) {
                    561: 		#can modify the requested section
                    562: 		return 1;
                    563: 	    } else {
                    564: 		# can't modify the request section
                    565: 		return 0;
                    566: 	    }
                    567: 	}
                    568:     }
                    569:     #can't modify
                    570:     return 0;
                    571: }
                    572: 
1.44      ng        573: #--- Retrieve the grade status of a student for all the parts
                    574: sub student_gradeStatus {
1.324     albertel  575:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  576:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        577:     my %partstatus = ();
                    578:     foreach (@$partlist) {
1.128     ng        579: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        580: 	$status              = 'nothing' if ($status eq '');
                    581: 	$partstatus{$_}      = $status;
                    582: 	my $subkey           = "resource.$_.submitted_by";
                    583: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    584:     }
                    585:     return %partstatus;
                    586: }
                    587: 
1.45      ng        588: # hidden form and javascript that calls the form
                    589: # Use by verifyscript and viewgrades
                    590: # Shows a student's view of problem and submission
                    591: sub jscriptNform {
1.324     albertel  592:     my ($symb) = @_;
1.442     banghart  593:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        594:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    595: 	'    function viewOneStudent(user,domain) {'."\n".
                    596: 	'	document.onestudent.student.value = user;'."\n".
                    597: 	'	document.onestudent.userdom.value = domain;'."\n".
                    598: 	'	document.onestudent.submit();'."\n".
                    599: 	'    }'."\n".
                    600: 	'</script>'."\n";
                    601:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  602: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  603: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    604: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  605: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        606: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    607: 	'<input type="hidden" name="student" value="" />'."\n".
                    608: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    609: 	'</form>'."\n";
                    610:     return $jscript;
                    611: }
1.39      ng        612: 
1.447     foxr      613: 
                    614: 
1.315     bowersj2  615: # Given the score (as a number [0-1] and the weight) what is the final
                    616: # point value? This function will round to the nearest tenth, third,
                    617: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  618: sub compute_points {
1.315     bowersj2  619:     my ($score, $weight) = @_;
                    620:     
                    621:     my $tolerance = .00001;
                    622:     my $points = $score * $weight;
                    623: 
                    624:     # Check for nearness to 1/x.
                    625:     my $check_for_nearness = sub {
                    626:         my ($factor) = @_;
                    627:         my $num = ($points * $factor) + $tolerance;
                    628:         my $floored_num = floor($num);
1.316     albertel  629:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  630:             return $floored_num / $factor;
                    631:         }
                    632:         return $points;
                    633:     };
                    634: 
                    635:     $points = $check_for_nearness->(10);
                    636:     $points = $check_for_nearness->(3);
                    637:     $points = $check_for_nearness->(4);
                    638:     
                    639:     return $points;
                    640: }
                    641: 
1.44      ng        642: #------------------ End of general use routines --------------------
1.87      www       643: 
                    644: #
                    645: # Find most similar essay
                    646: #
                    647: 
                    648: sub most_similar {
1.426     albertel  649:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       650: 
                    651: # ignore spaces and punctuation
                    652: 
                    653:     $uessay=~s/\W+/ /gs;
                    654: 
1.282     www       655: # ignore empty submissions (occuring when only files are sent)
                    656: 
                    657:     unless ($uessay=~/\w+/) { return ''; }
                    658: 
1.87      www       659: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       660:     my $limit=0.6;
1.87      www       661:     my $sname='';
                    662:     my $sdom='';
                    663:     my $scrsid='';
                    664:     my $sessay='';
                    665: # go through all essays ...
1.426     albertel  666:     foreach my $tkey (keys(%$old_essays)) {
                    667: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       668: # ... except the same student
1.426     albertel  669:         next if (($tname eq $uname) && ($tdom eq $udom));
                    670: 	my $tessay=$old_essays->{$tkey};
                    671: 	$tessay=~s/\W+/ /gs;
1.87      www       672: # String similarity gives up if not even limit
1.426     albertel  673: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       674: # Found one
1.426     albertel  675: 	if ($tsimilar>$limit) {
                    676: 	    $limit=$tsimilar;
                    677: 	    $sname=$tname;
                    678: 	    $sdom=$tdom;
                    679: 	    $scrsid=$tcrsid;
                    680: 	    $sessay=$old_essays->{$tkey};
                    681: 	}
1.87      www       682:     }
1.88      www       683:     if ($limit>0.6) {
1.87      www       684:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    685:     } else {
                    686:        return ('','','','',0);
                    687:     }
                    688: }
                    689: 
1.44      ng        690: #-------------------------------------------------------------------
                    691: 
                    692: #------------------------------------ Receipt Verification Routines
1.45      ng        693: #
1.44      ng        694: #--- Check whether a receipt number is valid.---
                    695: sub verifyreceipt {
                    696:     my $request  = shift;
                    697: 
1.257     albertel  698:     my $courseid = $env{'request.course.id'};
1.184     www       699:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  700: 	$env{'form.receipt'};
1.44      ng        701:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  702:     my ($symb)   = &get_symb($request);
1.44      ng        703: 
1.398     albertel  704:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    705: 	$receipt.'</h3></span>'."\n".
                    706: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        707: 
                    708:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   709:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  710:     
                    711:     my $receiptparts=0;
1.390     albertel  712:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    713: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  714:     my $parts=['0'];
1.324     albertel  715:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  716:     foreach (sort 
                    717: 	     {
                    718: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    719: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    720: 		 }
                    721: 		 return $a cmp $b;
                    722: 	     } (keys(%$fullname))) {
1.44      ng        723: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  724: 	foreach my $part (@$parts) {
                    725: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    726: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    727: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  728: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  729: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    730: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    731: 		if ($receiptparts) {
                    732: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    733: 		}
                    734: 		$contents.='</tr>'."\n";
                    735: 		
                    736: 		$matches++;
                    737: 	    }
1.44      ng        738: 	}
                    739:     }
                    740:     if ($matches == 0) {
                    741: 	$string = $title.'No match found for the above receipt.';
                    742:     } else {
1.324     albertel  743: 	$string = &jscriptNform($symb).$title.
1.44      ng        744: 	    'The above receipt matches the following student'.
                    745: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    746: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    747: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    748: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    749: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  750: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    751: 	if ($receiptparts) {
                    752: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    753: 	}
                    754: 	$string.='</tr>'."\n".$contents.
1.44      ng        755: 	    '</table></td></tr></table>'."\n";
                    756:     }
1.324     albertel  757:     return $string.&show_grading_menu_form($symb);
1.44      ng        758: }
                    759: 
                    760: #--- This is called by a number of programs.
                    761: #--- Called from the Grading Menu - View/Grade an individual student
                    762: #--- Also called directly when one clicks on the subm button 
                    763: #    on the problem page.
1.30      ng        764: sub listStudents {
1.41      ng        765:     my ($request) = shift;
1.49      albertel  766: 
1.324     albertel  767:     my ($symb) = &get_symb($request);
1.257     albertel  768:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    769:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    770:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    771:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    772: 
                    773:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    774:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    775: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  776: 
1.398     albertel  777:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    778: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        779: 
1.324     albertel  780:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  781: 
1.45      ng        782:     $request->print(<<LISTJAVASCRIPT);
                    783: <script type="text/javascript" language="javascript">
1.110     ng        784:     function checkSelect(checkBox) {
                    785: 	var ctr=0;
                    786: 	var sense="";
                    787: 	if (checkBox.length > 1) {
                    788: 	    for (var i=0; i<checkBox.length; i++) {
                    789: 		if (checkBox[i].checked) {
                    790: 		    ctr++;
                    791: 		}
                    792: 	    }
                    793: 	    sense = "a student or group of students";
                    794: 	} else {
                    795: 	    if (checkBox.checked) {
                    796: 		ctr = 1;
                    797: 	    }
                    798: 	    sense = "the student";
                    799: 	}
                    800: 	if (ctr == 0) {
1.126     ng        801: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        802: 	    return false;
                    803: 	}
                    804: 	document.gradesub.submit();
                    805:     }
                    806: 
                    807:     function reLoadList(formname) {
1.112     ng        808: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        809: 	formname.command.value = 'submission';
                    810: 	formname.submit();
                    811:     }
1.45      ng        812: </script>
                    813: LISTJAVASCRIPT
                    814: 
1.118     ng        815:     &commonJSfunctions($request);
1.41      ng        816:     $request->print($result);
1.39      ng        817: 
1.401     albertel  818:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    819:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  820:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    821: 	"\n".$table.
1.401     albertel  822: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  823: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    824: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    825: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    826: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  827: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  828: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  829:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  830: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  831:     }
1.442     banghart  832:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    833:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  834:     $env{'form.Status'} = $saveStatus;
1.267     albertel  835:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    836: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    837: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  838: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    839:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    840:         '<option value="1">Whole Points</option>'.
                    841:         '<option value=".5">Half Points</option>'.
1.349     albertel  842:         '<option value=".25">Quarter Points</option>'.
                    843:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  844:         '</select>'.
1.432     banghart  845:         &build_section_inputs().
1.45      ng        846: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  847: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    848: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    849: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    850: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  851: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        852: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    853: 
1.257     albertel  854:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  855: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        856:     } else {
                    857: 	$gradeTable.='<b>Student Status:</b> '.
                    858: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    859:     }
1.112     ng        860: 
1.126     ng        861:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    862: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        863: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  864: 
                    865: # checkall buttons
                    866:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        867:     $gradeTable.='<input type="button" '."\n".
1.45      ng        868: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  869: 	'value="Next->" /> <br />'."\n";
                    870:     $gradeTable.=&check_buttons();
1.401     albertel  871:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  872:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        873:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        874: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    875:     my $loop = 0;
                    876:     while ($loop < 2) {
1.126     ng        877: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  878: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  879: 	if ($env{'form.showgrading'} eq 'yes' 
                    880: 	    && $submitonly ne 'queued'
                    881: 	    && $submitonly ne 'all') {
1.110     ng        882: 	    foreach (sort(@$partlist)) {
1.324     albertel  883: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  884: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    885: 		    ' Status&nbsp;</b></td>';
1.110     ng        886: 	    }
1.301     albertel  887: 	} elsif ($submitonly eq 'queued') {
                    888: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        889: 	}
                    890: 	$loop++;
1.126     ng        891: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        892:     }
1.45      ng        893:     $gradeTable.='</tr>'."\n";
1.41      ng        894: 
1.45      ng        895:     my $ctr = 0;
1.294     albertel  896:     foreach my $student (sort 
                    897: 			 {
                    898: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    899: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    900: 			     }
                    901: 			     return $a cmp $b;
                    902: 			 }
                    903: 			 (keys(%$fullname))) {
1.41      ng        904: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  905: 
1.110     ng        906: 	my %status = ();
1.301     albertel  907: 
                    908: 	if ($submitonly eq 'queued') {
                    909: 	    my %queue_status = 
                    910: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    911: 							$udom,$uname);
                    912: 	    next if (!defined($queue_status{'gradingqueue'}));
                    913: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    914: 	}
                    915: 
                    916: 	if ($env{'form.showgrading'} eq 'yes' 
                    917: 	    && $submitonly ne 'queued'
                    918: 	    && $submitonly ne 'all') {
1.324     albertel  919: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  920: 	    my $submitted = 0;
1.164     albertel  921: 	    my $graded = 0;
1.248     albertel  922: 	    my $incorrect = 0;
1.110     ng        923: 	    foreach (keys(%status)) {
1.145     albertel  924: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  925: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    926: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    927: 		
1.110     ng        928: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    929: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  930: 		    $submitted = 0;
1.150     albertel  931: 		    my ($part)=split(/\./,$partid);
1.110     ng        932: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  933: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        934: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    935: 		}
1.41      ng        936: 	    }
1.248     albertel  937: 	    
1.156     albertel  938: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    939: 				     $submitonly eq 'incorrect' ||
                    940: 				     $submitonly eq 'graded'));
1.248     albertel  941: 	    next if (!$graded && ($submitonly eq 'graded'));
                    942: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        943: 	}
1.34      ng        944: 
1.45      ng        945: 	$ctr++;
1.249     albertel  946: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    947: 
1.104     albertel  948: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        949: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        950: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  951:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    952:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    953: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    954: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    955: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        956: 
1.257     albertel  957: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        958: 		foreach (sort keys(%status)) {
                    959: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  960: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        961: 		}
1.41      ng        962: 	    }
1.126     ng        963: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        964: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        965: 	}
                    966:     }
1.110     ng        967:     if ($ctr%2 ==1) {
1.126     ng        968: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  969: 	    if ($env{'form.showgrading'} eq 'yes' 
                    970: 		&& $submitonly ne 'queued'
                    971: 		&& $submitonly ne 'all') {
1.110     ng        972: 		foreach (@$partlist) {
                    973: 		    $gradeTable.='<td>&nbsp;</td>';
                    974: 		}
1.301     albertel  975: 	    } elsif ($submitonly eq 'queued') {
                    976: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        977: 	    }
                    978: 	$gradeTable.='</tr>';
                    979:     }
                    980: 
1.249     albertel  981:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        982: 	'<input type="button" '.
                    983: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        984: 	'value="Next->" /></form>'."\n";
1.45      ng        985:     if ($ctr == 0) {
1.96      albertel  986: 	my $num_students=(scalar(keys(%$fullname)));
                    987: 	if ($num_students eq 0) {
1.398     albertel  988: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  989: 	} else {
1.171     albertel  990: 	    my $submissions='submissions';
                    991: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    992: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  993: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  994: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  995: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  996: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  997: 	}
1.46      ng        998:     } elsif ($ctr == 1) {
                    999: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1000:     }
1.324     albertel 1001:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1002:     $request->print($gradeTable);
1.44      ng       1003:     return '';
1.10      ng       1004: }
                   1005: 
1.44      ng       1006: #---- Called from the listStudents routine
1.249     albertel 1007: 
                   1008: sub check_script {
                   1009:     my ($form, $type)=@_;
                   1010:     my $chkallscript='<script type="text/javascript">
                   1011:     function checkall() {
                   1012:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1013:             ele = document.forms.'.$form.'.elements[i];
                   1014:             if (ele.name == "'.$type.'") {
                   1015:             document.forms.'.$form.'.elements[i].checked=true;
                   1016:                                        }
                   1017:         }
                   1018:     }
                   1019: 
                   1020:     function checksec() {
                   1021:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1022:             ele = document.forms.'.$form.'.elements[i];
                   1023:            string = document.forms.'.$form.'.chksec.value;
                   1024:            if
                   1025:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1026:               document.forms.'.$form.'.elements[i].checked=true;
                   1027:             }
                   1028:         }
                   1029:     }
                   1030: 
                   1031: 
                   1032:     function uncheckall() {
                   1033:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1034:             ele = document.forms.'.$form.'.elements[i];
                   1035:             if (ele.name == "'.$type.'") {
                   1036:             document.forms.'.$form.'.elements[i].checked=false;
                   1037:                                        }
                   1038:         }
                   1039:     }
                   1040: 
                   1041: </script>'."\n";
                   1042:     return $chkallscript;
                   1043: }
                   1044: 
                   1045: sub check_buttons {
                   1046:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1047:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1048:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1049:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1050:     return $buttons;
                   1051: }
                   1052: 
1.44      ng       1053: #     Displays the submissions for one student or a group of students
1.34      ng       1054: sub processGroup {
1.41      ng       1055:     my ($request)  = shift;
                   1056:     my $ctr        = 0;
1.155     albertel 1057:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1058:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1059: 
1.396     banghart 1060:     foreach my $student (@stuchecked) {
                   1061: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1062: 	$env{'form.student'}        = $uname;
                   1063: 	$env{'form.userdom'}        = $udom;
                   1064: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1065: 	&submission($request,$ctr,$total);
                   1066: 	$ctr++;
                   1067:     }
                   1068:     return '';
1.35      ng       1069: }
1.34      ng       1070: 
1.44      ng       1071: #------------------------------------------------------------------------------------
                   1072: #
                   1073: #-------------------------- Next few routines handles grading by student, essentially
                   1074: #                           handles essay response type problem/part
                   1075: #
                   1076: #--- Javascript to handle the submission page functionality ---
                   1077: sub sub_page_js {
                   1078:     my $request = shift;
                   1079:     $request->print(<<SUBJAVASCRIPT);
                   1080: <script type="text/javascript" language="javascript">
1.71      ng       1081:     function updateRadio(formname,id,weight) {
1.125     ng       1082: 	var gradeBox = formname["GD_BOX"+id];
                   1083: 	var radioButton = formname["RADVAL"+id];
                   1084: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1085: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1086: 	gradeBox.value = pts;
                   1087: 	var resetbox = false;
                   1088: 	if (isNaN(pts) || pts < 0) {
                   1089: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1090: 	    for (var i=0; i<radioButton.length; i++) {
                   1091: 		if (radioButton[i].checked) {
                   1092: 		    gradeBox.value = i;
                   1093: 		    resetbox = true;
                   1094: 		}
                   1095: 	    }
                   1096: 	    if (!resetbox) {
                   1097: 		formtextbox.value = "";
                   1098: 	    }
                   1099: 	    return;
1.44      ng       1100: 	}
1.71      ng       1101: 
                   1102: 	if (pts > weight) {
                   1103: 	    var resp = confirm("You entered a value ("+pts+
                   1104: 			       ") greater than the weight for the part. Accept?");
                   1105: 	    if (resp == false) {
1.125     ng       1106: 		gradeBox.value = oldpts;
1.71      ng       1107: 		return;
                   1108: 	    }
1.44      ng       1109: 	}
1.13      albertel 1110: 
1.71      ng       1111: 	for (var i=0; i<radioButton.length; i++) {
                   1112: 	    radioButton[i].checked=false;
                   1113: 	    if (pts == i && pts != "") {
                   1114: 		radioButton[i].checked=true;
                   1115: 	    }
                   1116: 	}
                   1117: 	updateSelect(formname,id);
1.125     ng       1118: 	formname["stores"+id].value = "0";
1.41      ng       1119:     }
1.5       albertel 1120: 
1.72      ng       1121:     function writeBox(formname,id,pts) {
1.125     ng       1122: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1123: 	if (checkSolved(formname,id) == 'update') {
                   1124: 	    gradeBox.value = pts;
                   1125: 	} else {
1.125     ng       1126: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1127: 	    gradeBox.value = oldpts;
1.125     ng       1128: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1129: 	    for (var i=0; i<radioButton.length; i++) {
                   1130: 		radioButton[i].checked=false;
1.72      ng       1131: 		if (i == oldpts) {
1.71      ng       1132: 		    radioButton[i].checked=true;
                   1133: 		}
                   1134: 	    }
1.41      ng       1135: 	}
1.125     ng       1136: 	formname["stores"+id].value = "0";
1.71      ng       1137: 	updateSelect(formname,id);
                   1138: 	return;
1.41      ng       1139:     }
1.44      ng       1140: 
1.71      ng       1141:     function clearRadBox(formname,id) {
                   1142: 	if (checkSolved(formname,id) == 'noupdate') {
                   1143: 	    updateSelect(formname,id);
                   1144: 	    return;
                   1145: 	}
1.125     ng       1146: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1147: 	for (var i=0; i<gradeSelect.length; i++) {
                   1148: 	    if (gradeSelect[i].selected) {
                   1149: 		var selectx=i;
                   1150: 	    }
                   1151: 	}
1.125     ng       1152: 	var stores = formname["stores"+id];
1.71      ng       1153: 	if (selectx == stores.value) { return };
1.125     ng       1154: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1155: 	gradeBox.value = "";
1.125     ng       1156: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1157: 	for (var i=0; i<radioButton.length; i++) {
                   1158: 	    radioButton[i].checked=false;
                   1159: 	}
                   1160: 	stores.value = selectx;
                   1161:     }
1.5       albertel 1162: 
1.71      ng       1163:     function checkSolved(formname,id) {
1.125     ng       1164: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1165: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1166: 	    if (!reply) {return "noupdate";}
1.120     ng       1167: 	    formname.overRideScore.value = 'yes';
1.41      ng       1168: 	}
1.71      ng       1169: 	return "update";
1.13      albertel 1170:     }
1.71      ng       1171: 
                   1172:     function updateSelect(formname,id) {
1.125     ng       1173: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1174: 	return;
1.41      ng       1175:     }
1.33      ng       1176: 
1.121     ng       1177: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1178:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1179: 	formname.gradeOpt.value = val;
1.71      ng       1180: 	if (val == "Save & Next") {
                   1181: 	    for (i=0;i<=total;i++) {
                   1182: 		for (j=0;j<parttot;j++) {
1.125     ng       1183: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1184: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1185: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1186: 			if (points == "") {
1.125     ng       1187: 			    var name = formname["name"+i].value;
1.129     ng       1188: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1189: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1190: 					       ", part "+partid+". Continue?");
1.71      ng       1191: 			    if (resp == false) {
1.125     ng       1192: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1193: 				return false;
                   1194: 			    }
                   1195: 			}
                   1196: 		    }
                   1197: 		    
                   1198: 		}
                   1199: 	    }
                   1200: 	    
                   1201: 	}
1.121     ng       1202: 	if (val == "Grade Student") {
                   1203: 	    formname.showgrading.value = "yes";
                   1204: 	    if (formname.Status.value == "") {
                   1205: 		formname.Status.value = "Active";
                   1206: 	    }
                   1207: 	    formname.studentNo.value = total;
                   1208: 	}
1.120     ng       1209: 	formname.submit();
                   1210:     }
                   1211: 
1.71      ng       1212: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1213:     function checkSubmitPage(formname,total) {
                   1214: 	noscore = new Array(100);
                   1215: 	var ptr = 0;
                   1216: 	for (i=1;i<total;i++) {
1.125     ng       1217: 	    var partid = formname["q_"+i].value;
1.127     ng       1218: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1219: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1220: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1221: 		if (points == "" && status != "correct_by_student") {
                   1222: 		    noscore[ptr] = i;
                   1223: 		    ptr++;
                   1224: 		}
                   1225: 	    }
                   1226: 	}
                   1227: 	if (ptr != 0) {
                   1228: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1229: 	    var prolist = "";
                   1230: 	    if (ptr == 1) {
                   1231: 		prolist = noscore[0];
                   1232: 	    } else {
                   1233: 		var i = 0;
                   1234: 		while (i < ptr-1) {
                   1235: 		    prolist += noscore[i]+", ";
                   1236: 		    i++;
                   1237: 		}
                   1238: 		prolist += "and "+noscore[i];
                   1239: 	    }
                   1240: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1241: 	    if (resp == false) {
                   1242: 		return false;
                   1243: 	    }
                   1244: 	}
1.45      ng       1245: 
1.71      ng       1246: 	formname.submit();
                   1247:     }
                   1248: </script>
                   1249: SUBJAVASCRIPT
                   1250: }
1.45      ng       1251: 
1.71      ng       1252: #--- javascript for essay type problem --
                   1253: sub sub_page_kw_js {
                   1254:     my $request = shift;
1.80      ng       1255:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1256:     &commonJSfunctions($request);
1.350     albertel 1257: 
1.351     albertel 1258:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1259:     <script text="text/javascript">
                   1260:     function checkInput() {
                   1261:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1262:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1263:       var usrctr = document.msgcenter.usrctr.value;
                   1264:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1265:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1266: 
                   1267:       var msgchk = "";
                   1268:       if (document.msgcenter.subchk.checked) {
                   1269:          msgchk = "msgsub,";
                   1270:       }
                   1271:       var includemsg = 0;
                   1272:       for (var i=1; i<=nmsg; i++) {
                   1273:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1274:           var frmmsg = document.msgcenter["msg"+i];
                   1275:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1276:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1277:           showflg.value = "1";
                   1278:           var chkbox = document.msgcenter["msgn"+i];
                   1279:           if (chkbox.checked) {
                   1280:              msgchk += "savemsg"+i+",";
                   1281:              includemsg = 1;
                   1282:           }
                   1283:       }
                   1284:       if (document.msgcenter.newmsgchk.checked) {
                   1285:          msgchk += "newmsg"+usrctr;
                   1286:          includemsg = 1;
                   1287:       }
                   1288:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1289:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1290:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1291:       includemsg.value = msgchk;
                   1292: 
                   1293:       self.close()
                   1294: 
                   1295:     }
                   1296:     </script>
                   1297: INNERJS
                   1298: 
1.351     albertel 1299:     my $inner_js_highlight_central=<<INNERJS;
                   1300:  <script type="text/javascript">
                   1301:     function updateChoice(flag) {
                   1302:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1303:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1304:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1305:       opener.document.SCORE.refresh.value = "on";
                   1306:       if (opener.document.SCORE.keywords.value!=""){
                   1307:          opener.document.SCORE.submit();
                   1308:       }
                   1309:       self.close()
                   1310:     }
                   1311: </script>
                   1312: INNERJS
                   1313: 
                   1314:     my $start_page_msg_central = 
                   1315:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1316: 				       {'js_ready'  => 1,
                   1317: 					'only_body' => 1,
                   1318: 					'bgcolor'   =>'#FFFFFF',});
                   1319:     my $end_page_msg_central = 
                   1320: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1321: 
                   1322: 
                   1323:     my $start_page_highlight_central = 
                   1324:         &Apache::loncommon::start_page('Highlight Central',
                   1325: 				       $inner_js_highlight_central,
1.350     albertel 1326: 				       {'js_ready'  => 1,
                   1327: 					'only_body' => 1,
                   1328: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1329:     my $end_page_highlight_central = 
1.350     albertel 1330: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1331: 
1.219     www      1332:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1333:     $docopen=~s/^document\.//;
1.71      ng       1334:     $request->print(<<SUBJAVASCRIPT);
                   1335: <script type="text/javascript" language="javascript">
1.45      ng       1336: 
1.44      ng       1337: //===================== Show list of keywords ====================
1.122     ng       1338:   function keywords(formname) {
                   1339:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1340:     if (nret==null) return;
1.122     ng       1341:     formname.keywords.value = nret;
1.44      ng       1342: 
1.122     ng       1343:     if (formname.keywords.value != "") {
1.128     ng       1344: 	formname.refresh.value = "on";
1.122     ng       1345: 	formname.submit();
1.44      ng       1346:     }
                   1347:     return;
                   1348:   }
                   1349: 
                   1350: //===================== Script to view submitted by ==================
                   1351:   function viewSubmitter(submitter) {
                   1352:     document.SCORE.refresh.value = "on";
                   1353:     document.SCORE.NCT.value = "1";
                   1354:     document.SCORE.unamedom0.value = submitter;
                   1355:     document.SCORE.submit();
                   1356:     return;
                   1357:   }
                   1358: 
                   1359: //===================== Script to add keyword(s) ==================
                   1360:   function getSel() {
                   1361:     if (document.getSelection) txt = document.getSelection();
                   1362:     else if (document.selection) txt = document.selection.createRange().text;
                   1363:     else return;
                   1364:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1365:     if (cleantxt=="") {
1.46      ng       1366: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1367: 	return;
                   1368:     }
                   1369:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1370:     if (nret==null) return;
1.127     ng       1371:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1372:     if (document.SCORE.keywords.value != "") {
1.127     ng       1373: 	document.SCORE.refresh.value = "on";
1.44      ng       1374: 	document.SCORE.submit();
                   1375:     }
                   1376:     return;
                   1377:   }
                   1378: 
                   1379: //====================== Script for composing message ==============
1.80      ng       1380:    // preload images
                   1381:    img1 = new Image();
                   1382:    img1.src = "$iconpath/mailbkgrd.gif";
                   1383:    img2 = new Image();
                   1384:    img2.src = "$iconpath/mailto.gif";
                   1385: 
1.44      ng       1386:   function msgCenter(msgform,usrctr,fullname) {
                   1387:     var Nmsg  = msgform.savemsgN.value;
                   1388:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1389:     var subject = msgform.msgsub.value;
1.127     ng       1390:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1391:     re = /msgsub/;
                   1392:     var shwsel = "";
                   1393:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1394:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1395:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1396:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1397: 	var testmsg = "savemsg"+i+",";
                   1398: 	re = new RegExp(testmsg,"g");
1.44      ng       1399: 	shwsel = "";
                   1400: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1401: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1402: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1403: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1404: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1405:     }
1.125     ng       1406:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1407:     shwsel = "";
                   1408:     re = /newmsg/;
                   1409:     if (re.test(msgchk)) { shwsel = "checked" }
                   1410:     newMsg(newmsg,shwsel);
                   1411:     msgTail(); 
                   1412:     return;
                   1413:   }
                   1414: 
1.123     ng       1415:   function checkEntities(strx) {
                   1416:     if (strx.length == 0) return strx;
                   1417:     var orgStr = ["&", "<", ">", '"']; 
                   1418:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1419:     var counter = 0;
                   1420:     while (counter < 4) {
                   1421: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1422: 	counter++;
                   1423:     }
                   1424:     return strx;
                   1425:   }
                   1426: 
                   1427:   function strReplace(strx, orgStr, newStr) {
                   1428:     return strx.split(orgStr).join(newStr);
                   1429:   }
                   1430: 
1.44      ng       1431:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1432:     var height = 70*Nmsg+250;
1.44      ng       1433:     var scrollbar = "no";
                   1434:     if (height > 600) {
                   1435: 	height = 600;
                   1436: 	scrollbar = "yes";
                   1437:     }
1.118     ng       1438:     var xpos = (screen.width-600)/2;
                   1439:     xpos = (xpos < 0) ? '0' : xpos;
                   1440:     var ypos = (screen.height-height)/2-30;
                   1441:     ypos = (ypos < 0) ? '0' : ypos;
                   1442: 
1.206     albertel 1443:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1444:     pWin.focus();
                   1445:     pDoc = pWin.document;
1.219     www      1446:     pDoc.$docopen;
1.351     albertel 1447:     pDoc.write('$start_page_msg_central');
1.76      ng       1448: 
                   1449:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1450:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1451:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1452: 
                   1453:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1454:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1455:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1456: }
                   1457:     function displaySubject(msg,shwsel) {
1.76      ng       1458:     pDoc = pWin.document;
                   1459:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1460:     pDoc.write("<td>Subject</td>");
                   1461:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1462:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1463: }
                   1464: 
1.72      ng       1465:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1466:     pDoc = pWin.document;
                   1467:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1468:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1469:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1470:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1471: }
                   1472: 
                   1473:   function newMsg(newmsg,shwsel) {
1.76      ng       1474:     pDoc = pWin.document;
                   1475:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1476:     pDoc.write("<td align=\\"center\\">New</td>");
                   1477:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1478:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1479: }
                   1480: 
                   1481:   function msgTail() {
1.76      ng       1482:     pDoc = pWin.document;
                   1483:     pDoc.write("</table>");
                   1484:     pDoc.write("</td></tr></table>&nbsp;");
                   1485:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1486:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1487:     pDoc.write("</form>");
1.351     albertel 1488:     pDoc.write('$end_page_msg_central');
1.128     ng       1489:     pDoc.close();
1.44      ng       1490: }
                   1491: 
                   1492: //====================== Script for keyword highlight options ==============
                   1493:   function kwhighlight() {
                   1494:     var kwclr    = document.SCORE.kwclr.value;
                   1495:     var kwsize   = document.SCORE.kwsize.value;
                   1496:     var kwstyle  = document.SCORE.kwstyle.value;
                   1497:     var redsel = "";
                   1498:     var grnsel = "";
                   1499:     var blusel = "";
                   1500:     if (kwclr=="red")   {var redsel="checked"};
                   1501:     if (kwclr=="green") {var grnsel="checked"};
                   1502:     if (kwclr=="blue")  {var blusel="checked"};
                   1503:     var sznsel = "";
                   1504:     var sz1sel = "";
                   1505:     var sz2sel = "";
                   1506:     if (kwsize=="0")  {var sznsel="checked"};
                   1507:     if (kwsize=="+1") {var sz1sel="checked"};
                   1508:     if (kwsize=="+2") {var sz2sel="checked"};
                   1509:     var synsel = "";
                   1510:     var syisel = "";
                   1511:     var sybsel = "";
                   1512:     if (kwstyle=="")    {var synsel="checked"};
                   1513:     if (kwstyle=="<i>") {var syisel="checked"};
                   1514:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1515:     highlightCentral();
                   1516:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1517:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1518:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1519:     highlightend();
                   1520:     return;
                   1521:   }
                   1522: 
                   1523:   function highlightCentral() {
1.76      ng       1524: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1525:     var xpos = (screen.width-400)/2;
                   1526:     xpos = (xpos < 0) ? '0' : xpos;
                   1527:     var ypos = (screen.height-330)/2-30;
                   1528:     ypos = (ypos < 0) ? '0' : ypos;
                   1529: 
1.206     albertel 1530:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1531:     hwdWin.focus();
                   1532:     var hDoc = hwdWin.document;
1.219     www      1533:     hDoc.$docopen;
1.351     albertel 1534:     hDoc.write('$start_page_highlight_central');
1.76      ng       1535:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1536:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1537: 
                   1538:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1539:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1540:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1541:   }
                   1542: 
                   1543:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1544:     var hDoc = hwdWin.document;
                   1545:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1546:     hDoc.write("<td align=\\"left\\">");
                   1547:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1548:     hDoc.write("<td align=\\"left\\">");
                   1549:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1550:     hDoc.write("<td align=\\"left\\">");
                   1551:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1552:     hDoc.write("</tr>");
1.44      ng       1553:   }
                   1554: 
                   1555:   function highlightend() { 
1.76      ng       1556:     var hDoc = hwdWin.document;
                   1557:     hDoc.write("</table>");
                   1558:     hDoc.write("</td></tr></table>&nbsp;");
                   1559:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1560:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1561:     hDoc.write("</form>");
1.351     albertel 1562:     hDoc.write('$end_page_highlight_central');
1.128     ng       1563:     hDoc.close();
1.44      ng       1564:   }
                   1565: 
                   1566: </script>
                   1567: SUBJAVASCRIPT
                   1568: }
                   1569: 
1.349     albertel 1570: sub get_increment {
1.348     bowersj2 1571:     my $increment = $env{'form.increment'};
                   1572:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1573:         $increment != .1) {
                   1574:         $increment = 1;
                   1575:     }
                   1576:     return $increment;
                   1577: }
                   1578: 
1.71      ng       1579: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1580: sub gradeBox {
1.322     albertel 1581:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1582:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1583: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1584: 	'/check.gif" height="16" border="0" />';
                   1585:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1586:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1587: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1588:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1589:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1590: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1591:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1592:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1593:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1594: 				       [$partid]);
                   1595:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1596:     if ($last_resets{$partid}) {
                   1597:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1598:     }
1.71      ng       1599:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1600: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1601:     my $ctr = 0;
1.348     bowersj2 1602:     my $thisweight = 0;
1.349     albertel 1603:     my $increment = &get_increment();
1.71      ng       1604:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1605:     while ($thisweight<=$wgt) {
1.381     albertel 1606: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1607: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1608: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1609: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1610: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1611:         $thisweight += $increment;
1.71      ng       1612: 	$ctr++;
                   1613:     }
                   1614:     $result.='</tr></table>';
                   1615:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1616:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1617: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1618: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1619: 	$wgt.')" /></td>'."\n";
                   1620:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1621: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1622: 	' </td><td>'."\n";
                   1623:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1624: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1625:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1626: 	$result.='<option></option>'.
1.401     albertel 1627: 	    '<option selected="selected">excused</option>';
1.71      ng       1628:     } else {
1.401     albertel 1629: 	$result.='<option selected="selected"></option>'.
1.125     ng       1630: 	    '<option>excused</option>';
1.71      ng       1631:     }
1.125     ng       1632:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1633:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1634:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1635: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1636: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1637: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1638:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1639:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1640:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1641:         $aggtries.'" />'."\n";
1.71      ng       1642:     $result.='</td></tr></table>'."\n";
1.323     banghart 1643:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1644:     return $result;
                   1645: }
1.322     albertel 1646: 
                   1647: sub handback_box {
1.323     banghart 1648:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1649:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1650:     my (@respids);
1.375     albertel 1651:      my @part_response_id = &flatten_responseType($responseType);
                   1652:     foreach my $part_response_id (@part_response_id) {
                   1653:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1654:         if ($part eq $partid) {
1.375     albertel 1655:             push(@respids,$resp);
1.323     banghart 1656:         }
                   1657:     }
1.318     banghart 1658:     my $result;
1.323     banghart 1659:     foreach my $respid (@respids) {
1.322     albertel 1660: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1661: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1662: 	next if (!@$files);
                   1663: 	my $file_counter = 1;
1.313     banghart 1664: 	foreach my $file (@$files) {
1.368     banghart 1665: 	    if ($file =~ /\/portfolio\//) {
                   1666:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1667:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1668:     	        $file_disp = "$name.$ext";
                   1669:     	        $file = $file_path.$file_disp;
                   1670:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1671:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1672:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1673:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1674:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1675:     	        $file_counter++;
                   1676: 	    }
1.322     albertel 1677: 	}
1.313     banghart 1678:     }
1.318     banghart 1679:     return $result;    
1.71      ng       1680: }
1.44      ng       1681: 
1.58      albertel 1682: sub show_problem {
1.382     albertel 1683:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1684:     my $rendered;
1.382     albertel 1685:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1686:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1687:     if ($mode eq 'both' or $mode eq 'text') {
                   1688: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1689: 						       $env{'request.course.id'},
                   1690: 						       undef,\%form);
1.144     albertel 1691:     }
1.58      albertel 1692:     if ($removeform) {
                   1693: 	$rendered=~s|<form(.*?)>||g;
                   1694: 	$rendered=~s|</form>||g;
1.374     albertel 1695: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1696:     }
1.144     albertel 1697:     my $companswer;
                   1698:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1699: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1700: 	$companswer=
                   1701: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1702: 						    $env{'request.course.id'},
                   1703: 						    %form);
1.144     albertel 1704:     }
1.58      albertel 1705:     if ($removeform) {
                   1706: 	$companswer=~s|<form(.*?)>||g;
                   1707: 	$companswer=~s|</form>||g;
1.144     albertel 1708: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1709:     }
                   1710:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1711:     $result.='<table border="0" width="100%">';
1.144     albertel 1712:     if ($viewon) {
                   1713: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1714: 	if ($mode eq 'both' or $mode eq 'text') {
                   1715: 	    $result.='View of the problem - ';
                   1716: 	} else {
                   1717: 	    $result.='Correct answer: ';
                   1718: 	}
1.257     albertel 1719: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1720:     }
                   1721:     if ($mode eq 'both') {
                   1722: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1723: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1724:     } elsif ($mode eq 'text') {
                   1725: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1726:     } elsif ($mode eq 'answer') {
                   1727: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1728:     }
1.58      albertel 1729:     $result.='</td></tr></table>';
                   1730:     $result.='</td></tr></table><br />';
1.71      ng       1731:     return $result;
1.58      albertel 1732: }
1.397     albertel 1733: 
1.396     banghart 1734: sub files_exist {
                   1735:     my ($r, $symb) = @_;
                   1736:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1737: 
1.396     banghart 1738:     foreach my $student (@students) {
                   1739:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1740:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1741: 					      $udom,$uname);
1.396     banghart 1742:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1743:         foreach my $submission (@$string) {
                   1744:             my ($partid,$respid) =
                   1745: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1746:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1747: 					   \%record);
                   1748:             return 1 if (@$files);
1.396     banghart 1749:         }
                   1750:     }
1.397     albertel 1751:     return 0;
1.396     banghart 1752: }
1.397     albertel 1753: 
1.394     banghart 1754: sub download_all_link {
                   1755:     my ($r,$symb) = @_;
1.395     albertel 1756:     my $all_students = 
                   1757: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1758: 
                   1759:     my $parts =
                   1760: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1761: 
1.394     banghart 1762:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1763:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1764:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1765:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1766:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1767: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1768:     return
                   1769: }
1.395     albertel 1770: 
1.432     banghart 1771: sub build_section_inputs {
                   1772:     my $section_inputs;
                   1773:     if ($env{'form.section'} eq '') {
                   1774:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1775:     } else {
                   1776:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1777:         foreach my $section (@sections) {
1.432     banghart 1778:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1779:         }
                   1780:     }
                   1781:     return $section_inputs;
                   1782: }
                   1783: 
1.44      ng       1784: # --------------------------- show submissions of a student, option to grade 
                   1785: sub submission {
                   1786:     my ($request,$counter,$total) = @_;
                   1787: 
1.257     albertel 1788:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1789:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1790:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1791:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1792:     my $symb = &get_symb($request); 
                   1793:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1794: 
                   1795:     if (!&canview($usec)) {
1.398     albertel 1796: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1797: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1798: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1799: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1800: 	return;
                   1801:     }
                   1802: 
1.257     albertel 1803:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1804:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1805:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1806:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1807:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1808: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1809: 	'/check.gif" height="16" border="0" />';
1.41      ng       1810: 
1.426     albertel 1811:     my %old_essays;
1.41      ng       1812:     # header info
                   1813:     if ($counter == 0) {
                   1814: 	&sub_page_js($request);
1.257     albertel 1815: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1816: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1817: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1818: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1819: 	    &download_all_link($request, $symb);
                   1820: 	}
1.398     albertel 1821: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1822: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1823: 
1.257     albertel 1824: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1825: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1826: 		$checkIcon.' symbol.'."\n";
                   1827: 	    $request->print($checkMark);
                   1828: 	}
1.41      ng       1829: 
1.44      ng       1830: 	# option to display problem, only once else it cause problems 
                   1831:         # with the form later since the problem has a form.
1.257     albertel 1832: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1833: 	    my $mode;
1.257     albertel 1834: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1835: 		$mode='both';
1.257     albertel 1836: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1837: 		$mode='text';
1.257     albertel 1838: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1839: 		$mode='answer';
                   1840: 	    }
1.329     albertel 1841: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1842: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1843: 	}
1.441     www      1844: 
1.44      ng       1845: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1846:         # if this subroutine has been called once.
1.41      ng       1847: 	my %keyhash = ();
1.257     albertel 1848: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1849: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1850: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1851: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1852: 
1.257     albertel 1853: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1854: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1855: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1856: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1857: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1858: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1859: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1860: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1861: 	}
1.257     albertel 1862: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1863: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1864: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1865: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1866: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1867: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1868: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1869: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1870: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1871: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1872: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1873: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1874: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1875: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1876: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1877: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1878: 			&build_section_inputs().
1.326     albertel 1879: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1880: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1881: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1882: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1883: 	if ($env{'form.handgrade'} eq 'yes') {
                   1884: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1885: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1886: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1887: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1888: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1889: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1890: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1891: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1892: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1893: 	    }
1.123     ng       1894: 	}
1.41      ng       1895: 	
                   1896: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1897: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1898: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1899: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1900: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1901: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1902: 		'" />'."\n".
                   1903: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1904: 	    $cts++;
                   1905: 	}
                   1906: 	$request->print($prnmsg);
1.32      ng       1907: 
1.257     albertel 1908: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1909: #
                   1910: # Print out the keyword options line
                   1911: #
1.41      ng       1912: 	    $request->print(<<KEYWORDS);
1.38      ng       1913: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1914: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1915: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1916:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1917: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1918: KEYWORDS
1.88      www      1919: #
                   1920: # Load the other essays for similarity check
                   1921: #
1.324     albertel 1922:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1923: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1924: 	    $apath=&escape($apath);
1.88      www      1925: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1926: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1927:         }
                   1928:     }
1.44      ng       1929: 
1.441     www      1930: # This is where output for one specific student would start
                   1931:     my $bgcolor='#DDEEDD';
                   1932:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1933:     $request->print("\n\n".
                   1934:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1935: 
1.257     albertel 1936:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1937: 	my $mode;
1.257     albertel 1938: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1939: 	    $mode='both';
1.257     albertel 1940: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1941: 	    $mode='text';
1.257     albertel 1942: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1943: 	    $mode='answer';
                   1944: 	}
1.329     albertel 1945: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1946: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1947:     }
1.144     albertel 1948: 
1.257     albertel 1949:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1950:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1951: 
1.44      ng       1952:     # Display student info
1.41      ng       1953:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1954:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1955: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1956: 
1.257     albertel 1957:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1958:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1959: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1960: 
1.118     ng       1961:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1962:     my @col_fullnames;
1.56      matthew  1963:     my ($classlist,$fullname);
1.257     albertel 1964:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1965: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1966: 	for (keys (%$handgrade)) {
1.44      ng       1967: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1968: 					    '.maxcollaborators',
                   1969:                                             $symb,$udom,$uname);
                   1970: 	    next if ($ncol <= 0);
                   1971:             s/\_/\./g;
                   1972:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1973:             my @goodcollaborators = ();
                   1974:             my @badcollaborators  = ();
                   1975: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1976: 		$_ =~ s/[\$\^\(\)]//g;
                   1977: 		next if ($_ eq '');
1.80      ng       1978: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1979: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1980: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1981: 		# Doing this grep allows 'fuzzy' specification
                   1982: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1983: 		if (! scalar(@Matches)) {
                   1984: 		    push @badcollaborators,$_;
                   1985: 		} else {
                   1986: 		    push @goodcollaborators, @Matches;
                   1987: 		}
1.80      ng       1988: 	    }
1.86      ng       1989:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1990:                 $result.='<b>Collaborators: </b>';
1.86      ng       1991:                 foreach (@goodcollaborators) {
                   1992: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1993: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1994: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1995: 		}
1.57      matthew  1996:                 $result.='<br />'."\n";
1.150     albertel 1997: 		my ($part)=split(/\./,$_);
1.86      ng       1998: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1999: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2000: 		    "\n";
1.86      ng       2001: 	    }
                   2002: 	    if (scalar(@badcollaborators) > 0) {
                   2003: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2004: 		$result.='This student has submitted ';
                   2005: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2006: 		$result .= ': '.join(', ',@badcollaborators);
                   2007: 		$result .= '</td></tr></table>';
                   2008: 	    }         
                   2009: 	    if (scalar(@badcollaborators > $ncol)) {
                   2010: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2011: 		$result .= 'This student has submitted too many '.
                   2012: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2013: 		$result .= '</td></tr></table>';
                   2014: 	    }
1.41      ng       2015: 	}
                   2016:     }
1.44      ng       2017:     $request->print($result."\n");
1.33      ng       2018: 
1.44      ng       2019:     # print student answer/submission
                   2020:     # Options are (1) Handgaded submission only
                   2021:     #             (2) Last submission, includes submission that is not handgraded 
                   2022:     #                  (for multi-response type part)
                   2023:     #             (3) Last submission plus the parts info
                   2024:     #             (4) The whole record for this student
1.257     albertel 2025:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2026: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2027: 	my $lastsubonly=''.
                   2028: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2029: 	     $$timestamp)."</td></tr>\n";
                   2030: 	if ($$timestamp eq '') {
                   2031: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2032: 	} else {
                   2033: 	    my %seenparts;
1.375     albertel 2034: 	    my @part_response_id = &flatten_responseType($responseType);
                   2035: 	    foreach my $part (@part_response_id) {
1.393     albertel 2036: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2037: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2038: 
1.375     albertel 2039: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2040: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2041: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2042: 		    if (exists($seenparts{$partid})) { next; }
                   2043: 		    $seenparts{$partid}=1;
1.207     albertel 2044: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2045: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2046: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2047: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2048: 			'\');" target="_self">'.
1.257     albertel 2049: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2050: 		    $request->print($submitby);
                   2051: 		    next;
                   2052: 		}
                   2053: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2054: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2055: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2056: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2057: 			' )</span>&nbsp; &nbsp;'.
                   2058: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2059: 		    next;
                   2060: 		}
                   2061: 		foreach (@$string) {
                   2062: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2063: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2064: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2065: 		    # Similarity check
                   2066: 		    my $similar='';
1.257     albertel 2067: 		    if($env{'form.checkPlag'}){
1.151     albertel 2068: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2069: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2070: 			if ($osim) {
                   2071: 			    $osim=int($osim*100.0);
1.426     albertel 2072: 			    my %old_course_desc = 
                   2073: 				&Apache::lonnet::coursedescription($ocrsid,
                   2074: 								   {'one_time' => 1});
                   2075: 
                   2076: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2077: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2078: 				    $osim,
                   2079: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2080: 				    $oname,$odom,
1.426     albertel 2081: 				    $old_course_desc{'description'},
1.427     albertel 2082: 				    $old_course_desc{'num'},
1.426     albertel 2083: 				    $old_course_desc{'domain'}).
1.398     albertel 2084: 				'</span></h3><blockquote><i>'.
1.151     albertel 2085: 				&keywords_highlight($oessay).
                   2086: 				'</i></blockquote><hr />';
                   2087: 			}
1.150     albertel 2088: 		    }
1.151     albertel 2089: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2090: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2091: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2092: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2093: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2094: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2095: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2096: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2097: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2098: 			if (@$files) {
1.398     albertel 2099: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2100: 			    my $file_counter = 0;
1.313     banghart 2101: 			    foreach my $file (@$files) {
1.303     banghart 2102: 			        $file_counter ++;
1.232     albertel 2103: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2104: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2105: 			    }
1.236     albertel 2106: 			    $lastsubonly.='<br />';
1.41      ng       2107: 			}
1.151     albertel 2108: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2109: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2110: 					 $respid,\%record,$order);
                   2111: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2112: 		    }
                   2113: 		}
                   2114: 	    }
1.151     albertel 2115: 	}
                   2116: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2117: 	$request->print($lastsubonly);
1.257     albertel 2118:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2119: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2120: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2121:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2122: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2123: 								 $env{'request.course.id'},
1.44      ng       2124: 								 $last,'.submission',
                   2125: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2126:     }
1.120     ng       2127: 
1.121     ng       2128:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2129: 	.$udom.'" />'."\n");
1.41      ng       2130:     
1.44      ng       2131:     # return if view submission with no grading option
1.257     albertel 2132:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2133: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2134: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2135: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2136: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2137: 	if (($env{'form.command'} eq 'submission') || 
                   2138: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2139: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2140: 	}
1.180     albertel 2141: 	$request->print($toGrade);
1.41      ng       2142: 	return;
1.180     albertel 2143:     } else {
                   2144: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2145:     }
1.33      ng       2146: 
1.121     ng       2147:     # essay grading message center
1.257     albertel 2148:     if ($env{'form.handgrade'} eq 'yes') {
                   2149: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2150: 	my $msgfor = $givenn.' '.$lastname;
                   2151: 	if (scalar(@col_fullnames) > 0) {
                   2152: 	    my $lastone = pop @col_fullnames;
                   2153: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2154: 	}
                   2155: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2156: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2157: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2158: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2159: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2160: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2161: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2162: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2163: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2164: 	    '<br />&nbsp;('.
                   2165: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2166: 	$request->print($result);
1.118     ng       2167:     }
1.300     albertel 2168:     if ($perm{'vgr'}) {
1.297     www      2169: 	$request->print('<br />'.
1.300     albertel 2170: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2171: 						   $uname,$udom,'check'));
1.297     www      2172:     }
1.300     albertel 2173:     if ($perm{'opa'}) {
1.297     www      2174: 	$request->print('<br />'.
1.300     albertel 2175: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2176: 					 $uname,$udom,$symb,'check'));
1.297     www      2177:     }
1.41      ng       2178: 
                   2179:     my %seen = ();
                   2180:     my @partlist;
1.129     ng       2181:     my @gradePartRespid;
1.375     albertel 2182:     my @part_response_id = &flatten_responseType($responseType);
                   2183:     foreach my $part_response_id (@part_response_id) {
                   2184:     	my ($partid,$respid) = @{ $part_response_id };
                   2185: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2186: 	next if ($seen{$partid} > 0);
1.41      ng       2187: 	$seen{$partid}++;
1.393     albertel 2188: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2189: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2190: 	push @partlist,$partid;
1.129     ng       2191: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2192: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2193:     }
1.45      ng       2194:     $result='<input type="hidden" name="partlist'.$counter.
                   2195: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2196:     $result.='<input type="hidden" name="gradePartRespid'.
                   2197: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2198:     my $ctr = 0;
                   2199:     while ($ctr < scalar(@partlist)) {
                   2200: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2201: 	    $partlist[$ctr].'" />'."\n";
                   2202: 	$ctr++;
                   2203:     }
                   2204:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2205: 
1.441     www      2206: # Done with printing info for one student
                   2207: 
                   2208:     $request->print('</td></tr></table></p>');
                   2209: 
                   2210: 
1.41      ng       2211:     # print end of form
                   2212:     if ($counter == $total) {
1.297     www      2213: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2214: 	$endform.='<input type="button" value="Save & Next" '.
                   2215: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2216: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2217: 	my $ntstu ='<select name="NTSTU">'.
                   2218: 	    '<option>1</option><option>2</option>'.
                   2219: 	    '<option>3</option><option>5</option>'.
                   2220: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2221: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2222: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2223: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2224: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2225: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2226: 	    '<input type="button" value="Next" '.
1.417     albertel 2227: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2228: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2229:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2230:             "' name='increment' />";
1.45      ng       2231: 	$endform.='</td><tr></table></form>';
1.324     albertel 2232: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2233: 	$request->print($endform);
                   2234:     }
                   2235:     return '';
1.38      ng       2236: }
                   2237: 
1.44      ng       2238: #--- Retrieve the last submission for all the parts
1.38      ng       2239: sub get_last_submission {
1.119     ng       2240:     my ($returnhash)=@_;
1.46      ng       2241:     my (@string,$timestamp);
1.119     ng       2242:     if ($$returnhash{'version'}) {
1.46      ng       2243: 	my %lasthash=();
                   2244: 	my ($version);
1.119     ng       2245: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2246: 	    foreach my $key (sort(split(/\:/,
                   2247: 					$$returnhash{$version.':keys'}))) {
                   2248: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2249: 		$timestamp = 
                   2250: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2251: 	    }
                   2252: 	}
1.397     albertel 2253: 	foreach my $key (keys(%lasthash)) {
                   2254: 	    next if ($key !~ /\.submission$/);
                   2255: 
                   2256: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2257: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2258: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2259: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2260: 	}
                   2261:     }
1.397     albertel 2262:     if (!@string) {
                   2263: 	$string[0] =
1.398     albertel 2264: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2265:     }
                   2266:     return (\@string,\$timestamp);
1.38      ng       2267: }
1.35      ng       2268: 
1.44      ng       2269: #--- High light keywords, with style choosen by user.
1.38      ng       2270: sub keywords_highlight {
1.44      ng       2271:     my $string    = shift;
1.257     albertel 2272:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2273:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2274:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2275:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2276:     foreach my $keyword (@keylist) {
                   2277: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2278:     }
                   2279:     return $string;
1.38      ng       2280: }
1.36      ng       2281: 
1.44      ng       2282: #--- Called from submission routine
1.38      ng       2283: sub processHandGrade {
1.41      ng       2284:     my ($request) = shift;
1.324     albertel 2285:     my $symb   = &get_symb($request);
                   2286:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2287:     my $button = $env{'form.gradeOpt'};
                   2288:     my $ngrade = $env{'form.NCT'};
                   2289:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2290:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2291:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2292: 
1.44      ng       2293:     if ($button eq 'Save & Next') {
                   2294: 	my $ctr = 0;
                   2295: 	while ($ctr < $ngrade) {
1.257     albertel 2296: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2297: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2298: 	    if ($errorflag eq 'no_score') {
                   2299: 		$ctr++;
                   2300: 		next;
                   2301: 	    }
1.104     albertel 2302: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2303: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2304: 		$ctr++;
                   2305: 		next;
                   2306: 	    }
1.257     albertel 2307: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2308: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2309: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2310:             my ($feedurl,$showsymb) =
                   2311: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2312: 	    my $messagetail;
1.62      albertel 2313: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2314: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2315: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2316: 		$subject.=' ['.$restitle.']';
1.44      ng       2317: 		my (@msgnum) = split(/,/,$includemsg);
                   2318: 		foreach (@msgnum) {
1.257     albertel 2319: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2320: 		}
1.80      ng       2321: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2322: 		if ($env{'form.withgrades'.$ctr}) {
                   2323: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2324: 		    $messagetail = " for <a href=\"".
1.418     albertel 2325: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2326: 		}
                   2327: 		$msgstatus = 
                   2328:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2329: 						     $message.$messagetail,
1.418     albertel 2330:                                                      undef,$feedurl,undef,
1.386     raeburn  2331:                                                      undef,undef,$showsymb,
                   2332:                                                      $restitle);
                   2333: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2334: 				$msgstatus);
1.44      ng       2335: 	    }
1.257     albertel 2336: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2337: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2338: 		foreach my $collabstr (@collabstrs) {
                   2339: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2340: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2341: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2342: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2343: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2344: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2345: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2346: 			    next;
1.418     albertel 2347: 			} elsif ($message ne '') {
                   2348: 			    my ($baseurl,$showsymb) = 
                   2349: 				&get_feedurl_and_symb($symb,$collaborator,
                   2350: 						      $udom);
                   2351: 			    if ($env{'form.withgrades'.$ctr}) {
                   2352: 				$messagetail = " for <a href=\"".
1.386     raeburn  2353:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2354: 			    }
1.418     albertel 2355: 			    $msgstatus = 
                   2356: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2357: 			}
1.44      ng       2358: 		    }
                   2359: 		}
                   2360: 	    }
                   2361: 	    $ctr++;
                   2362: 	}
                   2363:     }
                   2364: 
1.257     albertel 2365:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2366: 	# Keywords sorted in alphabatical order
1.257     albertel 2367: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2368: 	my %keyhash = ();
1.257     albertel 2369: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2370: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2371: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2372: 	$env{'form.keywords'} = join(' ',@keywords);
                   2373: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2374: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2375: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2376: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2377: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2378: 
                   2379: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2380: 	# New messages are saved in env for the next student.
1.119     ng       2381: 	# All messages are saved in nohist_handgrade.db
                   2382: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2383: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2384: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2385: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2386: 		$idx++;
                   2387: 	    }
                   2388: 	    $ctr++;
1.41      ng       2389: 	}
1.119     ng       2390: 	$ctr = 0;
                   2391: 	while ($ctr < $ngrade) {
1.257     albertel 2392: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2393: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2394: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2395: 		$idx++;
                   2396: 	    }
                   2397: 	    $ctr++;
1.41      ng       2398: 	}
1.257     albertel 2399: 	$env{'form.savemsgN'} = --$idx;
                   2400: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2401: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2402: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2403:     }
1.44      ng       2404:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2405:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2406:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2407: 	my ($ctr,$total) = (0,0);
                   2408: 	while ($ctr < $ngrade) {
1.257     albertel 2409: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2410: 	    $ctr++;
                   2411: 	}
1.257     albertel 2412: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2413: 	$ctr = 0;
                   2414: 	while ($ctr < $total) {
1.257     albertel 2415: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2416: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2417: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2418: 	    &submission($request,$ctr,$total-1);
1.41      ng       2419: 	    $ctr++;
                   2420: 	}
                   2421: 	return '';
                   2422:     }
1.36      ng       2423: 
1.121     ng       2424: # Go directly to grade student - from submission or link from chart page
1.120     ng       2425:     if ($button eq 'Grade Student') {
1.324     albertel 2426: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2427: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2428: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2429: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2430: 	&submission($request,0,0);
                   2431: 	return '';
                   2432:     }
                   2433: 
1.44      ng       2434:     # Get the next/previous one or group of students
1.257     albertel 2435:     my $firststu = $env{'form.unamedom0'};
                   2436:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2437:     my $ctr = 2;
1.41      ng       2438:     while ($laststu eq '') {
1.257     albertel 2439: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2440: 	$ctr++;
                   2441: 	$laststu = $firststu if ($ctr > $ngrade);
                   2442:     }
1.44      ng       2443: 
1.41      ng       2444:     my (@parsedlist,@nextlist);
                   2445:     my ($nextflg) = 0;
1.294     albertel 2446:     foreach (sort 
                   2447: 	     {
                   2448: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2449: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2450: 		 }
                   2451: 		 return $a cmp $b;
                   2452: 	     } (keys(%$fullname))) {
1.41      ng       2453: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2454: 	    push @parsedlist,$_;
                   2455: 	}
                   2456: 	$nextflg = 1 if ($_ eq $laststu);
                   2457: 	if ($button eq 'Previous') {
                   2458: 	    last if ($_ eq $firststu);
                   2459: 	    push @parsedlist,$_;
                   2460: 	}
                   2461:     }
                   2462:     $ctr = 0;
                   2463:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2464:     my ($partlist) = &response_type($symb);
1.41      ng       2465:     foreach my $student (@parsedlist) {
1.257     albertel 2466: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2467: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2468: 	
                   2469: 	if ($submitonly eq 'queued') {
                   2470: 	    my %queue_status = 
                   2471: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2472: 							$udom,$uname);
                   2473: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2474: 	}
                   2475: 
1.156     albertel 2476: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2477: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2478: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2479: 	    my $submitted = 0;
1.248     albertel 2480: 	    my $ungraded = 0;
                   2481: 	    my $incorrect = 0;
1.145     albertel 2482: 	    foreach (keys(%status)) {
                   2483: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2484: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2485: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2486: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2487: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2488: 		    $submitted = 0;
                   2489: 		}
1.41      ng       2490: 	    }
1.156     albertel 2491: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2492: 				     $submitonly eq 'incorrect' ||
                   2493: 				     $submitonly eq 'graded'));
1.248     albertel 2494: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2495: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2496: 	}
                   2497: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2498: 	last if ($ctr == $ntstu);
1.41      ng       2499: 	$ctr++;
                   2500:     }
1.36      ng       2501: 
1.41      ng       2502:     $ctr = 0;
                   2503:     my $total = scalar(@nextlist)-1;
1.39      ng       2504: 
1.41      ng       2505:     foreach (sort @nextlist) {
                   2506: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2507: 	$env{'form.student'}  = $uname;
                   2508: 	$env{'form.userdom'}  = $udom;
                   2509: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2510: 	&submission($request,$ctr,$total);
                   2511: 	$ctr++;
                   2512:     }
                   2513:     if ($total < 0) {
1.398     albertel 2514: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2515: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2516: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2517: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2518: 	$request->print($the_end);
                   2519:     }
                   2520:     return '';
1.38      ng       2521: }
1.36      ng       2522: 
1.44      ng       2523: #---- Save the score and award for each student, if changed
1.38      ng       2524: sub saveHandGrade {
1.324     albertel 2525:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2526:     my @version_parts;
1.104     albertel 2527:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2528: 					   $env{'request.course.id'});
1.104     albertel 2529:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2530:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2531:     my @parts_graded;
1.77      ng       2532:     my %newrecord  = ();
                   2533:     my ($pts,$wgt) = ('','');
1.269     raeburn  2534:     my %aggregate = ();
                   2535:     my $aggregateflag = 0;
1.301     albertel 2536:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2537:     foreach my $new_part (@parts) {
1.337     banghart 2538: 	#collaborator ($submi may vary for different parts
1.259     banghart 2539: 	if ($submitter && $new_part ne $part) { next; }
                   2540: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2541: 	if ($dropMenu eq 'excused') {
1.259     banghart 2542: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2543: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2544: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2545: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2546: 		}
1.364     banghart 2547: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2548: 	    }
1.125     ng       2549: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2550: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2551: 	    foreach my $key (keys (%record)) {
1.259     banghart 2552: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2553: 	    }
1.259     banghart 2554: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2555: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2556:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2557: 
                   2558:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2559: 					       [$new_part]);
                   2560:             my $aggtries =$totaltries;
1.269     raeburn  2561:             if ($last_resets{$new_part}) {
1.270     albertel 2562:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2563: 					   $new_part);
1.269     raeburn  2564:             }
1.270     albertel 2565: 
                   2566:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2567:             if ($aggtries > 0) {
1.327     albertel 2568:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2569:                 $aggregateflag = 1;
                   2570:             }
1.125     ng       2571: 	} elsif ($dropMenu eq '') {
1.259     banghart 2572: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2573: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2574: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2575: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2576: 		next;
                   2577: 	    }
1.259     banghart 2578: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2579: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2580: 	    my $partial= $pts/$wgt;
1.259     banghart 2581: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2582: 		#do not update score for part if not changed.
1.346     banghart 2583:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2584: 		next;
1.251     banghart 2585: 	    } else {
1.259     banghart 2586: 	        push @parts_graded, $new_part;
1.153     albertel 2587: 	    }
1.259     banghart 2588: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2589: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2590: 	    }
1.259     banghart 2591: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2592: 	    if ($partial == 0) {
1.153     albertel 2593: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2594: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2595: 		}
1.41      ng       2596: 	    } else {
1.153     albertel 2597: 		if ($record{$reckey} ne 'correct_by_override') {
                   2598: 		    $newrecord{$reckey} = 'correct_by_override';
                   2599: 		}
                   2600: 	    }	    
                   2601: 	    if ($submitter && 
1.259     banghart 2602: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2603: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2604: 	    }
1.259     banghart 2605: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2606: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2607: 	}
1.259     banghart 2608: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2609: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2610: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2611: 	        $dropMenu eq 'reset status')
                   2612: 	   {
1.342     banghart 2613: 	    push (@version_parts,$new_part);
1.259     banghart 2614: 	}
1.41      ng       2615:     }
1.301     albertel 2616:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2617:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2618: 
1.344     albertel 2619:     if (%newrecord) {
                   2620:         if (@version_parts) {
1.364     banghart 2621:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2622:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2623: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2624: 	    foreach my $new_part (@version_parts) {
                   2625: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2626: 				$new_part,\%newrecord);
                   2627: 	    }
1.259     banghart 2628:         }
1.44      ng       2629: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2630: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2631: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2632: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2633:     }
1.269     raeburn  2634:     if ($aggregateflag) {
                   2635:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2636: 			      $cdom,$cnum);
1.269     raeburn  2637:     }
1.301     albertel 2638:     return ('',$pts,$wgt);
1.36      ng       2639: }
1.322     albertel 2640: 
1.380     albertel 2641: sub check_and_remove_from_queue {
                   2642:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2643:     my @ungraded_parts;
                   2644:     foreach my $part (@{$parts}) {
                   2645: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2646: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2647: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2648: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2649: 		) {
                   2650: 	    push(@ungraded_parts, $part);
                   2651: 	}
                   2652:     }
                   2653:     if ( !@ungraded_parts ) {
                   2654: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2655: 					       $cnum,$domain,$stuname);
                   2656:     }
                   2657: }
                   2658: 
1.337     banghart 2659: sub handback_files {
                   2660:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2661:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2662:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2663: 
                   2664:     my @part_response_id = &flatten_responseType($responseType);
                   2665:     foreach my $part_response_id (@part_response_id) {
                   2666:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2667: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2668:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2669:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2670:                 my $file_counter = 1;
1.367     albertel 2671: 		my $file_msg;
1.337     banghart 2672:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2673:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2674:                     my ($directory,$answer_file) = 
                   2675:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2676:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2677: 		        &file_name_version_ext($answer_file);
1.355     banghart 2678: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2679: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2680: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2681:                     # fix file name
                   2682:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2683:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2684:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2685:             	                                $save_file_name);
1.337     banghart 2686:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2687:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2688:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2689:                     } else {
1.360     banghart 2690:                         # mark the file as read only
                   2691:                         my @files = ($save_file_name);
1.372     albertel 2692:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2693:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2694: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2695: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2696: 			}
                   2697:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2698: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2699: 
1.337     banghart 2700:                     }
                   2701:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2702:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2703:                     $file_counter++;
                   2704:                 }
1.367     albertel 2705: 		my $subject = "File Handed Back by Instructor ";
                   2706: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2707: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2708: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2709: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2710: 		my ($feedurl,$showsymb) = 
                   2711: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2712:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2713: 		my $msgstatus = 
                   2714:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2715: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2716:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2717:             }
                   2718:         }
1.338     banghart 2719:     return;
1.337     banghart 2720: }
                   2721: 
1.418     albertel 2722: sub get_feedurl_and_symb {
                   2723:     my ($symb,$uname,$udom) = @_;
                   2724:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2725:     $url = &Apache::lonnet::clutter($url);
                   2726:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2727: 					$symb,$udom,$uname);
                   2728:     if ($encrypturl =~ /^yes$/i) {
                   2729: 	&Apache::lonenc::encrypted(\$url,1);
                   2730: 	&Apache::lonenc::encrypted(\$symb,1);
                   2731:     }
                   2732:     return ($url,$symb);
                   2733: }
                   2734: 
1.313     banghart 2735: sub get_submitted_files {
                   2736:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2737:     my @files;
                   2738:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2739:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2740:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2741:     	    push(@files,$file_url.$file);
                   2742:         }
                   2743:     }
                   2744:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2745:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2746:     }
                   2747:     return (\@files);
                   2748: }
1.322     albertel 2749: 
1.269     raeburn  2750: # ----------- Provides number of tries since last reset.
                   2751: sub get_num_tries {
                   2752:     my ($record,$last_reset,$part) = @_;
                   2753:     my $timestamp = '';
                   2754:     my $num_tries = 0;
                   2755:     if ($$record{'version'}) {
                   2756:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2757:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2758:                 $timestamp = $$record{$version.':timestamp'};
                   2759:                 if ($timestamp > $last_reset) {
                   2760:                     $num_tries ++;
                   2761:                 } else {
                   2762:                     last;
                   2763:                 }
                   2764:             }
                   2765:         }
                   2766:     }
                   2767:     return $num_tries;
                   2768: }
                   2769: 
                   2770: # ----------- Determine decrements required in aggregate totals 
                   2771: sub decrement_aggs {
                   2772:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2773:     my %decrement = (
                   2774:                         attempts => 0,
                   2775:                         users => 0,
                   2776:                         correct => 0
                   2777:                     );
                   2778:     $decrement{'attempts'} = $aggtries;
                   2779:     if ($solvedstatus =~ /^correct/) {
                   2780:         $decrement{'correct'} = 1;
                   2781:     }
                   2782:     if ($aggtries == $totaltries) {
                   2783:         $decrement{'users'} = 1;
                   2784:     }
                   2785:     foreach my $type (keys (%decrement)) {
                   2786:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2787:     }
                   2788:     return;
                   2789: }
                   2790: 
                   2791: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2792: sub get_last_resets {
1.270     albertel 2793:     my ($symb,$courseid,$partids) =@_;
                   2794:     my %last_resets;
1.269     raeburn  2795:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2796:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2797:     my @keys;
                   2798:     foreach my $part (@{$partids}) {
                   2799: 	push(@keys,"$symb\0$part\0resettime");
                   2800:     }
                   2801:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2802: 				     $cdom,$cname);
                   2803:     foreach my $part (@{$partids}) {
                   2804: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2805:     }
1.270     albertel 2806:     return %last_resets;
1.269     raeburn  2807: }
                   2808: 
1.251     banghart 2809: # ----------- Handles creating versions for portfolio files as answers
                   2810: sub version_portfiles {
1.343     banghart 2811:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2812:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2813:     my @returned_keys;
1.255     banghart 2814:     my $parts = join('|', @$parts_graded);
1.359     www      2815:     my $portfolio_root = &propath($domain,$stu_name).
                   2816: 	'/userfiles/portfolio';
1.277     albertel 2817:     foreach my $key (keys(%$record)) {
1.259     banghart 2818:         my $new_portfiles;
1.263     banghart 2819:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2820:             my @versioned_portfiles;
1.367     albertel 2821:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2822:             foreach my $file (@portfiles) {
1.306     banghart 2823:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2824:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2825: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2826: 		    &file_name_version_ext($answer_file);
1.306     banghart 2827:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2828:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2829:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2830:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2831:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2832:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2833:                         [$directory.$new_answer],
1.306     banghart 2834:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2835:                 }
1.252     banghart 2836:             }
1.343     banghart 2837:             $$record{$key} = join(',',@versioned_portfiles);
                   2838:             push(@returned_keys,$key);
1.251     banghart 2839:         }
                   2840:     } 
1.343     banghart 2841:     return (@returned_keys);   
1.305     banghart 2842: }
                   2843: 
1.307     banghart 2844: sub get_next_version {
1.341     banghart 2845:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2846:     my $version;
                   2847:     foreach my $row (@$dir_list) {
                   2848:         my ($file) = split(/\&/,$row,2);
                   2849:         my ($file_name,$file_version,$file_ext) =
                   2850: 	    &file_name_version_ext($file);
                   2851:         if (($file_name eq $answer_name) && 
                   2852: 	    ($file_ext eq $answer_ext)) {
                   2853:                 # gets here if filename and extension match, regardless of version
                   2854:                 if ($file_version ne '') {
                   2855:                 # a versioned file is found  so save it for later
                   2856:                 if ($file_version > $version) {
                   2857: 		    $version = $file_version;
                   2858: 	        }
                   2859:             }
                   2860:         }
                   2861:     } 
                   2862:     $version ++;
                   2863:     return($version);
                   2864: }
                   2865: 
1.305     banghart 2866: sub version_selected_portfile {
1.306     banghart 2867:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2868:     my ($answer_name,$answer_ver,$answer_ext) =
                   2869:         &file_name_version_ext($file_name);
                   2870:     my $new_answer;
                   2871:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2872:     if($env{'form.copy'} eq '-1') {
                   2873:         $new_answer = 'problem getting file';
                   2874:     } else {
                   2875:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2876:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2877:                             $stu_name,$domain,'copy',
                   2878: 		        '/portfolio'.$directory.$new_answer);
                   2879:     }    
                   2880:     return ($new_answer);
1.251     banghart 2881: }
                   2882: 
1.304     albertel 2883: sub file_name_version_ext {
                   2884:     my ($file)=@_;
                   2885:     my @file_parts = split(/\./, $file);
                   2886:     my ($name,$version,$ext);
                   2887:     if (@file_parts > 1) {
                   2888: 	$ext=pop(@file_parts);
                   2889: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2890: 	    $version=pop(@file_parts);
                   2891: 	}
                   2892: 	$name=join('.',@file_parts);
                   2893:     } else {
                   2894: 	$name=join('.',@file_parts);
                   2895:     }
                   2896:     return($name,$version,$ext);
                   2897: }
                   2898: 
1.44      ng       2899: #--------------------------------------------------------------------------------------
                   2900: #
                   2901: #-------------------------- Next few routines handles grading by section or whole class
                   2902: #
                   2903: #--- Javascript to handle grading by section or whole class
1.42      ng       2904: sub viewgrades_js {
                   2905:     my ($request) = shift;
                   2906: 
1.41      ng       2907:     $request->print(<<VIEWJAVASCRIPT);
                   2908: <script type="text/javascript" language="javascript">
1.45      ng       2909:    function writePoint(partid,weight,point) {
1.125     ng       2910: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2911: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2912: 	if (point == "textval") {
1.125     ng       2913: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2914: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2915: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2916: 		var resetbox = false;
                   2917: 		for (var i=0; i<radioButton.length; i++) {
                   2918: 		    if (radioButton[i].checked) {
                   2919: 			textbox.value = i;
                   2920: 			resetbox = true;
                   2921: 		    }
                   2922: 		}
                   2923: 		if (!resetbox) {
                   2924: 		    textbox.value = "";
                   2925: 		}
                   2926: 		return;
                   2927: 	    }
1.109     matthew  2928: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2929: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2930: 				   ") greater than the weight for the part. Accept?");
                   2931: 		if (resp == false) {
                   2932: 		    textbox.value = "";
                   2933: 		    return;
                   2934: 		}
                   2935: 	    }
1.42      ng       2936: 	    for (var i=0; i<radioButton.length; i++) {
                   2937: 		radioButton[i].checked=false;
1.109     matthew  2938: 		if (parseFloat(point) == i) {
1.42      ng       2939: 		    radioButton[i].checked=true;
                   2940: 		}
                   2941: 	    }
1.41      ng       2942: 
1.42      ng       2943: 	} else {
1.125     ng       2944: 	    textbox.value = parseFloat(point);
1.42      ng       2945: 	}
1.41      ng       2946: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2947: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2948: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2949: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2950: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2951: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2952: 	    if (saveval != "correct") {
                   2953: 		scorename.value = point;
1.43      ng       2954: 		if (selname[0].selected != true) {
                   2955: 		    selname[0].selected = true;
                   2956: 		}
1.42      ng       2957: 	    }
                   2958: 	}
1.125     ng       2959: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2960:     }
                   2961: 
                   2962:     function writeRadText(partid,weight) {
1.125     ng       2963: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2964: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2965:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2966: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2967: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2968: 	    for (var i=0; i<radioButton.length; i++) {
                   2969: 		radioButton[i].checked=false;
                   2970: 
                   2971: 	    }
                   2972: 	    textbox.value = "";
                   2973: 
                   2974: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2975: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2976: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2977: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2978: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2979: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2980: 		if ((saveval != "correct") || override) {
1.42      ng       2981: 		    scorename.value = "";
1.125     ng       2982: 		    if (selval[1].selected) {
                   2983: 			selname[1].selected = true;
                   2984: 		    } else {
                   2985: 			selname[2].selected = true;
                   2986: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2987: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2988: 		    }
1.42      ng       2989: 		}
                   2990: 	    }
1.43      ng       2991: 	} else {
                   2992: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2993: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2994: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2995: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2996: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2997: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2998: 		if ((saveval != "correct") || override) {
1.125     ng       2999: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3000: 		    selname[0].selected = true;
                   3001: 		}
                   3002: 	    }
                   3003: 	}	    
1.42      ng       3004:     }
                   3005: 
                   3006:     function changeSelect(partid,user) {
1.125     ng       3007: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3008: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3009: 	var point  = textbox.value;
1.125     ng       3010: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3011: 
1.109     matthew  3012: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3013: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3014: 	    textbox.value = "";
                   3015: 	    return;
                   3016: 	}
1.109     matthew  3017: 	if (parseFloat(point) > parseFloat(weight)) {
                   3018: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3019: 			       ") greater than the weight of the part. Accept?");
                   3020: 	    if (resp == false) {
                   3021: 		textbox.value = "";
                   3022: 		return;
                   3023: 	    }
                   3024: 	}
1.42      ng       3025: 	selval[0].selected = true;
                   3026:     }
                   3027: 
                   3028:     function changeOneScore(partid,user) {
1.125     ng       3029: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3030: 	if (selval[1].selected || selval[2].selected) {
                   3031: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3032: 	    if (selval[2].selected) {
                   3033: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3034: 	    }
1.269     raeburn  3035:         }
1.42      ng       3036:     }
                   3037: 
                   3038:     function resetEntry(numpart) {
                   3039: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3040: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3041: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3042: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3043: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3044: 	    for (var i=0; i<radioButton.length; i++) {
                   3045: 		radioButton[i].checked=false;
                   3046: 
                   3047: 	    }
                   3048: 	    textbox.value = "";
                   3049: 	    selval[0].selected = true;
                   3050: 
                   3051: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3052: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3053: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3054: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3055: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3056: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3057: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3058: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3059: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3060: 		if (saveselval == "excused") {
1.43      ng       3061: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3062: 		} else {
1.43      ng       3063: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3064: 		}
                   3065: 	    }
1.41      ng       3066: 	}
1.42      ng       3067:     }
                   3068: 
1.41      ng       3069: </script>
                   3070: VIEWJAVASCRIPT
1.42      ng       3071: }
                   3072: 
1.44      ng       3073: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3074: sub viewgrades {
                   3075:     my ($request) = shift;
                   3076:     &viewgrades_js($request);
1.41      ng       3077: 
1.324     albertel 3078:     my ($symb) = &get_symb($request);
1.168     albertel 3079:     #need to make sure we have the correct data for later EXT calls, 
                   3080:     #thus invalidate the cache
                   3081:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3082:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3083:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3084:     &Apache::lonnet::clear_EXT_cache_status();
                   3085: 
1.398     albertel 3086:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3087:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3088: 
                   3089:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3090:     $result.=&jscriptNform($symb);
1.41      ng       3091: 
1.44      ng       3092:     #beginning of class grading form
1.442     banghart 3093:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3094:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3095: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3096: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3097: 	&build_section_inputs().
1.257     albertel 3098: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3099: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3100: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3101: 
1.126     ng       3102:     my $sectionClass;
1.430     banghart 3103:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3104:     if ($env{'form.section'} eq 'all') {
1.126     ng       3105: 	$sectionClass='Class </h3>';
1.257     albertel 3106:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3107: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3108:     } else {
1.431     banghart 3109: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3110:     }
1.431     banghart 3111:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3112:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3113: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3114:     #radio buttons/text box for assigning points for a section or class.
                   3115:     #handles different parts of a problem
1.375     albertel 3116:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3117:     my %weight = ();
                   3118:     my $ctsparts = 0;
1.41      ng       3119:     $result.='<table border="0">';
1.45      ng       3120:     my %seen = ();
1.375     albertel 3121:     my @part_response_id = &flatten_responseType($responseType);
                   3122:     foreach my $part_response_id (@part_response_id) {
                   3123:     	my ($partid,$respid) = @{ $part_response_id };
                   3124: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3125: 	next if $seen{$partid};
                   3126: 	$seen{$partid}++;
1.375     albertel 3127: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3128: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3129: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3130: 
1.44      ng       3131: 	$result.='<input type="hidden" name="partid_'.
                   3132: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3133: 	$result.='<input type="hidden" name="weight_'.
                   3134: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3135: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3136: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3137: 	$result.='<table border="0"><tr>';  
1.41      ng       3138: 	my $ctr = 0;
1.42      ng       3139: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3140: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3141: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3142: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3143: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3144: 	    $ctr++;
                   3145: 	}
                   3146: 	$result.='</tr></table>';
1.44      ng       3147: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3148: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3149: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3150: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3151: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3152: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3153: 		$weight{$partid}.')"> '.
1.401     albertel 3154: 	    '<option selected="selected"> </option>'.
1.125     ng       3155: 	    '<option>excused</option>'.
1.265     www      3156: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3157:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3158: 	$ctsparts++;
1.41      ng       3159:     }
1.52      albertel 3160:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3161: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3162:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3163: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3164: 
1.44      ng       3165:     #table listing all the students in a section/class
                   3166:     #header of table
1.126     ng       3167:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3168:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3169: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3170: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3171:     my (@parts) = sort(&getpartlist($symb));
                   3172:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3173:     my @partids = ();
1.41      ng       3174:     foreach my $part (@parts) {
                   3175: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3176: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3177: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3178: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3179:         push(@partids, $partid);
1.324     albertel 3180: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3181: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3182: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3183: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3184: 	    next;
1.207     albertel 3185: 	} else {
                   3186: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3187: 	}
1.53      albertel 3188: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3189: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3190:     }
                   3191:     $result.='</tr>';
1.44      ng       3192: 
1.270     albertel 3193:     my %last_resets = 
                   3194: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3195: 
1.41      ng       3196:     #get info for each student
1.44      ng       3197:     #list all the students - with points and grade status
1.257     albertel 3198:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3199:     my $ctr = 0;
1.294     albertel 3200:     foreach (sort 
                   3201: 	     {
                   3202: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3203: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3204: 		 }
                   3205: 		 return $a cmp $b;
                   3206: 	     } (keys(%$fullname))) {
1.126     ng       3207: 	$ctr++;
1.324     albertel 3208: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3209: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3210:     }
                   3211:     $result.='</table></td></tr></table>';
                   3212:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3213:     $result.='<input type="button" value="Save" '.
1.417     albertel 3214: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3215:     if (scalar(%$fullname) eq 0) {
                   3216: 	my $colspan=3+scalar(@parts);
1.433     banghart 3217: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3218:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3219: 	$result='<span class="LC_warning">'.
                   3220: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3221: 	        $section_display, $stu_status).
1.433     banghart 3222: 	    '</span>';
1.96      albertel 3223:     }
1.324     albertel 3224:     $result.=&show_grading_menu_form($symb);
1.41      ng       3225:     return $result;
                   3226: }
                   3227: 
1.44      ng       3228: #--- call by previous routine to display each student
1.41      ng       3229: sub viewstudentgrade {
1.324     albertel 3230:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3231:     my ($uname,$udom) = split(/:/,$student);
                   3232:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3233:     my %aggregates = (); 
1.233     albertel 3234:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3235: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3236: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3237: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3238: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3239: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3240:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3241:     foreach my $apart (@$parts) {
                   3242: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3243: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3244:         $result.='<td align="center">';
1.269     raeburn  3245:         my ($aggtries,$totaltries);
                   3246:         unless (exists($aggregates{$part})) {
1.270     albertel 3247: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3248: 
                   3249: 	    $aggtries = $totaltries;
1.269     raeburn  3250:             if ($$last_resets{$part}) {  
1.270     albertel 3251:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3252: 					   $part);
                   3253:             }
1.269     raeburn  3254:             $result.='<input type="hidden" name="'.
                   3255:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3256:             $result.='<input type="hidden" name="'.
                   3257:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3258:             $aggregates{$part} = 1;
                   3259:         }
1.41      ng       3260: 	if ($type eq 'awarded') {
1.320     albertel 3261: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3262: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3263: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3264: 	    $result.='<input type="text" name="'.
1.89      albertel 3265: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3266: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3267: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3268: 	} elsif ($type eq 'solved') {
                   3269: 	    my ($status,$foo)=split(/_/,$score,2);
                   3270: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3271: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3272: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3273: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3274: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3275: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3276: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3277: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3278: 	    $result.='<option>reset status</option>';
1.126     ng       3279: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3280: 	} else {
                   3281: 	    $result.='<input type="hidden" name="'.
                   3282: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3283: 		    "\n";
1.233     albertel 3284: 	    $result.='<input type="text" name="'.
1.122     ng       3285: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3286: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3287: 	}
                   3288:     }
                   3289:     $result.='</tr>';
                   3290:     return $result;
1.38      ng       3291: }
                   3292: 
1.44      ng       3293: #--- change scores for all the students in a section/class
                   3294: #    record does not get update if unchanged
1.38      ng       3295: sub editgrades {
1.41      ng       3296:     my ($request) = @_;
                   3297: 
1.324     albertel 3298:     my $symb=&get_symb($request);
1.433     banghart 3299:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3300:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3301:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3302:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3303: 
1.44      ng       3304:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3305:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3306: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3307: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3308: 
                   3309:     my %scoreptr = (
                   3310: 		    'correct'  =>'correct_by_override',
                   3311: 		    'incorrect'=>'incorrect_by_override',
                   3312: 		    'excused'  =>'excused',
                   3313: 		    'ungraded' =>'ungraded_attempted',
                   3314: 		    'nothing'  => '',
                   3315: 		    );
1.257     albertel 3316:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3317: 
1.44      ng       3318:     my (@partid);
                   3319:     my %weight = ();
1.54      albertel 3320:     my %columns = ();
1.44      ng       3321:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3322: 
1.324     albertel 3323:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3324:     my $header;
1.257     albertel 3325:     while ($ctr < $env{'form.totalparts'}) {
                   3326: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3327: 	push @partid,$partid;
1.257     albertel 3328: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3329: 	$ctr++;
1.54      albertel 3330:     }
1.324     albertel 3331:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3332:     foreach my $partid (@partid) {
                   3333: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3334: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3335: 	$columns{$partid}=2;
                   3336: 	foreach my $stores (@parts) {
                   3337: 	    my ($part,$type) = &split_part_type($stores);
                   3338: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3339: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3340: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3341: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3342: 	    $display =~ s/Number of Attempts/Tries/;
                   3343: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3344: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3345: 	    $columns{$partid}+=2;
                   3346: 	}
                   3347:     }
                   3348:     foreach my $partid (@partid) {
1.324     albertel 3349: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3350: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3351: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3352: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3353: 
1.44      ng       3354:     }
                   3355:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3356:     $result .= $header;
1.44      ng       3357:     $result .= '</tr>'."\n";
1.93      albertel 3358:     my $noupdate;
1.126     ng       3359:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3360:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3361: 	my $line;
1.257     albertel 3362: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3363: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3364: 	my %newrecord;
                   3365: 	my $updateflag = 0;
1.281     albertel 3366: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3367: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3368: 	if (!&canmodify($usec)) {
1.126     ng       3369: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3370: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3371: 	    next;
                   3372: 	}
1.269     raeburn  3373:         my %aggregate = ();
                   3374:         my $aggregateflag = 0;
1.281     albertel 3375: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3376: 	foreach (@partid) {
1.257     albertel 3377: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3378: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3379: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3380: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3381: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3382: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3383: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3384: 	    my $score;
                   3385: 	    if ($partial eq '') {
1.257     albertel 3386: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3387: 	    } elsif ($partial > 0) {
                   3388: 		$score = 'correct_by_override';
                   3389: 	    } elsif ($partial == 0) {
                   3390: 		$score = 'incorrect_by_override';
                   3391: 	    }
1.257     albertel 3392: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3393: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3394: 
1.292     albertel 3395: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3396: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3397: 	    if ($dropMenu eq 'reset status' &&
                   3398: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3399: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3400: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3401: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3402: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3403: 		$updateflag = 1;
1.269     raeburn  3404:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3405:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3406:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3407:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3408:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3409:                     $aggregateflag = 1;
                   3410:                 }
1.139     albertel 3411: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3412: 		$updateflag = 1;
                   3413: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3414: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3415: 		$rec_update++;
1.125     ng       3416: 	    }
                   3417: 
1.93      albertel 3418: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3419: 		'<td align="center">'.$awarded.
                   3420: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3421: 
1.54      albertel 3422: 
                   3423: 	    my $partid=$_;
                   3424: 	    foreach my $stores (@parts) {
                   3425: 		my ($part,$type) = &split_part_type($stores);
                   3426: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3427: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3428: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3429: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3430: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3431: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3432: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3433: 		    $updateflag=1;
                   3434: 		}
1.93      albertel 3435: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3436: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3437: 	    }
1.44      ng       3438: 	}
1.93      albertel 3439: 	$line.='</tr>'."\n";
1.301     albertel 3440: 
                   3441: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3442: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3443: 
1.44      ng       3444: 	if ($updateflag) {
                   3445: 	    $count++;
1.257     albertel 3446: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3447: 				    $udom,$uname);
1.301     albertel 3448: 
                   3449: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3450: 					      $cnum,$udom,$uname)) {
                   3451: 		# need to figure out if should be in queue.
                   3452: 		my %record =  
                   3453: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3454: 					     $udom,$uname);
                   3455: 		my $all_graded = 1;
                   3456: 		my $none_graded = 1;
                   3457: 		foreach my $part (@parts) {
                   3458: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3459: 			$all_graded = 0;
                   3460: 		    } else {
                   3461: 			$none_graded = 0;
                   3462: 		    }
                   3463: 		}
                   3464: 
                   3465: 		if ($all_graded || $none_graded) {
                   3466: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3467: 							   $symb,$cdom,$cnum,
                   3468: 							   $udom,$uname);
                   3469: 		}
                   3470: 	    }
                   3471: 
1.126     ng       3472: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3473: 	    $updateCtr++;
1.93      albertel 3474: 	} else {
1.126     ng       3475: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3476: 	    $noupdateCtr++;
1.44      ng       3477: 	}
1.269     raeburn  3478:         if ($aggregateflag) {
                   3479:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3480: 				  $cdom,$cnum);
1.269     raeburn  3481:         }
1.93      albertel 3482:     }
                   3483:     if ($noupdate) {
1.126     ng       3484: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3485: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3486: 	$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       3487:     }
1.72      ng       3488:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3489: 	&show_grading_menu_form ($symb);
1.125     ng       3490:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3491: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3492: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3493:     return $title.$msg.$result;
1.5       albertel 3494: }
1.54      albertel 3495: 
                   3496: sub split_part_type {
                   3497:     my ($partstr) = @_;
                   3498:     my ($temp,@allparts)=split(/_/,$partstr);
                   3499:     my $type=pop(@allparts);
1.439     albertel 3500:     my $part=join('_',@allparts);
1.54      albertel 3501:     return ($part,$type);
                   3502: }
                   3503: 
1.44      ng       3504: #------------- end of section for handling grading by section/class ---------
                   3505: #
                   3506: #----------------------------------------------------------------------------
                   3507: 
1.5       albertel 3508: 
1.44      ng       3509: #----------------------------------------------------------------------------
                   3510: #
                   3511: #-------------------------- Next few routines handles grading by csv upload
                   3512: #
                   3513: #--- Javascript to handle csv upload
1.27      albertel 3514: sub csvupload_javascript_reverse_associate {
1.246     albertel 3515:     my $error1=&mt('You need to specify the username or ID');
                   3516:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3517:   return(<<ENDPICK);
                   3518:   function verify(vf) {
                   3519:     var foundsomething=0;
                   3520:     var founduname=0;
1.243     albertel 3521:     var foundID=0;
1.27      albertel 3522:     for (i=0;i<=vf.nfields.value;i++) {
                   3523:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3524:       if (i==0 && tw!=0) { foundID=1; }
                   3525:       if (i==1 && tw!=0) { founduname=1; }
                   3526:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3527:     }
1.246     albertel 3528:     if (founduname==0 && foundID==0) {
                   3529: 	alert('$error1');
                   3530: 	return;
1.27      albertel 3531:     }
                   3532:     if (foundsomething==0) {
1.246     albertel 3533: 	alert('$error2');
                   3534: 	return;
1.27      albertel 3535:     }
                   3536:     vf.submit();
                   3537:   }
                   3538:   function flip(vf,tf) {
                   3539:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3540:     var i;
                   3541:     for (i=0;i<=vf.nfields.value;i++) {
                   3542:       //can not pick the same destination field for both name and domain
                   3543:       if (((i ==0)||(i ==1)) && 
                   3544:           ((tf==0)||(tf==1)) && 
                   3545:           (i!=tf) &&
                   3546:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3547:         eval('vf.f'+i+'.selectedIndex=0;')
                   3548:       }
                   3549:     }
                   3550:   }
                   3551: ENDPICK
                   3552: }
                   3553: 
                   3554: sub csvupload_javascript_forward_associate {
1.246     albertel 3555:     my $error1=&mt('You need to specify the username or ID');
                   3556:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3557:   return(<<ENDPICK);
                   3558:   function verify(vf) {
                   3559:     var foundsomething=0;
                   3560:     var founduname=0;
1.243     albertel 3561:     var foundID=0;
1.27      albertel 3562:     for (i=0;i<=vf.nfields.value;i++) {
                   3563:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3564:       if (tw==1) { foundID=1; }
                   3565:       if (tw==2) { founduname=1; }
                   3566:       if (tw>3) { foundsomething=1; }
1.27      albertel 3567:     }
1.246     albertel 3568:     if (founduname==0 && foundID==0) {
                   3569: 	alert('$error1');
                   3570: 	return;
1.27      albertel 3571:     }
                   3572:     if (foundsomething==0) {
1.246     albertel 3573: 	alert('$error2');
                   3574: 	return;
1.27      albertel 3575:     }
                   3576:     vf.submit();
                   3577:   }
                   3578:   function flip(vf,tf) {
                   3579:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3580:     var i;
                   3581:     //can not pick the same destination field twice
                   3582:     for (i=0;i<=vf.nfields.value;i++) {
                   3583:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3584:         eval('vf.f'+i+'.selectedIndex=0;')
                   3585:       }
                   3586:     }
                   3587:   }
                   3588: ENDPICK
                   3589: }
                   3590: 
1.26      albertel 3591: sub csvuploadmap_header {
1.324     albertel 3592:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3593:     my $javascript;
1.257     albertel 3594:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3595: 	$javascript=&csvupload_javascript_reverse_associate();
                   3596:     } else {
                   3597: 	$javascript=&csvupload_javascript_forward_associate();
                   3598:     }
1.45      ng       3599: 
1.324     albertel 3600:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3601:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3602:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3603:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3604:     $request->print(<<ENDPICK);
1.26      albertel 3605: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3606: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3607: $result
1.326     albertel 3608: <hr />
1.26      albertel 3609: <h3>Identify fields</h3>
                   3610: Total number of records found in file: $distotal <hr />
                   3611: Enter as many fields as you can. The system will inform you and bring you back
                   3612: to this page if the data selected is insufficient to run your class.<hr />
                   3613: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3614: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3615: <input type="hidden" name="associate"  value="" />
                   3616: <input type="hidden" name="phase"      value="three" />
                   3617: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3618: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3619: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3620: <input type="hidden" name="upfile_associate" 
1.257     albertel 3621:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3622: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3623: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3624: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3625: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3626: <hr />
                   3627: <script type="text/javascript" language="Javascript">
                   3628: $javascript
                   3629: </script>
                   3630: ENDPICK
1.118     ng       3631:     return '';
1.26      albertel 3632: 
                   3633: }
                   3634: 
                   3635: sub csvupload_fields {
1.324     albertel 3636:     my ($symb) = @_;
                   3637:     my (@parts) = &getpartlist($symb);
1.243     albertel 3638:     my @fields=(['ID','Student ID'],
                   3639: 		['username','Student Username'],
                   3640: 		['domain','Student Domain']);
1.324     albertel 3641:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3642:     foreach my $part (sort(@parts)) {
                   3643: 	my @datum;
                   3644: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3645: 	my $name=$part;
                   3646: 	if  (!$display) { $display = $name; }
                   3647: 	@datum=($name,$display);
1.244     albertel 3648: 	if ($name=~/^stores_(.*)_awarded/) {
                   3649: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3650: 	}
1.41      ng       3651: 	push(@fields,\@datum);
                   3652:     }
                   3653:     return (@fields);
1.26      albertel 3654: }
                   3655: 
                   3656: sub csvuploadmap_footer {
1.41      ng       3657:     my ($request,$i,$keyfields) =@_;
                   3658:     $request->print(<<ENDPICK);
1.26      albertel 3659: </table>
                   3660: <input type="hidden" name="nfields" value="$i" />
                   3661: <input type="hidden" name="keyfields" value="$keyfields" />
                   3662: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3663: </form>
                   3664: ENDPICK
                   3665: }
                   3666: 
1.283     albertel 3667: sub checkforfile_js {
1.86      ng       3668:     my $result =<<CSVFORMJS;
                   3669: <script type="text/javascript" language="javascript">
                   3670:     function checkUpload(formname) {
                   3671: 	if (formname.upfile.value == "") {
                   3672: 	    alert("Please use the browse button to select a file from your local directory.");
                   3673: 	    return false;
                   3674: 	}
                   3675: 	formname.submit();
                   3676:     }
                   3677:     </script>
                   3678: CSVFORMJS
1.283     albertel 3679:     return $result;
                   3680: }
                   3681: 
                   3682: sub upcsvScores_form {
                   3683:     my ($request) = shift;
1.324     albertel 3684:     my ($symb)=&get_symb($request);
1.283     albertel 3685:     if (!$symb) {return '';}
                   3686:     my $result=&checkforfile_js();
1.257     albertel 3687:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3688:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3689:     $result.=$table;
1.326     albertel 3690:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3691:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3692:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3693: 	'.</b></td></tr>'."\n";
                   3694:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3695:     my $upload=&mt("Upload Scores");
1.86      ng       3696:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3697:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3698:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3699:     $result.=<<ENDUPFORM;
1.106     albertel 3700: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3701: <input type="hidden" name="symb" value="$symb" />
                   3702: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3703: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3704: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3705: $upfile_select
1.370     www      3706: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3707: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3708: </form>
                   3709: ENDUPFORM
1.370     www      3710:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3711:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3712:     .'</td></tr></table>'."\n";
1.86      ng       3713:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3714:     $result.=&show_grading_menu_form($symb);
1.86      ng       3715:     return $result;
                   3716: }
                   3717: 
                   3718: 
1.26      albertel 3719: sub csvuploadmap {
1.41      ng       3720:     my ($request)= @_;
1.324     albertel 3721:     my ($symb)=&get_symb($request);
1.41      ng       3722:     if (!$symb) {return '';}
1.72      ng       3723: 
1.41      ng       3724:     my $datatoken;
1.257     albertel 3725:     if (!$env{'form.datatoken'}) {
1.41      ng       3726: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3727:     } else {
1.257     albertel 3728: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3729: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3730:     }
1.41      ng       3731:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3732:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3733:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3734:     my ($i,$keyfields);
                   3735:     if (@records) {
1.324     albertel 3736: 	my @fields=&csvupload_fields($symb);
1.45      ng       3737: 
1.257     albertel 3738: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3739: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3740: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3741: 							  \@fields);
                   3742: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3743: 	    chop($keyfields);
                   3744: 	} else {
                   3745: 	    unshift(@fields,['none','']);
                   3746: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3747: 							    \@fields);
1.311     banghart 3748:             foreach my $rec (@records) {
                   3749:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3750:                 if (%temp) {
                   3751:                     $keyfields=join(',',sort(keys(%temp)));
                   3752:                     last;
                   3753:                 }
                   3754:             }
1.41      ng       3755: 	}
                   3756:     }
                   3757:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3758:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3759: 
1.41      ng       3760:     return '';
1.27      albertel 3761: }
                   3762: 
1.246     albertel 3763: sub csvuploadoptions {
1.41      ng       3764:     my ($request)= @_;
1.324     albertel 3765:     my ($symb)=&get_symb($request);
1.257     albertel 3766:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3767:     my $ignore=&mt('Ignore First Line');
                   3768:     $request->print(<<ENDPICK);
                   3769: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3770: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3771: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3772: <!--
1.246     albertel 3773: <p>
                   3774: <label>
                   3775:    <input type="checkbox" name="show_full_results" />
                   3776:    Show a table of all changes
                   3777: </label>
                   3778: </p>
1.302     albertel 3779: -->
1.246     albertel 3780: <p>
                   3781: <label>
                   3782:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3783:    Overwrite any existing score
                   3784: </label>
                   3785: </p>
                   3786: ENDPICK
                   3787:     my %fields=&get_fields();
                   3788:     if (!defined($fields{'domain'})) {
1.257     albertel 3789: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3790: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3791:     }
1.257     albertel 3792:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3793: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3794: 	my $cleankey=$1;
                   3795: 	if ($cleankey eq 'command') { next; }
                   3796: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3797: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3798:     }
                   3799:     # FIXME do a check for any duplicated user ids...
                   3800:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3801:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3802: <hr /></form>'."\n");
1.324     albertel 3803:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3804:     return '';
                   3805: }
                   3806: 
                   3807: sub get_fields {
                   3808:     my %fields;
1.257     albertel 3809:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3810:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3811: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3812: 	    if ($env{'form.f'.$i} ne 'none') {
                   3813: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3814: 	    }
                   3815: 	} else {
1.257     albertel 3816: 	    if ($env{'form.f'.$i} ne 'none') {
                   3817: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3818: 	    }
                   3819: 	}
1.27      albertel 3820:     }
1.246     albertel 3821:     return %fields;
                   3822: }
                   3823: 
                   3824: sub csvuploadassign {
                   3825:     my ($request)= @_;
1.324     albertel 3826:     my ($symb)=&get_symb($request);
1.246     albertel 3827:     if (!$symb) {return '';}
1.345     bowersj2 3828:     my $error_msg = '';
1.246     albertel 3829:     &Apache::loncommon::load_tmp_file($request);
                   3830:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3831:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3832:     my %fields=&get_fields();
1.41      ng       3833:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3834:     my $courseid=$env{'request.course.id'};
1.97      albertel 3835:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3836:     my @notallowed;
1.41      ng       3837:     my @skipped;
                   3838:     my $countdone=0;
                   3839:     foreach my $grade (@gradedata) {
                   3840: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3841: 	my $domain;
                   3842: 	if ($entries{$fields{'domain'}}) {
                   3843: 	    $domain=$entries{$fields{'domain'}};
                   3844: 	} else {
1.257     albertel 3845: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3846: 	}
1.243     albertel 3847: 	$domain=~s/\s//g;
1.41      ng       3848: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3849: 	$username=~s/\s//g;
1.243     albertel 3850: 	if (!$username) {
                   3851: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3852: 	    $id=~s/\s//g;
1.243     albertel 3853: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3854: 	    $username=$ids{$id};
                   3855: 	}
1.41      ng       3856: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3857: 	    my $id=$entries{$fields{'ID'}};
                   3858: 	    $id=~s/\s//g;
                   3859: 	    if ($id) {
                   3860: 		push(@skipped,"$id:$domain");
                   3861: 	    } else {
                   3862: 		push(@skipped,"$username:$domain");
                   3863: 	    }
1.41      ng       3864: 	    next;
                   3865: 	}
1.108     albertel 3866: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3867: 	if (!&canmodify($usec)) {
                   3868: 	    push(@notallowed,"$username:$domain");
                   3869: 	    next;
                   3870: 	}
1.244     albertel 3871: 	my %points;
1.41      ng       3872: 	my %grades;
                   3873: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3874: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3875: 		$dest eq 'domain') { next; }
                   3876: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3877: 	    if ($dest=~/stores_(.*)_points/) {
                   3878: 		my $part=$1;
                   3879: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3880: 					      $symb,$domain,$username);
1.345     bowersj2 3881:                 if ($wgt) {
                   3882:                     $entries{$fields{$dest}}=~s/\s//g;
                   3883:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3884:                     my $award='correct_by_override';
                   3885:                     $grades{"resource.$part.awarded"}=$pcr;
                   3886:                     $grades{"resource.$part.solved"}=$award;
                   3887:                     $points{$part}=1;
                   3888:                 } else {
                   3889:                     $error_msg = "<br />" .
                   3890:                         &mt("Some point values were assigned"
                   3891:                             ." for problems with a weight "
                   3892:                             ."of zero. These values were "
                   3893:                             ."ignored.");
                   3894:                 }
1.244     albertel 3895: 	    } else {
                   3896: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3897: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3898: 		my $store_key=$dest;
                   3899: 		$store_key=~s/^stores/resource/;
                   3900: 		$store_key=~s/_/\./g;
                   3901: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3902: 	    }
1.41      ng       3903: 	}
1.398     albertel 3904: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3905: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3906: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3907: 					   $env{'request.course.id'},
                   3908: 					   $domain,$username);
                   3909: 	if ($result eq 'ok') {
                   3910: 	    $request->print('.');
                   3911: 	} else {
                   3912: 	    $request->print("<p>
1.398     albertel 3913:                               <span class=\"LC_error\">
                   3914:                                  Failed to save student $username:$domain.
                   3915:                                  Message when trying to save was ($result)
                   3916:                               </span>
1.302     albertel 3917:                              </p>" );
                   3918: 	}
1.41      ng       3919: 	$request->rflush();
                   3920: 	$countdone++;
                   3921:     }
1.398     albertel 3922:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3923:     if (@skipped) {
1.398     albertel 3924: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3925: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3926:     }
                   3927:     if (@notallowed) {
1.398     albertel 3928: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3929: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3930:     }
1.106     albertel 3931:     $request->print("<br />\n");
1.324     albertel 3932:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3933:     return $error_msg;
1.26      albertel 3934: }
1.44      ng       3935: #------------- end of section for handling csv file upload ---------
                   3936: #
                   3937: #-------------------------------------------------------------------
                   3938: #
1.122     ng       3939: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3940: #
                   3941: #--- Select a page/sequence and a student to grade
1.68      ng       3942: sub pickStudentPage {
                   3943:     my ($request) = shift;
                   3944: 
                   3945:     $request->print(<<LISTJAVASCRIPT);
                   3946: <script type="text/javascript" language="javascript">
                   3947: 
                   3948: function checkPickOne(formname) {
1.76      ng       3949:     if (radioSelection(formname.student) == null) {
1.68      ng       3950: 	alert("Please select the student you wish to grade.");
                   3951: 	return;
                   3952:     }
1.125     ng       3953:     ptr = pullDownSelection(formname.selectpage);
                   3954:     formname.page.value = formname["page"+ptr].value;
                   3955:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3956:     formname.submit();
                   3957: }
                   3958: 
                   3959: </script>
                   3960: LISTJAVASCRIPT
1.118     ng       3961:     &commonJSfunctions($request);
1.324     albertel 3962:     my ($symb) = &get_symb($request);
1.257     albertel 3963:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3964:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3965:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3966: 
1.398     albertel 3967:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3968: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3969: 
1.80      ng       3970:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3971:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3972:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3973:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3974: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3975: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3976:     my $ctr=0;
1.68      ng       3977:     foreach (@$titles) {
                   3978: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3979: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3980: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3981: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3982: 	$ctr++;
1.68      ng       3983:     }
1.326     albertel 3984:     $result.= '</select>'."<br />\n";
1.70      ng       3985:     $ctr=0;
                   3986:     foreach (@$titles) {
                   3987: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3988: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3989: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3990: 	$ctr++;
                   3991:     }
1.72      ng       3992:     $result.='<input type="hidden" name="page" />'."\n".
                   3993: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3994: 
1.401     albertel 3995:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3996: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3997: 
1.71      ng       3998:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3999: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4000: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4001: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4002:     
                   4003:     $result.=&build_section_inputs();
1.442     banghart 4004:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4005:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4006: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4007: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4008: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4009: 
1.382     albertel 4010:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4011: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4012: 
1.80      ng       4013:     $result.='&nbsp;<input type="button" '.
1.126     ng       4014: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4015: 
1.68      ng       4016:     $request->print($result);
                   4017: 
1.326     albertel 4018:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4019: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4020: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4021: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4022: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4023: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4024: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4025:  
1.76      ng       4026:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4027:     my $ptr = 1;
1.294     albertel 4028:     foreach my $student (sort 
                   4029: 			 {
                   4030: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4031: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4032: 			     }
                   4033: 			     return $a cmp $b;
                   4034: 			 } (keys(%$fullname))) {
1.68      ng       4035: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4036: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4037: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4038: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4039: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4040: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4041: 	$ptr++;
                   4042:     }
1.381     albertel 4043:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4044:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4045:     $studentTable.='<input type="button" '.
                   4046: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4047: 
1.324     albertel 4048:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4049:     $request->print($studentTable);
                   4050: 
                   4051:     return '';
                   4052: }
                   4053: 
                   4054: sub getSymbMap {
1.132     bowersj2 4055:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4056: 
                   4057:     my %symbx = ();
                   4058:     my @titles = ();
1.117     bowersj2 4059:     my $minder = 0;
                   4060: 
                   4061:     # Gather every sequence that has problems.
1.240     albertel 4062:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4063: 					       1,0,1);
1.117     bowersj2 4064:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4065: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4066: 	    my $title = $minder.'.'.
                   4067: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4068: 	    push(@titles, $title); # minder in case two titles are identical
                   4069: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4070: 	    $minder++;
1.241     albertel 4071: 	}
1.68      ng       4072:     }
                   4073:     return \@titles,\%symbx;
                   4074: }
                   4075: 
1.72      ng       4076: #
                   4077: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4078: sub displayPage {
                   4079:     my ($request) = shift;
                   4080: 
1.324     albertel 4081:     my ($symb) = &get_symb($request);
1.257     albertel 4082:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4083:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4084:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4085:     my $pageTitle = $env{'form.page'};
1.103     albertel 4086:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4087:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4088:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4089: 
                   4090:     #need to make sure we have the correct data for later EXT calls, 
                   4091:     #thus invalidate the cache
                   4092:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4093:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4094:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4095:     &Apache::lonnet::clear_EXT_cache_status();
                   4096: 
1.103     albertel 4097:     if (!&canview($usec)) {
1.398     albertel 4098: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4099: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4100: 	return;
                   4101:     }
1.398     albertel 4102:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4103:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4104: 	'</h3>'."\n";
1.382     albertel 4105:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4106: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4107:     } else {
                   4108: 	delete($env{'form.CODE'});
                   4109:     }
1.71      ng       4110:     &sub_page_js($request);
                   4111:     $request->print($result);
                   4112: 
1.132     bowersj2 4113:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4114:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4115:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4116:     if (!$map) {
1.398     albertel 4117: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4118: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4119: 	return; 
                   4120:     }
1.68      ng       4121:     my $iterator = $navmap->getIterator($map->map_start(),
                   4122: 					$map->map_finish());
                   4123: 
1.71      ng       4124:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4125: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4126: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4127: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4128: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4129: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4130: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4131: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4132: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4133: 
1.382     albertel 4134:     if (defined($env{'form.CODE'})) {
                   4135: 	$studentTable.=
                   4136: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4137:     }
1.381     albertel 4138:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4139: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4140: 	'/check.gif" height="16" border="0" />';
                   4141: 
1.118     ng       4142:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4143: 	' symbol.'."\n".
1.71      ng       4144: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4145: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4146: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4147: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4148: 
1.329     albertel 4149:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4150:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4151:     $iterator->next(); # skip the first BEGIN_MAP
                   4152:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4153:     while ($depth > 0) {
1.68      ng       4154:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4155:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4156: 
1.385     albertel 4157:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4158: 	    my $parts = $curRes->parts();
1.68      ng       4159:             my $title = $curRes->compTitle();
1.71      ng       4160: 	    my $symbx = $curRes->symb();
1.196     albertel 4161: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4162: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4163: 	    $studentTable.='<td valign="top">';
1.382     albertel 4164: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4165: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4166: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4167: 					     undef,'both',\%form);
1.71      ng       4168: 	    } else {
1.382     albertel 4169: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4170: 		$companswer =~ s|<form(.*?)>||g;
                   4171: 		$companswer =~ s|</form>||g;
1.71      ng       4172: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4173: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4174: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4175: #		}
1.116     ng       4176: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4177: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4178: 	    }
                   4179: 
1.257     albertel 4180: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4181: 
1.257     albertel 4182: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4183: 		if ($record{'version'} eq '') {
1.398     albertel 4184: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4185: 		} else {
1.116     ng       4186: 		    my %responseType = ();
                   4187: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4188: 			my @responseIds =$curRes->responseIds($partid);
                   4189: 			my @responseType =$curRes->responseType($partid);
                   4190: 			my %responseIds;
                   4191: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4192: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4193: 			}
                   4194: 			$responseType{$partid} = \%responseIds;
1.116     ng       4195: 		    }
1.148     albertel 4196: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4197: 
1.71      ng       4198: 		}
1.257     albertel 4199: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4200: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4201: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4202: 									$env{'request.course.id'},
1.71      ng       4203: 									'','.submission');
                   4204:  
                   4205: 	    }
1.103     albertel 4206: 	    if (&canmodify($usec)) {
                   4207: 		foreach my $partid (@{$parts}) {
                   4208: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4209: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4210: 		    $question++;
                   4211: 		}
1.196     albertel 4212: 		$prob++;
1.71      ng       4213: 	    }
                   4214: 	    $studentTable.='</td></tr>';
1.68      ng       4215: 
1.103     albertel 4216: 	}
1.68      ng       4217:         $curRes = $iterator->next();
                   4218:     }
                   4219: 
1.381     albertel 4220:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4221: 	'<input type="button" value="Save" '.
1.381     albertel 4222: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4223: 	'</form>'."\n";
1.324     albertel 4224:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4225:     $request->print($studentTable);
                   4226: 
                   4227:     return '';
1.119     ng       4228: }
                   4229: 
                   4230: sub displaySubByDates {
1.148     albertel 4231:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4232:     my $isCODE=0;
1.335     albertel 4233:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4234:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4235:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4236: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4237: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4238: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4239: 	'<td><b>Submission</b></td>'.
                   4240: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4241:     my ($version);
                   4242:     my %mark;
1.148     albertel 4243:     my %orders;
1.119     ng       4244:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4245:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4246: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4247:     }
1.335     albertel 4248: 
                   4249:     my $interaction;
1.119     ng       4250:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4251: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4252: 	if (exists($$record{$version.':resource.0.version'})) {
                   4253: 	    $interaction = $$record{$version.':resource.0.version'};
                   4254: 	}
                   4255: 
                   4256: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4257: 		             : "$version:resource");
1.119     ng       4258: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4259: 	if ($isCODE) {
                   4260: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4261: 	}
1.119     ng       4262: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4263: 	my @displaySub = ();
                   4264: 	foreach my $partid (@{$parts}) {
1.335     albertel 4265: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4266: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4267: 	    
                   4268: 
1.122     ng       4269: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4270: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4271: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4272: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4273: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4274: 
                   4275: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4276: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4277: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4278: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4279: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4280: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4281: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4282: 		    } else {
                   4283: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4284: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4285: 		    }
1.335     albertel 4286: 		    my $responseType=($isTask ? 'Task'
                   4287:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4288: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4289: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4290: 			$orders{$partid}->{$responseId}=
                   4291: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4292: 		    }
1.147     albertel 4293: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4294: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4295: 		}
                   4296: 	    }
1.335     albertel 4297: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4298: 		$displaySub[1].='Checked in by '.
                   4299: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4300: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4301: 		    '<br />';
                   4302: 	    }
                   4303: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4304: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4305: 		    lc($$record{"$where.$partid.award"}).' '.
                   4306: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4307: 		    '<br />';
                   4308: 	    }
1.335     albertel 4309: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4310: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4311: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4312: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4313: 		$displaySub[2].=
                   4314: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4315: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4316: 	    }
                   4317: 	}
                   4318: 	# needed because old essay regrader has not parts info
                   4319: 	if (exists $$record{"$version:resource.regrader"}) {
                   4320: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4321: 	}
                   4322: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4323: 	if ($displaySub[2]) {
                   4324: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4325: 	}
1.382     albertel 4326: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4327:     
1.119     ng       4328:     }
                   4329:     $studentTable.='</table></td></tr></table>';
                   4330:     return $studentTable;
1.71      ng       4331: }
                   4332: 
                   4333: sub updateGradeByPage {
                   4334:     my ($request) = shift;
                   4335: 
1.257     albertel 4336:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4337:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4338:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4339:     my $pageTitle = $env{'form.page'};
1.103     albertel 4340:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4341:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4342:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4343:     if (!&canmodify($usec)) {
1.398     albertel 4344: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4345: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4346: 	return;
                   4347:     }
1.398     albertel 4348:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4349:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4350: 	'</h3>'."\n";
1.70      ng       4351: 
1.68      ng       4352:     $request->print($result);
                   4353: 
1.132     bowersj2 4354:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4355:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4356:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4357:     if (!$map) {
1.398     albertel 4358: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4359: 	my ($symb)=&get_symb($request);
                   4360: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4361: 	return; 
                   4362:     }
1.71      ng       4363:     my $iterator = $navmap->getIterator($map->map_start(),
                   4364: 					$map->map_finish());
1.70      ng       4365: 
1.71      ng       4366:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4367: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4368: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4369: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4370: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4371: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4372: 
                   4373:     $iterator->next(); # skip the first BEGIN_MAP
                   4374:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4375:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4376:     while ($depth > 0) {
1.71      ng       4377:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4378:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4379: 
1.385     albertel 4380:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4381: 	    my $parts = $curRes->parts();
1.71      ng       4382:             my $title = $curRes->compTitle();
                   4383: 	    my $symbx = $curRes->symb();
1.196     albertel 4384: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4385: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4386: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4387: 
                   4388: 	    my %newrecord=();
                   4389: 	    my @displayPts=();
1.269     raeburn  4390:             my %aggregate = ();
                   4391:             my $aggregateflag = 0;
1.71      ng       4392: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4393: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4394: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4395: 
1.257     albertel 4396: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4397: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4398: 		my $partial = $newpts/$wgt;
                   4399: 		my $score;
                   4400: 		if ($partial > 0) {
                   4401: 		    $score = 'correct_by_override';
1.125     ng       4402: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4403: 		    $score = 'incorrect_by_override';
                   4404: 		}
1.257     albertel 4405: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4406: 		if ($dropMenu eq 'excused') {
1.71      ng       4407: 		    $partial = '';
                   4408: 		    $score = 'excused';
1.125     ng       4409: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4410: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4411: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4412: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4413: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4414: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4415: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4416: 		    $changeflag++;
                   4417: 		    $newpts = '';
1.269     raeburn  4418:                     
                   4419:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4420:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4421:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4422:                     if ($aggtries > 0) {
                   4423:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4424:                         $aggregateflag = 1;
                   4425:                     }
1.71      ng       4426: 		}
1.324     albertel 4427: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4428: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4429: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4430: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4431: 		    '&nbsp;<br />';
1.207     albertel 4432: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4433: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4434: 		    '&nbsp;<br />';
1.71      ng       4435: 		$question++;
1.380     albertel 4436: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4437: 
1.71      ng       4438: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4439: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4440: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4441: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4442: 
                   4443: 		$changeflag++;
                   4444: 	    }
                   4445: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4446: 		my %record = 
                   4447: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4448: 					     $udom,$uname);
                   4449: 
                   4450: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4451: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4452: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4453: 		    $newrecord{'resource.CODE'} = '';
                   4454: 		}
1.257     albertel 4455: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4456: 					$udom,$uname);
1.382     albertel 4457: 		%record = &Apache::lonnet::restore($symbx,
                   4458: 						   $env{'request.course.id'},
                   4459: 						   $udom,$uname);
1.380     albertel 4460: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4461: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4462: 	    }
1.380     albertel 4463: 	    
1.269     raeburn  4464:             if ($aggregateflag) {
                   4465:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4466:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4467:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4468:             }
1.125     ng       4469: 
1.71      ng       4470: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4471: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4472: 		'</tr>';
1.68      ng       4473: 
1.196     albertel 4474: 	    $prob++;
1.68      ng       4475: 	}
1.71      ng       4476:         $curRes = $iterator->next();
1.68      ng       4477:     }
1.98      albertel 4478: 
1.71      ng       4479:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4480:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4481:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4482: 		  'The scores were changed for '.
                   4483: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4484:     $request->print($grademsg.$studentTable);
1.68      ng       4485: 
1.70      ng       4486:     return '';
                   4487: }
                   4488: 
1.72      ng       4489: #-------- end of section for handling grading by page/sequence ---------
                   4490: #
                   4491: #-------------------------------------------------------------------
                   4492: 
1.75      albertel 4493: #--------------------Scantron Grading-----------------------------------
                   4494: #
                   4495: #------ start of section for handling grading by page/sequence ---------
                   4496: 
1.423     albertel 4497: =pod
                   4498: 
                   4499: =head1 Bubble sheet grading routines
                   4500: 
1.424     albertel 4501:   For this documentation:
                   4502: 
                   4503:    'scanline' refers to the full line of characters
                   4504:    from the file that we are parsing that represents one entire sheet
                   4505: 
                   4506:    'bubble line' refers to the data
                   4507:    representing the line of bubbles that are on the physical bubble sheet
                   4508: 
                   4509: 
                   4510: The overall process is that a scanned in bubble sheet data is uploaded
                   4511: into a course. When a user wants to grade, they select a
                   4512: sequence/folder of resources, a file of bubble sheet info, and pick
                   4513: one of the predefined configurations for what each scanline looks
                   4514: like.
                   4515: 
                   4516: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4517: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4518: because too light bubbling), 'double bubble' (each bubble line should
                   4519: have no more that one letter picked), invalid or duplicated CODE,
                   4520: invalid student ID
                   4521: 
                   4522: If the CODE option is used that determines the randomization of the
                   4523: homework problems, either way the student ID is looked up into a
                   4524: username:domain.
                   4525: 
                   4526: During the validation phase the instructor can choose to skip scanlines. 
                   4527: 
1.435     foxr     4528: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4529: 
                   4530:   scantron_original_filename (unmodified original file)
                   4531:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4532:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4533: 
                   4534: Also there is a separate hash nohist_scantrondata that contains extra
                   4535: correction information that isn't representable in the bubble sheet
                   4536: file (see &scantron_getfile() for more information)
                   4537: 
                   4538: After all scanlines are either valid, marked as valid or skipped, then
                   4539: foreach line foreach problem in the picked sequence, an ssi request is
                   4540: made that simulates a user submitting their selected letter(s) against
                   4541: the homework problem.
1.423     albertel 4542: 
                   4543: =over 4
                   4544: 
                   4545: 
                   4546: 
                   4547: =item defaultFormData
                   4548: 
                   4549:   Returns html hidden inputs used to hold context/default values.
                   4550: 
                   4551:  Arguments:
                   4552:   $symb - $symb of the current resource 
                   4553: 
                   4554: =cut
1.422     foxr     4555: 
1.81      albertel 4556: sub defaultFormData {
1.324     albertel 4557:     my ($symb)=@_;
1.447     foxr     4558:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4559:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4560:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4561: }
                   4562: 
1.447     foxr     4563: 
1.423     albertel 4564: =pod 
                   4565: 
                   4566: =item getSequenceDropDown
                   4567: 
                   4568:    Return html dropdown of possible sequences to grade
                   4569:  
                   4570:  Arguments:
                   4571:    $symb - $symb of the current resource 
                   4572: 
                   4573: =cut
1.422     foxr     4574: 
1.75      albertel 4575: sub getSequenceDropDown {
1.423     albertel 4576:     my ($symb)=@_;
1.75      albertel 4577:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4578:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4579:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4580:     my $ctr=0;
                   4581:     foreach (@$titles) {
                   4582: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4583: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4584: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4585: 	    '>'.$showtitle.'</option>'."\n";
                   4586: 	$ctr++;
                   4587:     }
                   4588:     $result.= '</select>';
                   4589:     return $result;
                   4590: }
                   4591: 
1.423     albertel 4592: 
                   4593: =pod 
                   4594: 
                   4595: =item scantron_filenames
                   4596: 
                   4597:    Returns a list of the scantron files in the current course 
                   4598: 
                   4599: =cut
1.422     foxr     4600: 
1.202     albertel 4601: sub scantron_filenames {
1.257     albertel 4602:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4603:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4604:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4605: 				    &propath($cdom,$cname));
1.202     albertel 4606:     my @possiblenames;
1.201     albertel 4607:     foreach my $filename (sort(@files)) {
1.157     albertel 4608: 	($filename)=split(/&/,$filename);
                   4609: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4610: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4611: 	push(@possiblenames,$filename);
                   4612:     }
                   4613:     return @possiblenames;
                   4614: }
                   4615: 
1.423     albertel 4616: =pod 
                   4617: 
                   4618: =item scantron_uploads
                   4619: 
                   4620:    Returns  html drop-down list of scantron files in current course.
                   4621: 
                   4622:  Arguments:
                   4623:    $file2grade - filename to set as selected in the dropdown
                   4624: 
                   4625: =cut
1.422     foxr     4626: 
1.202     albertel 4627: sub scantron_uploads {
1.209     ng       4628:     my ($file2grade) = @_;
1.202     albertel 4629:     my $result=	'<select name="scantron_selectfile">';
                   4630:     $result.="<option></option>";
                   4631:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4632: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4633:     }
                   4634:     $result.="</select>";
                   4635:     return $result;
                   4636: }
                   4637: 
1.423     albertel 4638: =pod 
                   4639: 
                   4640: =item scantron_scantab
                   4641: 
                   4642:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4643:   file.
                   4644: 
                   4645: =cut
1.422     foxr     4646: 
1.82      albertel 4647: sub scantron_scantab {
                   4648:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4649:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4650:     $result.='<option></option>'."\n";
1.82      albertel 4651:     foreach my $line (<$fh>) {
                   4652: 	my ($name,$descrip)=split(/:/,$line);
                   4653: 	if ($name =~ /^\#/) { next; }
                   4654: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4655:     }
                   4656:     $result.='</select>'."\n";
                   4657: 
                   4658:     return $result;
                   4659: }
                   4660: 
1.423     albertel 4661: =pod 
                   4662: 
                   4663: =item scantron_CODElist
                   4664: 
                   4665:   Returns html drop down of the saved CODE lists from current course,
                   4666:   generated from earlier printings.
                   4667: 
                   4668: =cut
1.422     foxr     4669: 
1.186     albertel 4670: sub scantron_CODElist {
1.257     albertel 4671:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4672:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4673:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4674:     my $namechoice='<option></option>';
1.225     albertel 4675:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4676: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4677: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4678: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4679:     }
                   4680:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4681:     return $namechoice;
                   4682: }
                   4683: 
1.423     albertel 4684: =pod 
                   4685: 
                   4686: =item scantron_CODEunique
                   4687: 
                   4688:   Returns the html for "Each CODE to be used once" radio.
                   4689: 
                   4690: =cut
1.422     foxr     4691: 
1.186     albertel 4692: sub scantron_CODEunique {
1.381     albertel 4693:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4694:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4695:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4696:                 </span>
                   4697:                 <span style="white-space: nowrap;">
1.272     albertel 4698:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4699:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4700:                 </span>';
1.186     albertel 4701:     return $result;
                   4702: }
1.423     albertel 4703: 
                   4704: =pod 
                   4705: 
                   4706: =item scantron_selectphase
                   4707: 
                   4708:   Generates the initial screen to start the bubble sheet process.
                   4709:   Allows for - starting a grading run.
1.424     albertel 4710:              - downloading existing scan data (original, corrected
1.423     albertel 4711:                                                 or skipped info)
                   4712: 
                   4713:              - uploading new scan data
                   4714: 
                   4715:  Arguments:
                   4716:   $r          - The Apache request object
                   4717:   $file2grade - name of the file that contain the scanned data to score
                   4718: 
                   4719: =cut
1.186     albertel 4720: 
1.75      albertel 4721: sub scantron_selectphase {
1.209     ng       4722:     my ($r,$file2grade) = @_;
1.324     albertel 4723:     my ($symb)=&get_symb($r);
1.75      albertel 4724:     if (!$symb) {return '';}
1.423     albertel 4725:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4726:     my $default_form_data=&defaultFormData($symb);
                   4727:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4728:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4729:     my $format_selector=&scantron_scantab();
1.186     albertel 4730:     my $CODE_selector=&scantron_CODElist();
                   4731:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4732:     my $result;
1.422     foxr     4733: 
                   4734:     # Chunk of form to prompt for a file to grade and how:
                   4735: 
1.75      albertel 4736:     $result.= <<SCANTRONFORM;
1.162     albertel 4737:     <table width="100%" border="0">
1.75      albertel 4738:     <tr>
1.226     albertel 4739:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4740:       <td bgcolor="#777777">
1.203     albertel 4741:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4742:         $default_form_data
1.75      albertel 4743:         <table width="100%" border="0">
                   4744:           <tr bgcolor="#e6ffff">
1.174     albertel 4745:             <td colspan="2">
                   4746:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4747:             </td>
                   4748:           </tr>
                   4749:           <tr bgcolor="#ffffe6">
1.174     albertel 4750:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4751:           </tr>
                   4752:           <tr bgcolor="#ffffe6">
1.174     albertel 4753:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4754:           </tr>
1.82      albertel 4755:           <tr bgcolor="#ffffe6">
1.174     albertel 4756:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4757:           </tr>
1.157     albertel 4758:           <tr bgcolor="#ffffe6">
1.186     albertel 4759:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4760:           </tr>
                   4761:           <tr bgcolor="#ffffe6">
                   4762:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4763:           </tr>
                   4764:           <tr bgcolor="#ffffe6">
1.187     albertel 4765: 	    <td> Options: </td>
                   4766:             <td>
1.272     albertel 4767: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4768:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4769:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4770: 	    </td>
                   4771:           </tr>
                   4772:           <tr bgcolor="#ffffe6">
1.174     albertel 4773:             <td colspan="2">
1.265     www      4774:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4775:             </td>
                   4776:           </tr>
                   4777:         </table>
1.226     albertel 4778:        </td>
                   4779:      </form>
1.162     albertel 4780:     </tr>
                   4781: SCANTRONFORM
                   4782:    
                   4783:     $r->print($result);
                   4784: 
1.257     albertel 4785:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4786:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4787: 
1.422     foxr     4788: 	# Chunk of form to prompt for a scantron file upload.
                   4789: 
1.162     albertel 4790:         $r->print(<<SCANTRONFORM);
                   4791:     <tr>
                   4792:       <td bgcolor="#777777">
                   4793:         <table width="100%" border="0">
                   4794:           <tr bgcolor="#e6ffff">
                   4795:             <td>
1.174     albertel 4796:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4797:             </td>
                   4798:           </tr>
                   4799:           <tr bgcolor="#ffffe6">
                   4800:             <td>
                   4801: SCANTRONFORM
1.324     albertel 4802:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4803:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4804:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4805:     $r->print(<<UPLOAD);
                   4806:               <script type="text/javascript" language="javascript">
                   4807:     function checkUpload(formname) {
                   4808: 	if (formname.upfile.value == "") {
                   4809: 	    alert("Please use the browse button to select a file from your local directory.");
                   4810: 	    return false;
                   4811: 	}
                   4812: 	formname.submit();
                   4813:     }
                   4814:               </script>
                   4815: 
                   4816:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4817:                 $default_form_data
                   4818:                 <input name='courseid' type='hidden' value='$cnum' />
                   4819:                 <input name='domainid' type='hidden' value='$cdom' />
                   4820:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4821:                 File to upload:<input type="file" name="upfile" size="50" />
                   4822:                 <br />
                   4823:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4824:               </form>
                   4825: UPLOAD
1.162     albertel 4826: 
                   4827:         $r->print(<<SCANTRONFORM);
                   4828:             </td>
                   4829:           </tr>
1.75      albertel 4830:         </table>
                   4831:       </td>
                   4832:     </tr>
1.162     albertel 4833: SCANTRONFORM
                   4834:     }
1.422     foxr     4835: 
                   4836:     # Chunk of the form that prompts to view a scoring office file,
                   4837:     # corrected file, skipped records in a file.
                   4838: 
1.187     albertel 4839:     $r->print(<<SCANTRONFORM);
                   4840:     <tr>
1.226     albertel 4841:       <form action='/adm/grades' name='scantron_download'>
                   4842:         <td bgcolor="#777777">
1.379     albertel 4843: 	  $default_form_data
1.187     albertel 4844:           <input type="hidden" name="command" value="scantron_download" />
                   4845:           <table width="100%" border="0">
                   4846:             <tr bgcolor="#e6ffff">
                   4847:               <td colspan="2">
                   4848:                 &nbsp;<b>Download a scoring office file</b>
                   4849:               </td>
                   4850:             </tr>
                   4851:             <tr bgcolor="#ffffe6">
                   4852:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4853:             </tr>
                   4854:             <tr bgcolor="#ffffe6">
                   4855:               <td colspan="2">
1.293     www      4856:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4857:               </td>
                   4858:             </tr>
                   4859:           </table>
1.226     albertel 4860:         </td>
                   4861:       </form>
1.187     albertel 4862:     </tr>
                   4863: SCANTRONFORM
1.162     albertel 4864: 
                   4865:     $r->print(<<SCANTRONFORM);
1.75      albertel 4866:   </table>
1.81      albertel 4867: $grading_menu_button
1.75      albertel 4868: SCANTRONFORM
                   4869: 
1.162     albertel 4870:     return
1.75      albertel 4871: }
                   4872: 
1.423     albertel 4873: =pod
                   4874: 
                   4875: =item get_scantron_config
                   4876: 
                   4877:    Parse and return the scantron configuration line selected as a
                   4878:    hash of configuration file fields.
                   4879: 
                   4880:  Arguments:
                   4881:     which - the name of the configuration to parse from the file.
                   4882: 
                   4883: 
                   4884:  Returns:
                   4885:             If the named configuration is not in the file, an empty
                   4886:             hash is returned.
                   4887:     a hash with the fields
                   4888:       name         - internal name for the this configuration setup
                   4889:       description  - text to display to operator that describes this config
                   4890:       CODElocation - if 0 or the string 'none'
                   4891:                           - no CODE exists for this config
                   4892:                      if -1 || the string 'letter'
                   4893:                           - a CODE exists for this config and is
                   4894:                             a string of letters
                   4895:                      Unsupported value (but planned for future support)
                   4896:                           if a positive integer
                   4897:                                - The CODE exists as the first n items from
                   4898:                                  the question section of the form
                   4899:                           if the string 'number'
                   4900:                                - The CODE exists for this config and is
                   4901:                                  a string of numbers
                   4902:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4903:                      the CODE starts
                   4904:       CODElength  - length of the CODE
                   4905:       IDstart     - column where the student ID number starts
                   4906:       IDlength    - length of the student ID info
                   4907:       Qstart      - column where the information from the bubbled
                   4908:                     'questions' start
                   4909:       Qlength     - number of columns comprising a single bubble line from
                   4910:                     the sheet. (usually either 1 or 10)
1.424     albertel 4911:       Qon         - either a single character representing the character used
1.423     albertel 4912:                     to signal a bubble was chosen in the positional setup, or
                   4913:                     the string 'letter' if the letter of the chosen bubble is
                   4914:                     in the final, or 'number' if a number representing the
                   4915:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4916:       Qoff        - the character used to represent that a bubble was
                   4917:                     left blank
1.423     albertel 4918:       PaperID     - if the scanning process generates a unique number for each
                   4919:                     sheet scanned the column that this ID number starts in
                   4920:       PaperIDlength - number of columns that comprise the unique ID number
                   4921:                       for the sheet of paper
1.424     albertel 4922:       FirstName   - column that the first name starts in
1.423     albertel 4923:       FirstNameLength - number of columns that the first name spans
                   4924:  
                   4925:       LastName    - column that the last name starts in
                   4926:       LastNameLength - number of columns that the last name spans
                   4927: 
                   4928: =cut
1.422     foxr     4929: 
1.82      albertel 4930: sub get_scantron_config {
                   4931:     my ($which) = @_;
                   4932:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4933:     my %config;
1.157     albertel 4934:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4935:     foreach my $line (<$fh>) {
                   4936: 	my ($name,$descrip)=split(/:/,$line);
                   4937: 	if ($name ne $which ) { next; }
                   4938: 	chomp($line);
                   4939: 	my @config=split(/:/,$line);
                   4940: 	$config{'name'}=$config[0];
                   4941: 	$config{'description'}=$config[1];
                   4942: 	$config{'CODElocation'}=$config[2];
                   4943: 	$config{'CODEstart'}=$config[3];
                   4944: 	$config{'CODElength'}=$config[4];
                   4945: 	$config{'IDstart'}=$config[5];
                   4946: 	$config{'IDlength'}=$config[6];
                   4947: 	$config{'Qstart'}=$config[7];
                   4948: 	$config{'Qlength'}=$config[8];
                   4949: 	$config{'Qoff'}=$config[9];
                   4950: 	$config{'Qon'}=$config[10];
1.157     albertel 4951: 	$config{'PaperID'}=$config[11];
                   4952: 	$config{'PaperIDlength'}=$config[12];
                   4953: 	$config{'FirstName'}=$config[13];
                   4954: 	$config{'FirstNamelength'}=$config[14];
                   4955: 	$config{'LastName'}=$config[15];
                   4956: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4957: 	last;
                   4958:     }
                   4959:     return %config;
                   4960: }
                   4961: 
1.423     albertel 4962: =pod 
                   4963: 
                   4964: =item username_to_idmap
                   4965: 
                   4966:     creates a hash keyed by student id with values of the corresponding
                   4967:     student username:domain.
                   4968: 
                   4969:   Arguments:
                   4970: 
                   4971:     $classlist - reference to the class list hash. This is a hash
                   4972:                  keyed by student name:domain  whose elements are references
1.424     albertel 4973:                  to arrays containing various chunks of information
1.423     albertel 4974:                  about the student. (See loncoursedata for more info).
                   4975: 
                   4976:   Returns
                   4977:     %idmap - the constructed hash
                   4978: 
                   4979: =cut
                   4980: 
1.82      albertel 4981: sub username_to_idmap {
                   4982:     my ($classlist)= @_;
                   4983:     my %idmap;
                   4984:     foreach my $student (keys(%$classlist)) {
                   4985: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4986: 	    $student;
                   4987:     }
                   4988:     return %idmap;
                   4989: }
1.423     albertel 4990: 
                   4991: =pod
                   4992: 
1.424     albertel 4993: =item scantron_fixup_scanline
1.423     albertel 4994: 
                   4995:    Process a requested correction to a scanline.
                   4996: 
                   4997:   Arguments:
                   4998:     $scantron_config   - hash from &get_scantron_config()
                   4999:     $scan_data         - hash of correction information 
                   5000:                           (see &scantron_getfile())
                   5001:     $line              - existing scanline
                   5002:     $whichline         - line number of the passed in scanline
                   5003:     $field             - type of change to process 
                   5004:                          (either 
                   5005:                           'ID'     -> correct the student ID number
                   5006:                           'CODE'   -> correct the CODE
                   5007:                           'answer' -> fixup the submitted answers)
                   5008:     
                   5009:    $args               - hash of additional info,
                   5010:                           - 'ID' 
                   5011:                                'newid' -> studentID to use in replacement
1.424     albertel 5012:                                           of existing one
1.423     albertel 5013:                           - 'CODE' 
                   5014:                                'CODE_ignore_dup' - set to true if duplicates
                   5015:                                                    should be ignored.
                   5016: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5017:                                         if the existing unfound code should
1.423     albertel 5018:                                         be used as is
                   5019:                           - 'answer'
                   5020:                                'response' - new answer or 'none' if blank
                   5021:                                'question' - the bubble line to change
                   5022: 
                   5023:   Returns:
                   5024:     $line - the modified scanline
                   5025: 
                   5026:   Side effects: 
                   5027:     $scan_data - may be updated
                   5028: 
                   5029: =cut
                   5030: 
1.82      albertel 5031: 
1.157     albertel 5032: sub scantron_fixup_scanline {
                   5033:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5034: 
1.157     albertel 5035:     if ($field eq 'ID') {
                   5036: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5037: 	    return ($line,1,'New value too large');
1.157     albertel 5038: 	}
                   5039: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5040: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5041: 				     $args->{'newid'});
                   5042: 	}
                   5043: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5044: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5045: 	if ($args->{'newid'}=~/^\s*$/) {
                   5046: 	    &scan_data($scan_data,"$whichline.user",
                   5047: 		       $args->{'username'}.':'.$args->{'domain'});
                   5048: 	}
1.186     albertel 5049:     } elsif ($field eq 'CODE') {
1.192     albertel 5050: 	if ($args->{'CODE_ignore_dup'}) {
                   5051: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5052: 	}
                   5053: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5054: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5055: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5056: 		return ($line,1,'New CODE value too large');
                   5057: 	    }
                   5058: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5059: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5060: 	    }
                   5061: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5062: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5063: 	}
1.157     albertel 5064:     } elsif ($field eq 'answer') {
                   5065: 	my $length=$scantron_config->{'Qlength'};
                   5066: 	my $off=$scantron_config->{'Qoff'};
                   5067: 	my $on=$scantron_config->{'Qon'};
                   5068: 	my $answer=${off}x$length;
                   5069: 	if ($args->{'response'} eq 'none') {
                   5070: 	    &scan_data($scan_data,
                   5071: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5072: 	} else {
1.274     albertel 5073: 	    if ($on eq 'letter') {
                   5074: 		my @alphabet=('A'..'Z');
                   5075: 		$answer=$alphabet[$args->{'response'}];
                   5076: 	    } elsif ($on eq 'number') {
                   5077: 		$answer=$args->{'response'}+1;
1.389     albertel 5078: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5079: 	    } else {
                   5080: 		substr($answer,$args->{'response'},1)=$on;
                   5081: 	    }
1.157     albertel 5082: 	    &scan_data($scan_data,
                   5083: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5084: 	}
                   5085: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5086: 	substr($line,$where-1,$length)=$answer;
                   5087:     }
                   5088:     return $line;
                   5089: }
1.423     albertel 5090: 
                   5091: =pod
                   5092: 
                   5093: =item scan_data
                   5094: 
                   5095:     Edit or look up  an item in the scan_data hash.
                   5096: 
                   5097:   Arguments:
                   5098:     $scan_data  - The hash (see scantron_getfile)
                   5099:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5100:                   scantronfilename_key).
1.423     albertel 5101:     $data        - New value of the hash entry.
                   5102:     $delete      - If true, the entry is removed from the hash.
                   5103: 
                   5104:   Returns:
                   5105:     The new value of the hash table field (undefined if deleted).
                   5106: 
                   5107: =cut
                   5108: 
                   5109: 
1.157     albertel 5110: sub scan_data {
                   5111:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5112:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5113:     if (defined($value)) {
                   5114: 	$scan_data->{$filename.'_'.$key} = $value;
                   5115:     }
                   5116:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5117:     return $scan_data->{$filename.'_'.$key};
                   5118: }
1.423     albertel 5119: 
                   5120: =pod 
                   5121: 
                   5122: =item scantron_parse_scanline
                   5123: 
                   5124:   Decodes a scanline from the selected scantron file
                   5125: 
                   5126:  Arguments:
                   5127:     line             - The text of the scantron file line to process
                   5128:     whichline        - Line number
                   5129:     scantron_config  - Hash describing the format of the scantron lines.
                   5130:     scan_data        - Hash of extra information about the scanline
                   5131:                        (see scantron_getfile for more information)
                   5132:     just_header      - True if should not process question answers but only
                   5133:                        the stuff to the left of the answers.
                   5134:  Returns:
                   5135:    Hash containing the result of parsing the scanline
                   5136: 
                   5137:    Keys are all proceeded by the string 'scantron.'
                   5138: 
                   5139:        CODE    - the CODE in use for this scanline
                   5140:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5141:                  by the operator
                   5142:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5143:                             CODEs were selected, but the usage has been
                   5144:                             forced by the operator
                   5145:        ID  - student ID
                   5146:        PaperID - if used, the ID number printed on the sheet when the 
                   5147:                  paper was scanned
                   5148:        FirstName - first name from the sheet
                   5149:        LastName  - last name from the sheet
                   5150: 
                   5151:      if just_header was not true these key may also exist
                   5152: 
1.447     foxr     5153:        missingerror - a list of bubble ranges that are considered to be answers
                   5154:                       to a single question that don't have any bubbles filled in.
                   5155:                       Of the form questionnumber:firstbubblenumber:count.
                   5156:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5157:                       to a single question that have more than one bubble filled in.
                   5158:                       Of the form questionnumber::firstbubblenumber:count
                   5159:    
                   5160:                 In the above, count is the number of bubble responses in the
                   5161:                 input line needed to represent the possible answers to the question.
                   5162:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5163:                 per line would have count = 2.
                   5164: 
1.423     albertel 5165:        maxquest     - the number of the last bubble line that was parsed
                   5166: 
                   5167:        (<number> starts at 1)
                   5168:        <number>.answer - zero or more letters representing the selected
                   5169:                          letters from the scanline for the bubble line 
                   5170:                          <number>.
                   5171:                          if blank there was either no bubble or there where
                   5172:                          multiple bubbles, (consult the keys missingerror and
                   5173:                          doubleerror if this is an error condition)
                   5174: 
                   5175: =cut
                   5176: 
1.82      albertel 5177: sub scantron_parse_scanline {
1.423     albertel 5178:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5179:     my %record;
1.422     foxr     5180:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5181:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5182:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5183: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5184: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5185: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5186: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5187: 	    $record{'scantron.CODE'}=substr($data,
                   5188: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5189: 					    $$scantron_config{'CODElength'});
1.191     albertel 5190: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5191: 		$record{'scantron.useCODE'}=1;
                   5192: 	    }
1.192     albertel 5193: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5194: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5195: 	    }
1.82      albertel 5196: 	} else {
                   5197: 	    #FIXME interpret first N questions
                   5198: 	}
                   5199:     }
1.83      albertel 5200:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5201: 				  $$scantron_config{'IDlength'});
1.157     albertel 5202:     $record{'scantron.PaperID'}=
                   5203: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5204: 	       $$scantron_config{'PaperIDlength'});
                   5205:     $record{'scantron.FirstName'}=
                   5206: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5207: 	       $$scantron_config{'FirstNamelength'});
                   5208:     $record{'scantron.LastName'}=
                   5209: 	substr($data,$$scantron_config{'LastName'}-1,
                   5210: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5211:     if ($just_header) { return \%record; }
1.194     albertel 5212: 
1.82      albertel 5213:     my @alphabet=('A'..'Z');
                   5214:     my $questnum=0;
1.447     foxr     5215:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5216: 
1.82      albertel 5217:     while ($questions) {
1.447     foxr     5218: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5219: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5220: 
                   5221: 
                   5222: 
1.82      albertel 5223: 	$questnum++;
1.447     foxr     5224: 	my $currentquest = substr($questions,0,$answer_length);
                   5225: 	$questions       = substr($questions,0,$answer_length)='';
                   5226: 	if (length($currentquest) < $answer_length) { next; }
                   5227: 
                   5228: 	# Qon letter implies for each slot in currentquest we have:
                   5229: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5230:         #    about anything else (esp. a value of Qoff for missing
                   5231: 	#    bubbles.
                   5232: 
                   5233: 
1.239     albertel 5234: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5235: 
                   5236: 	    if ($currentquest =~ /\?/
                   5237: 		|| $currentquest =~ /\*/
                   5238: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5239: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5240: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5241: 		    $record{"scantron.$ansnum.answer"}='';
                   5242: 		    $ansnum++;
                   5243: 		}
                   5244: 
1.389     albertel 5245: 	    } elsif (!defined($currentquest)
1.447     foxr     5246: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5247: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5248: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5249: 		    $record{"scantron.$ansnum.answer"}='';
                   5250: 		    $ansnum++;
                   5251: 
                   5252: 		}
1.239     albertel 5253: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5254: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5255: 		    $ansnum += $answers_needed;
1.239     albertel 5256: 		}
1.447     foxr     5257: 
1.239     albertel 5258: 	    } else {
1.447     foxr     5259: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5260: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5261: 		    $ansnum++;
                   5262: 		}
1.239     albertel 5263: 	    }
1.447     foxr     5264: 
                   5265: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5266: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5267:         #    and *? for double bubbles on a line.
                   5268: 	#    these answers are also stored as letters.
                   5269: 
1.239     albertel 5270: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5271: 	    if ($currentquest =~ /\?/
                   5272: 		|| $currentquest =~ /\*/
                   5273: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5274: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5275: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5276: 		    $record{"scantron.$ansnum.answer"}='';
                   5277: 		    $ansnum++;
                   5278: 		}
                   5279: 
1.389     albertel 5280: 	    } elsif (!defined($currentquest)
1.447     foxr     5281: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5282: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5283: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5284: 		    $record{"scantron.$ansnum.answer"}='';
                   5285: 		    $ansnum++;
                   5286: 
                   5287: 		}
1.239     albertel 5288: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5289: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5290: 		    $ansnum += $answers_needed;
1.239     albertel 5291: 		}
1.447     foxr     5292: 
1.239     albertel 5293: 	    } else {
1.447     foxr     5294: 		$currentquest = &digits_to_letters($currentquest);
                   5295: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5296: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5297: 		    $ansnum++;
1.371     albertel 5298: 		}
1.239     albertel 5299: 	    }
1.82      albertel 5300: 	} else {
1.447     foxr     5301: 
                   5302: 	    # Otherwise there's a positional notation;
                   5303: 	    # each bubble line requires Qlength items, and there are filled in
                   5304: 	    # bubbles for each case where there 'Qon' characters.
                   5305: 	    #
                   5306: 
1.239     albertel 5307: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5308: 
                   5309: 	    # If the split only  giveas us one element.. the full length of the
                   5310: 	    # answser string, no bubbles are filled in:
                   5311: 
                   5312: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5313: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5314: 		    $record{"scantron.$ansnum.answer"}='';
                   5315: 		    $ansnum++;
                   5316: 
                   5317: 		}
1.239     albertel 5318: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5319: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5320: 		}
1.447     foxr     5321: 	    } elsif (scalar(@array) lt 2) {
                   5322: 
                   5323: 		my $location      = [length($array[0])];
                   5324: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5325: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5326: 
                   5327: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5328: 		    if ($ans eq $line_num) {
                   5329: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5330: 		    } else {
                   5331: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5332: 		    }
                   5333: 		    $ansnum++;
                   5334: 		}
1.239     albertel 5335: 	    }
1.447     foxr     5336: 	    #  If there's more than one instance of a bubble character
                   5337: 	    #  That's a double bubble; with positional notation we can
                   5338: 	    #  record all the bubbles filled in as well as the 
                   5339: 	    #  fact this response consists of multiple bubbles.
                   5340: 	    #
                   5341: 	    else {
1.239     albertel 5342: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5343: 
                   5344: 		my $first_answer = $ansnum;
                   5345: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5346: 		    $record{"scantron.$ansnum.answer"} = '';
                   5347: 		    $ans++;
                   5348: 		}
                   5349: 
1.239     albertel 5350: 		my @ans=@array;
                   5351: 		my $i=length($ans[0]);shift(@ans);
                   5352: 		while ($#ans) {
                   5353: 		    $i+=length($ans[0])+1;
1.447     foxr     5354: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5355: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5356: 
                   5357: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5358: 		    shift(@ans);
                   5359: 		}
                   5360: 	    }
1.82      albertel 5361: 	}
                   5362:     }
1.83      albertel 5363:     $record{'scantron.maxquest'}=$questnum;
                   5364:     return \%record;
1.82      albertel 5365: }
                   5366: 
1.423     albertel 5367: =pod
                   5368: 
                   5369: =item scantron_add_delay
                   5370: 
                   5371:    Adds an error message that occurred during the grading phase to a
                   5372:    queue of messages to be shown after grading pass is complete
                   5373: 
                   5374:  Arguments:
1.424     albertel 5375:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5376:    $scanline    - the scanline that caused the error
                   5377:    $errormesage - the error message
                   5378:    $errorcode   - a numeric code for the error
                   5379: 
                   5380:  Side Effects:
1.424     albertel 5381:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5382: 
                   5383: =cut
                   5384: 
1.82      albertel 5385: sub scantron_add_delay {
1.140     albertel 5386:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5387:     push(@$delayqueue,
                   5388: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5389: 	  'ecode' => $errorcode }
                   5390: 	 );
1.82      albertel 5391: }
                   5392: 
1.423     albertel 5393: =pod
                   5394: 
                   5395: =item scantron_find_student
                   5396: 
1.424     albertel 5397:    Finds the username for the current scanline
                   5398: 
                   5399:   Arguments:
                   5400:    $scantron_record - hash result from scantron_parse_scanline
                   5401:    $scan_data       - hash of correction information 
                   5402:                       (see &scantron_getfile() form more information)
                   5403:    $idmap           - hash from &username_to_idmap()
                   5404:    $line            - number of current scanline
                   5405:  
                   5406:   Returns:
                   5407:    Either 'username:domain' or undef if unknown
                   5408: 
1.423     albertel 5409: =cut
                   5410: 
1.82      albertel 5411: sub scantron_find_student {
1.157     albertel 5412:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5413:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5414:     if ($scanID =~ /^\s*$/) {
                   5415:  	return &scan_data($scan_data,"$line.user");
                   5416:     }
1.83      albertel 5417:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5418:  	if (lc($id) eq lc($scanID)) {
                   5419:  	    return $$idmap{$id};
                   5420:  	}
1.83      albertel 5421:     }
                   5422:     return undef;
                   5423: }
                   5424: 
1.423     albertel 5425: =pod
                   5426: 
                   5427: =item scantron_filter
                   5428: 
1.424     albertel 5429:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5430:    hidden resources was selected
                   5431: 
1.423     albertel 5432: =cut
                   5433: 
1.83      albertel 5434: sub scantron_filter {
                   5435:     my ($curres)=@_;
1.331     albertel 5436: 
                   5437:     if (ref($curres) && $curres->is_problem()) {
                   5438: 	# if the user has asked to not have either hidden
                   5439: 	# or 'randomout' controlled resources to be graded
                   5440: 	# don't include them
                   5441: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5442: 	    && $curres->randomout) {
                   5443: 	    return 0;
                   5444: 	}
1.83      albertel 5445: 	return 1;
                   5446:     }
                   5447:     return 0;
1.82      albertel 5448: }
                   5449: 
1.423     albertel 5450: =pod
                   5451: 
                   5452: =item scantron_process_corrections
                   5453: 
1.424     albertel 5454:    Gets correction information out of submitted form data and corrects
                   5455:    the scanline
                   5456: 
1.423     albertel 5457: =cut
                   5458: 
1.157     albertel 5459: sub scantron_process_corrections {
                   5460:     my ($r) = @_;
1.257     albertel 5461:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5462:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5463:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5464:     my $which=$env{'form.scantron_line'};
1.200     albertel 5465:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5466:     my ($skip,$err,$errmsg);
1.257     albertel 5467:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5468: 	$skip=1;
1.257     albertel 5469:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5470: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5471: 	    $env{'form.scantron_domain'};
1.157     albertel 5472: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5473: 	($line,$err,$errmsg)=
                   5474: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5475: 				     'ID',{'newid'=>$newid,
1.257     albertel 5476: 				    'username'=>$env{'form.scantron_username'},
                   5477: 				    'domain'=>$env{'form.scantron_domain'}});
                   5478:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5479: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5480: 	my $newCODE;
1.192     albertel 5481: 	my %args;
1.190     albertel 5482: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5483: 	    $newCODE='use_unfound';
1.190     albertel 5484: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5485: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5486: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5487: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5488: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5489: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5490: 	}
1.257     albertel 5491: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5492: 	    $args{'CODE_ignore_dup'}=1;
                   5493: 	}
                   5494: 	$args{'CODE'}=$newCODE;
1.186     albertel 5495: 	($line,$err,$errmsg)=
                   5496: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5497: 				     'CODE',\%args);
1.257     albertel 5498:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5499: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5500: 	    ($line,$err,$errmsg)=
                   5501: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5502: 					 $which,'answer',
                   5503: 					 { 'question'=>$question,
1.257     albertel 5504: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5505: 	    if ($err) { last; }
                   5506: 	}
                   5507:     }
                   5508:     if ($err) {
1.398     albertel 5509: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5510:     } else {
1.200     albertel 5511: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5512: 	&scantron_putfile($scanlines,$scan_data);
                   5513:     }
                   5514: }
                   5515: 
1.423     albertel 5516: =pod
                   5517: 
                   5518: =item reset_skipping_status
                   5519: 
1.424     albertel 5520:    Forgets the current set of remember skipped scanlines (and thus
                   5521:    reverts back to considering all lines in the
                   5522:    scantron_skipped_<filename> file)
                   5523: 
1.423     albertel 5524: =cut
                   5525: 
1.200     albertel 5526: sub reset_skipping_status {
                   5527:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5528:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5529:     &scantron_putfile(undef,$scan_data);
                   5530: }
                   5531: 
1.423     albertel 5532: =pod
                   5533: 
                   5534: =item start_skipping
                   5535: 
1.424     albertel 5536:    Marks a scanline to be skipped. 
                   5537: 
1.423     albertel 5538: =cut
                   5539: 
1.376     albertel 5540: sub start_skipping {
1.200     albertel 5541:     my ($scan_data,$i)=@_;
                   5542:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5543:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5544: 	$remembered{$i}=2;
                   5545:     } else {
                   5546: 	$remembered{$i}=1;
                   5547:     }
1.200     albertel 5548:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5549: }
                   5550: 
1.423     albertel 5551: =pod
                   5552: 
                   5553: =item should_be_skipped
                   5554: 
1.424     albertel 5555:    Checks whether a scanline should be skipped.
                   5556: 
1.423     albertel 5557: =cut
                   5558: 
1.200     albertel 5559: sub should_be_skipped {
1.376     albertel 5560:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5561:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5562: 	# not redoing old skips
1.376     albertel 5563: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5564: 	return 0;
                   5565:     }
                   5566:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5567: 
                   5568:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5569: 	return 0;
                   5570:     }
1.200     albertel 5571:     return 1;
                   5572: }
                   5573: 
1.423     albertel 5574: =pod
                   5575: 
                   5576: =item remember_current_skipped
                   5577: 
1.424     albertel 5578:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5579:    file and remembers them into scan_data for later use.
                   5580: 
1.423     albertel 5581: =cut
                   5582: 
1.200     albertel 5583: sub remember_current_skipped {
                   5584:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5585:     my %to_remember;
                   5586:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5587: 	if ($scanlines->{'skipped'}[$i]) {
                   5588: 	    $to_remember{$i}=1;
                   5589: 	}
                   5590:     }
1.376     albertel 5591: 
1.200     albertel 5592:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5593:     &scantron_putfile(undef,$scan_data);
                   5594: }
                   5595: 
1.423     albertel 5596: =pod
                   5597: 
                   5598: =item check_for_error
                   5599: 
1.424     albertel 5600:     Checks if there was an error when attempting to remove a specific
                   5601:     scantron_.. bubble sheet data file. Prints out an error if
                   5602:     something went wrong.
                   5603: 
1.423     albertel 5604: =cut
                   5605: 
1.200     albertel 5606: sub check_for_error {
                   5607:     my ($r,$result)=@_;
                   5608:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5609: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5610:     }
                   5611: }
1.157     albertel 5612: 
1.423     albertel 5613: =pod
                   5614: 
                   5615: =item scantron_warning_screen
                   5616: 
1.424     albertel 5617:    Interstitial screen to make sure the operator has selected the
                   5618:    correct options before we start the validation phase.
                   5619: 
1.423     albertel 5620: =cut
                   5621: 
1.203     albertel 5622: sub scantron_warning_screen {
                   5623:     my ($button_text)=@_;
1.257     albertel 5624:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5625:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5626:     my $CODElist;
1.284     albertel 5627:     if ($scantron_config{'CODElocation'} &&
                   5628: 	$scantron_config{'CODEstart'} &&
                   5629: 	$scantron_config{'CODElength'}) {
                   5630: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5631: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5632: 	$CODElist=
                   5633: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5634: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5635:     }
1.203     albertel 5636:     return (<<STUFF);
                   5637: <p>
1.398     albertel 5638: <span class="LC_warning">Please double check the information
                   5639:                  below before clicking on '$button_text'</span>
1.203     albertel 5640: </p>
                   5641: <table>
1.284     albertel 5642: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5643: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5644: $CODElist
1.203     albertel 5645: </table>
                   5646: <br />
                   5647: <p> If this information is correct, please click on '$button_text'.</p>
                   5648: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5649: 
                   5650: <br />
                   5651: STUFF
                   5652: }
                   5653: 
1.423     albertel 5654: =pod
                   5655: 
                   5656: =item scantron_do_warning
                   5657: 
1.424     albertel 5658:    Check if the operator has picked something for all required
                   5659:    fields. Error out if something is missing.
                   5660: 
1.423     albertel 5661: =cut
                   5662: 
1.203     albertel 5663: sub scantron_do_warning {
                   5664:     my ($r)=@_;
1.324     albertel 5665:     my ($symb)=&get_symb($r);
1.203     albertel 5666:     if (!$symb) {return '';}
1.324     albertel 5667:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5668:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5669:     if ( $env{'form.selectpage'} eq '' ||
                   5670: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5671: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5672: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5673: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5674: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5675: 	} 
1.257     albertel 5676: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5677: 	    $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 5678: 	} 
1.257     albertel 5679: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5680: 	    $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 5681: 	} 
                   5682:     } else {
1.265     www      5683: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5684: 	$r->print(<<STUFF);
1.203     albertel 5685: $warning
1.265     www      5686: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5687: <input type="hidden" name="command" value="scantron_validate" />
                   5688: STUFF
1.237     albertel 5689:     }
1.352     albertel 5690:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5691:     return '';
                   5692: }
                   5693: 
1.423     albertel 5694: =pod
                   5695: 
                   5696: =item scantron_form_start
                   5697: 
1.424     albertel 5698:     html hidden input for remembering all selected grading options
                   5699: 
1.423     albertel 5700: =cut
                   5701: 
1.203     albertel 5702: sub scantron_form_start {
                   5703:     my ($max_bubble)=@_;
                   5704:     my $result= <<SCANTRONFORM;
                   5705: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5706:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5707:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5708:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5709:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5710:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5711:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5712:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5713:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5714:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5715: SCANTRONFORM
1.447     foxr     5716: 
                   5717:   my $line = 0;
                   5718:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448   ! foxr     5719: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5720:        my $chunk =
                   5721: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448   ! foxr     5722:        $chunk .=
        !          5723: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5724:        $result .= $chunk;
                   5725:        $line++;
                   5726:    }
1.203     albertel 5727:     return $result;
                   5728: }
                   5729: 
1.423     albertel 5730: =pod
                   5731: 
                   5732: =item scantron_validate_file
                   5733: 
1.424     albertel 5734:     Dispatch routine for doing validation of a bubble sheet data file.
                   5735: 
                   5736:     Also processes any necessary information resets that need to
                   5737:     occur before validation begins (ignore previous corrections,
                   5738:     restarting the skipped records processing)
                   5739: 
1.423     albertel 5740: =cut
                   5741: 
1.157     albertel 5742: sub scantron_validate_file {
                   5743:     my ($r) = @_;
1.324     albertel 5744:     my ($symb)=&get_symb($r);
1.157     albertel 5745:     if (!$symb) {return '';}
1.324     albertel 5746:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5747:     
                   5748:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5749:     # them when doing the corrections reset
1.257     albertel 5750:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5751: 	&reset_skipping_status();
                   5752:     }
1.257     albertel 5753:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5754: 	&remember_current_skipped();
1.257     albertel 5755: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5756:     }
                   5757: 
1.257     albertel 5758:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5759: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5760: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5761: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5762: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5763:     }
1.200     albertel 5764: 
1.257     albertel 5765:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5766: 	&scantron_process_corrections($r);
                   5767:     }
1.424     albertel 5768:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5769:     #get the student pick code ready
                   5770:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5771:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5772:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5773:     $r->print($result);
                   5774:     
1.334     albertel 5775:     my @validate_phases=( 'sequence',
                   5776: 			  'ID',
1.157     albertel 5777: 			  'CODE',
                   5778: 			  'doublebubble',
                   5779: 			  'missingbubbles');
1.257     albertel 5780:     if (!$env{'form.validatepass'}) {
                   5781: 	$env{'form.validatepass'} = 0;
1.157     albertel 5782:     }
1.257     albertel 5783:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5784: 
1.448   ! foxr     5785:     &Apache::lonnet::logthis("Phase: $currentphase");
        !          5786: 
1.157     albertel 5787:     my $stop=0;
                   5788:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5789: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5790: 	$r->rflush();
                   5791: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5792: 	{
                   5793: 	    no strict 'refs';
                   5794: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5795: 	}
                   5796:     }
                   5797:     if (!$stop) {
1.203     albertel 5798: 	my $warning=&scantron_warning_screen('Start Grading');
                   5799: 	$r->print(<<STUFF);
                   5800: Validation process complete.<br />
                   5801: $warning
                   5802: <input type="submit" name="submit" value="Start Grading" />
                   5803: <input type="hidden" name="command" value="scantron_process" />
                   5804: STUFF
                   5805: 
1.157     albertel 5806:     } else {
                   5807: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5808: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5809:     }
                   5810:     if ($stop) {
1.334     albertel 5811: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5812: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5813: 	    $r->print(' this error <br />');
                   5814: 
                   5815: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5816: 	} else {
                   5817: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5818: 	    $r->print(' using corrected info <br />');
                   5819: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5820: 	    $r->print(" this scanline saving it for later.");
                   5821: 	}
1.157     albertel 5822:     }
1.352     albertel 5823:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5824:     return '';
                   5825: }
                   5826: 
1.423     albertel 5827: 
                   5828: =pod
                   5829: 
                   5830: =item scantron_remove_file
                   5831: 
1.424     albertel 5832:    Removes the requested bubble sheet data file, makes sure that
                   5833:    scantron_original_<filename> is never removed
                   5834: 
                   5835: 
1.423     albertel 5836: =cut
                   5837: 
1.200     albertel 5838: sub scantron_remove_file {
1.192     albertel 5839:     my ($which)=@_;
1.257     albertel 5840:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5841:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5842:     my $file='scantron_';
1.200     albertel 5843:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5844: 	$file.=$which.'_';
1.192     albertel 5845:     } else {
                   5846: 	return 'refused';
                   5847:     }
1.257     albertel 5848:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5849:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5850: }
                   5851: 
1.423     albertel 5852: 
                   5853: =pod
                   5854: 
                   5855: =item scantron_remove_scan_data
                   5856: 
1.424     albertel 5857:    Removes all scan_data correction for the requested bubble sheet
                   5858:    data file.  (In the case that both the are doing skipped records we need
                   5859:    to remember the old skipped lines for the time being so that element
                   5860:    persists for a while.)
                   5861: 
1.423     albertel 5862: =cut
                   5863: 
1.200     albertel 5864: sub scantron_remove_scan_data {
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 @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5868:     my @todelete;
1.257     albertel 5869:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5870:     foreach my $key (@keys) {
                   5871: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5872: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5873: 		$key=~/remember_skipping/) {
                   5874: 		next;
                   5875: 	    }
1.192     albertel 5876: 	    push(@todelete,$key);
                   5877: 	}
                   5878:     }
1.200     albertel 5879:     my $result;
1.192     albertel 5880:     if (@todelete) {
1.200     albertel 5881: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5882:     }
                   5883:     return $result;
                   5884: }
                   5885: 
1.423     albertel 5886: 
                   5887: =pod
                   5888: 
                   5889: =item scantron_getfile
                   5890: 
1.424     albertel 5891:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5892:     the scan_data hash
                   5893:   
                   5894:   Arguments:
                   5895:     None
                   5896: 
                   5897:   Returns:
                   5898:     2 hash references
                   5899: 
                   5900:      - first one has 
                   5901:          orig      -
                   5902:          corrected -
                   5903:          skipped   -  each of which points to an array ref of the specified
                   5904:                       file broken up into individual lines
                   5905:          count     - number of scanlines
                   5906:  
                   5907:      - second is the scan_data hash possible keys are
1.425     albertel 5908:        ($number refers to scanline numbered $number and thus the key affects
                   5909:         only that scanline
                   5910:         $bubline refers to the specific bubble line element and the aspects
                   5911:         refers to that specific bubble line element)
                   5912: 
                   5913:        $number.user - username:domain to use
                   5914:        $number.CODE_ignore_dup 
                   5915:                     - ignore the duplicate CODE error 
                   5916:        $number.useCODE
                   5917:                     - use the CODE in the scanline as is
                   5918:        $number.no_bubble.$bubline
                   5919:                     - it is valid that there is no bubbled in bubble
                   5920:                       at $number $bubline
                   5921:        remember_skipping
                   5922:                     - a frozen hash containing keys of $number and values
                   5923:                       of either 
                   5924:                         1 - we are on a 'do skipped records pass' and plan
                   5925:                             on processing this line
                   5926:                         2 - we are on a 'do skipped records pass' and this
                   5927:                             scanline has been marked to skip yet again
1.424     albertel 5928: 
1.423     albertel 5929: =cut
                   5930: 
1.157     albertel 5931: sub scantron_getfile {
1.200     albertel 5932:     #FIXME really would prefer a scantron directory
1.257     albertel 5933:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5934:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5935:     my $lines;
                   5936:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5937: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5938:     my %scanlines;
                   5939:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5940:     my $temp=$scanlines{'orig'};
                   5941:     $scanlines{'count'}=$#$temp;
                   5942: 
                   5943:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5944: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5945:     if ($lines eq '-1') {
                   5946: 	$scanlines{'corrected'}=[];
                   5947:     } else {
                   5948: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5949:     }
                   5950:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5951: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5952:     if ($lines eq '-1') {
                   5953: 	$scanlines{'skipped'}=[];
                   5954:     } else {
                   5955: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5956:     }
1.175     albertel 5957:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5958:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5959:     my %scan_data = @tmp;
                   5960:     return (\%scanlines,\%scan_data);
                   5961: }
                   5962: 
1.423     albertel 5963: =pod
                   5964: 
                   5965: =item lonnet_putfile
                   5966: 
1.424     albertel 5967:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5968: 
                   5969:  Arguments:
                   5970:    $contents - data to store
                   5971:    $filename - filename to store $contents into
                   5972: 
                   5973:  Returns:
                   5974:    result value from &Apache::lonnet::finishuserfileupload
                   5975: 
1.423     albertel 5976: =cut
                   5977: 
1.157     albertel 5978: sub lonnet_putfile {
                   5979:     my ($contents,$filename)=@_;
1.257     albertel 5980:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5981:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5982:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5983:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5984: 
                   5985: }
                   5986: 
1.423     albertel 5987: =pod
                   5988: 
                   5989: =item scantron_putfile
                   5990: 
1.424     albertel 5991:     Stores the current version of the bubble sheet data files, and the
                   5992:     scan_data hash. (Does not modify the original version only the
                   5993:     corrected and skipped versions.
                   5994: 
                   5995:  Arguments:
                   5996:     $scanlines - hash ref that looks like the first return value from
                   5997:                  &scantron_getfile()
                   5998:     $scan_data - hash ref that looks like the second return value from
                   5999:                  &scantron_getfile()
                   6000: 
1.423     albertel 6001: =cut
                   6002: 
1.157     albertel 6003: sub scantron_putfile {
                   6004:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6005:     #FIXME really would prefer a scantron directory
1.257     albertel 6006:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6007:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6008:     if ($scanlines) {
                   6009: 	my $prefix='scantron_';
1.157     albertel 6010: # no need to update orig, shouldn't change
                   6011: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6012: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6013: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6014: 			$prefix.'corrected_'.
1.257     albertel 6015: 			$env{'form.scantron_selectfile'});
1.200     albertel 6016: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6017: 			$prefix.'skipped_'.
1.257     albertel 6018: 			$env{'form.scantron_selectfile'});
1.200     albertel 6019:     }
1.175     albertel 6020:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6021: }
                   6022: 
1.423     albertel 6023: =pod
                   6024: 
                   6025: =item scantron_get_line
                   6026: 
1.424     albertel 6027:    Returns the correct version of the scanline
                   6028: 
                   6029:  Arguments:
                   6030:     $scanlines - hash ref that looks like the first return value from
                   6031:                  &scantron_getfile()
                   6032:     $scan_data - hash ref that looks like the second return value from
                   6033:                  &scantron_getfile()
                   6034:     $i         - number of the requested line (starts at 0)
                   6035: 
                   6036:  Returns:
                   6037:    A scanline, (either the original or the corrected one if it
                   6038:    exists), or undef if the requested scanline should be
                   6039:    skipped. (Either because it's an skipped scanline, or it's an
                   6040:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6041:    pass.
                   6042: 
1.423     albertel 6043: =cut
                   6044: 
1.157     albertel 6045: sub scantron_get_line {
1.200     albertel 6046:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6047:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6048:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6049:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6050:     return $scanlines->{'orig'}[$i]; 
                   6051: }
                   6052: 
1.423     albertel 6053: =pod
                   6054: 
                   6055: =item scantron_todo_count
                   6056: 
1.424     albertel 6057:     Counts the number of scanlines that need processing.
                   6058: 
                   6059:  Arguments:
                   6060:     $scanlines - hash ref that looks like the first return value from
                   6061:                  &scantron_getfile()
                   6062:     $scan_data - hash ref that looks like the second return value from
                   6063:                  &scantron_getfile()
                   6064: 
                   6065:  Returns:
                   6066:     $count - number of scanlines to process
                   6067: 
1.423     albertel 6068: =cut
                   6069: 
1.200     albertel 6070: sub get_todo_count {
                   6071:     my ($scanlines,$scan_data)=@_;
                   6072:     my $count=0;
                   6073:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6074: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6075: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6076: 	$count++;
                   6077:     }
                   6078:     return $count;
                   6079: }
                   6080: 
1.423     albertel 6081: =pod
                   6082: 
                   6083: =item scantron_put_line
                   6084: 
1.424     albertel 6085:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6086:     data file.
                   6087: 
                   6088:  Arguments:
                   6089:     $scanlines - hash ref that looks like the first return value from
                   6090:                  &scantron_getfile()
                   6091:     $scan_data - hash ref that looks like the second return value from
                   6092:                  &scantron_getfile()
                   6093:     $i         - line number to update
                   6094:     $newline   - contents of the updated scanline
                   6095:     $skip      - if true make the line for skipping and update the
                   6096:                  'skipped' file
                   6097: 
1.423     albertel 6098: =cut
                   6099: 
1.157     albertel 6100: sub scantron_put_line {
1.200     albertel 6101:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6102:     if ($skip) {
                   6103: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6104: 	&start_skipping($scan_data,$i);
1.157     albertel 6105: 	return;
                   6106:     }
                   6107:     $scanlines->{'corrected'}[$i]=$newline;
                   6108: }
                   6109: 
1.423     albertel 6110: =pod
                   6111: 
                   6112: =item scantron_clear_skip
                   6113: 
1.424     albertel 6114:    Remove a line from the 'skipped' file
                   6115: 
                   6116:  Arguments:
                   6117:     $scanlines - hash ref that looks like the first return value from
                   6118:                  &scantron_getfile()
                   6119:     $scan_data - hash ref that looks like the second return value from
                   6120:                  &scantron_getfile()
                   6121:     $i         - line number to update
                   6122: 
1.423     albertel 6123: =cut
                   6124: 
1.376     albertel 6125: sub scantron_clear_skip {
                   6126:     my ($scanlines,$scan_data,$i)=@_;
                   6127:     if (exists($scanlines->{'skipped'}[$i])) {
                   6128: 	undef($scanlines->{'skipped'}[$i]);
                   6129: 	return 1;
                   6130:     }
                   6131:     return 0;
                   6132: }
                   6133: 
1.423     albertel 6134: =pod
                   6135: 
                   6136: =item scantron_filter_not_exam
                   6137: 
1.424     albertel 6138:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6139:    filter out resources that are not marked as 'exam' mode
                   6140: 
1.423     albertel 6141: =cut
                   6142: 
1.334     albertel 6143: sub scantron_filter_not_exam {
                   6144:     my ($curres)=@_;
                   6145:     
                   6146:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6147: 	# if the user has asked to not have either hidden
                   6148: 	# or 'randomout' controlled resources to be graded
                   6149: 	# don't include them
                   6150: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6151: 	    && $curres->randomout) {
                   6152: 	    return 0;
                   6153: 	}
                   6154: 	return 1;
                   6155:     }
                   6156:     return 0;
                   6157: }
                   6158: 
1.423     albertel 6159: =pod
                   6160: 
                   6161: =item scantron_validate_sequence
                   6162: 
1.424     albertel 6163:     Validates the selected sequence, checking for resource that are
                   6164:     not set to exam mode.
                   6165: 
1.423     albertel 6166: =cut
                   6167: 
1.334     albertel 6168: sub scantron_validate_sequence {
                   6169:     my ($r,$currentphase) = @_;
                   6170: 
                   6171:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6172:     my (undef,undef,$sequence)=
                   6173: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6174: 
                   6175:     my $map=$navmap->getResourceByUrl($sequence);
                   6176: 
                   6177:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6178:                                     value="ignore" />');
                   6179:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6180: 	my @resources=
                   6181: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6182: 	if (@resources) {
1.357     banghart 6183: 	    $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 6184: 	    return (1,$currentphase);
                   6185: 	}
                   6186:     }
                   6187: 
                   6188:     return (0,$currentphase+1);
                   6189: }
                   6190: 
1.423     albertel 6191: =pod
                   6192: 
                   6193: =item scantron_validate_ID
                   6194: 
1.424     albertel 6195:    Validates all scanlines in the selected file to not have any
                   6196:    invalid or underspecified student IDs
                   6197: 
1.423     albertel 6198: =cut
                   6199: 
1.157     albertel 6200: sub scantron_validate_ID {
                   6201:     my ($r,$currentphase) = @_;
                   6202:     
                   6203:     #get student info
                   6204:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6205:     my %idmap=&username_to_idmap($classlist);
                   6206: 
                   6207:     #get scantron line setup
1.257     albertel 6208:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6209:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6210:     
                   6211:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6212: 
                   6213:     my %found=('ids'=>{},'usernames'=>{});
                   6214:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6215: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6216: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6217: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6218: 						 $scan_data);
                   6219: 	my $id=$$scan_record{'scantron.ID'};
                   6220: 	my $found;
                   6221: 	foreach my $checkid (keys(%idmap)) {
                   6222: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6223: 	}
                   6224: 	if ($found) {
                   6225: 	    my $username=$idmap{$found};
                   6226: 	    if ($found{'ids'}{$found}) {
                   6227: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6228: 					 $line,'duplicateID',$found);
1.194     albertel 6229: 		return(1,$currentphase);
1.157     albertel 6230: 	    } elsif ($found{'usernames'}{$username}) {
                   6231: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6232: 					 $line,'duplicateID',$username);
1.194     albertel 6233: 		return(1,$currentphase);
1.157     albertel 6234: 	    }
1.186     albertel 6235: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6236: 	    $found{'ids'}{$found}++;
                   6237: 	    $found{'usernames'}{$username}++;
                   6238: 	} else {
                   6239: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6240: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6241: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6242: 		    &scantron_get_correction($r,$i,$scan_record,
                   6243: 					     \%scantron_config,
                   6244: 					     $line,'duplicateID',$username);
1.194     albertel 6245: 		    return(1,$currentphase);
1.157     albertel 6246: 		} elsif (!defined($username)) {
                   6247: 		    &scantron_get_correction($r,$i,$scan_record,
                   6248: 					     \%scantron_config,
                   6249: 					     $line,'incorrectID');
1.194     albertel 6250: 		    return(1,$currentphase);
1.157     albertel 6251: 		}
                   6252: 		$found{'usernames'}{$username}++;
                   6253: 	    } else {
                   6254: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6255: 					 $line,'incorrectID');
1.194     albertel 6256: 		return(1,$currentphase);
1.157     albertel 6257: 	    }
                   6258: 	}
                   6259:     }
                   6260: 
                   6261:     return (0,$currentphase+1);
                   6262: }
                   6263: 
1.423     albertel 6264: =pod
                   6265: 
                   6266: =item scantron_get_correction
                   6267: 
1.424     albertel 6268:    Builds the interface screen to interact with the operator to fix a
                   6269:    specific error condition in a specific scanline
                   6270: 
                   6271:  Arguments:
                   6272:     $r           - Apache request object
                   6273:     $i           - number of the current scanline
                   6274:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6275:     $scan_config - hash ref as returned from &get_scantron_config()
                   6276:     $line        - full contents of the current scanline
                   6277:     $error       - error condition, valid values are
                   6278:                    'incorrectCODE', 'duplicateCODE',
                   6279:                    'doublebubble', 'missingbubble',
                   6280:                    'duplicateID', 'incorrectID'
                   6281:     $arg         - extra information needed
                   6282:        For errors:
                   6283:          - duplicateID   - paper number that this studentID was seen before on
                   6284:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6285:                            seen on before
                   6286:          - incorrectCODE - current incorrect CODE 
                   6287:          - doublebubble  - array ref of the bubble lines that have double
                   6288:                            bubble errors
                   6289:          - missingbubble - array ref of the bubble lines that have missing
                   6290:                            bubble errors
                   6291: 
1.423     albertel 6292: =cut
                   6293: 
1.157     albertel 6294: sub scantron_get_correction {
                   6295:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6296: 
                   6297: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6298: #to show both the current line and the previous one and allow skipping
                   6299: #the previous one or the current one
                   6300: 
1.161     albertel 6301:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6302:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6303: 	$r->print(" for PaperID <tt>".
                   6304: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6305:     } else {
                   6306: 	$r->print(" in scanline $i <pre>".
                   6307: 		  $line."</pre> \n");
                   6308:     }
1.242     albertel 6309:     my $message="<p>The ID on the form is  <tt>".
                   6310: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6311: 	"The name on the paper is ".
                   6312: 	$$scan_record{'scantron.LastName'}.",".
                   6313: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6314: 
1.157     albertel 6315:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6316:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6317:     if ($error =~ /ID$/) {
1.186     albertel 6318: 	if ($error eq 'incorrectID') {
1.157     albertel 6319: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6320: 	} elsif ($error eq 'duplicateID') {
                   6321: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6322: 	}
1.242     albertel 6323: 	$r->print($message);
1.157     albertel 6324: 	$r->print("<p>How should I handle this? <br /> \n");
                   6325: 	$r->print("\n<ul><li> ");
                   6326: 	#FIXME it would be nice if this sent back the user ID and
                   6327: 	#could do partial userID matches
                   6328: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6329: 				       'scantron_username','scantron_domain'));
                   6330: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6331: 	$r->print("\n@".
1.257     albertel 6332: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6333: 
                   6334: 	$r->print('</li>');
1.186     albertel 6335:     } elsif ($error =~ /CODE$/) {
                   6336: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6337: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6338: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6339: 	    $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 6340: 	}
1.224     albertel 6341: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6342: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6343: 	$r->print($message);
1.186     albertel 6344: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6345: 	$r->print("\n<br /> ");
1.194     albertel 6346: 	my $i=0;
1.273     albertel 6347: 	if ($error eq 'incorrectCODE' 
                   6348: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6349: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6350: 	    if ($closest > 0) {
                   6351: 		foreach my $testcode (@{$closest}) {
                   6352: 		    my $checked='';
1.401     albertel 6353: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6354: 		    $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' />");
                   6355: 		    $r->print("\n<br />");
                   6356: 		    $i++;
                   6357: 		}
1.194     albertel 6358: 	    }
                   6359: 	}
1.273     albertel 6360: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6361: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6362: 	    $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>");
                   6363: 	    $r->print("\n<br />");
                   6364: 	}
1.194     albertel 6365: 
1.188     albertel 6366: 	$r->print(<<ENDSCRIPT);
                   6367: <script type="text/javascript">
                   6368: function change_radio(field) {
1.190     albertel 6369:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6370:     var i;
                   6371:     for (i=0;i<slct.length;i++) {
                   6372:         if (slct[i].value==field) { slct[i].checked=true; }
                   6373:     }
                   6374: }
                   6375: </script>
                   6376: ENDSCRIPT
1.187     albertel 6377: 	my $href="/adm/pickcode?".
1.359     www      6378: 	   "form=".&escape("scantronupload").
                   6379: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6380: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6381: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6382: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6383: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6384: 	    $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')\" />");
                   6385: 	    $r->print("\n<br />");
                   6386: 	}
1.272     albertel 6387: 	$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 6388: 	$r->print("\n<br /><br />");
1.157     albertel 6389:     } elsif ($error eq 'doublebubble') {
                   6390: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6391: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6392: 		  join(',',@{$arg}).'" />');
1.242     albertel 6393: 	$r->print($message);
1.157     albertel 6394: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6395: 	foreach my $question (@{$arg}) {
1.447     foxr     6396: 
                   6397: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6398: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6399: 				      split('',$selected));
1.157     albertel 6400: 	}
                   6401:     } elsif ($error eq 'missingbubble') {
                   6402: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6403: 	$r->print($message);
1.157     albertel 6404: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6405: 	$r->print("Some questions have no scanned bubbles\n");
                   6406: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6407: 		  join(',',@{$arg}).'" />');
                   6408: 	foreach my $question (@{$arg}) {
1.448   ! foxr     6409: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6410: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6411: 	}
                   6412:     } else {
                   6413: 	$r->print("\n<ul>");
                   6414:     }
                   6415:     $r->print("\n</li></ul>");
                   6416: 
                   6417: }
1.423     albertel 6418: 
                   6419: =pod
                   6420: 
                   6421: =item scantron_bubble_selector
                   6422:   
                   6423:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6424:    possibly showing the existing the selected bubbles if known
1.423     albertel 6425: 
                   6426:  Arguments:
                   6427:     $r           - Apache request object
                   6428:     $scan_config - hash from &get_scantron_config()
                   6429:     $quest       - number of the bubble line to make a corrector for
                   6430:     $selected    - array of letters of previously selected bubbles
                   6431: 
                   6432: =cut
                   6433: 
1.157     albertel 6434: sub scantron_bubble_selector {
1.447     foxr     6435:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6436:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6437: 
                   6438:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6439: 
                   6440: 
1.274     albertel 6441:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6442: 
1.448   ! foxr     6443:     my $response = $quest-1;
        !          6444:     my $lines = $bubble_lines_per_response{$response};
        !          6445:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6446: 
1.422     foxr     6447:     my $total_lines = $lines*2;
1.157     albertel 6448:     my @alphabet=('A'..'Z');
1.422     foxr     6449:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6450: 
                   6451:     for (my $l = 0; $l < $lines; $l++) {
                   6452: 	if ($l != 0) {
                   6453: 	    $r->print('<tr>');
                   6454: 	}
                   6455: 
                   6456: 	# FIXME:  This loop probably has to be considerably more clever for
                   6457: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6458: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6459: 
                   6460: 	for (my $i=0;$i<$max;$i++) {
                   6461: 	    $r->print("\n".'<td align="center">');
                   6462: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6463: 		$r->print('X'); 
                   6464: 		shift(@selected) ;
                   6465: 	    } else { 
                   6466: 		$r->print('&nbsp;'); 
                   6467: 	    }
                   6468: 	    $r->print('</td>');
                   6469: 	    
                   6470: 	}
                   6471: 
                   6472: 	if ($l == 0) {
                   6473: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6474: 
                   6475: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6476: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6477: 	
                   6478: 	}
                   6479: 
                   6480: 	$r->print('</tr><tr>');
                   6481: 
                   6482: 	# FIXME: This may have to be a bit more clever for
                   6483: 	#        multiline questions (different values e.g..).
                   6484: 
                   6485: 	for (my $i=0;$i<$max;$i++) {
                   6486: 	    $r->print("\n".
                   6487: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6488: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6489: 	}
                   6490: 	$r->print('</tr>');
                   6491: 
                   6492: 	    
1.157     albertel 6493:     }
1.422     foxr     6494:     $r->print('</table>');
1.157     albertel 6495: }
                   6496: 
1.423     albertel 6497: =pod
                   6498: 
                   6499: =item num_matches
                   6500: 
1.424     albertel 6501:    Counts the number of characters that are the same between the two arguments.
                   6502: 
                   6503:  Arguments:
                   6504:    $orig - CODE from the scanline
                   6505:    $code - CODE to match against
                   6506: 
                   6507:  Returns:
                   6508:    $count - integer count of the number of same characters between the
                   6509:             two arguments
                   6510: 
1.423     albertel 6511: =cut
                   6512: 
1.194     albertel 6513: sub num_matches {
                   6514:     my ($orig,$code) = @_;
                   6515:     my @code=split(//,$code);
                   6516:     my @orig=split(//,$orig);
                   6517:     my $same=0;
                   6518:     for (my $i=0;$i<scalar(@code);$i++) {
                   6519: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6520:     }
                   6521:     return $same;
                   6522: }
                   6523: 
1.423     albertel 6524: =pod
                   6525: 
                   6526: =item scantron_get_closely_matching_CODEs
                   6527: 
1.424     albertel 6528:    Cycles through all CODEs and finds the set that has the greatest
                   6529:    number of same characters as the provided CODE
                   6530: 
                   6531:  Arguments:
                   6532:    $allcodes - hash ref returned by &get_codes()
                   6533:    $CODE     - CODE from the current scanline
                   6534: 
                   6535:  Returns:
                   6536:    2 element list
                   6537:     - first elements is number of how closely matching the best fit is 
                   6538:       (5 means best set has 5 matching characters)
                   6539:     - second element is an arrary ref containing the set of valid CODEs
                   6540:       that best fit the passed in CODE
                   6541: 
1.423     albertel 6542: =cut
                   6543: 
1.194     albertel 6544: sub scantron_get_closely_matching_CODEs {
                   6545:     my ($allcodes,$CODE)=@_;
                   6546:     my @CODEs;
                   6547:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6548: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6549:     }
                   6550: 
                   6551:     return ($#CODEs,$CODEs[-1]);
                   6552: }
                   6553: 
1.423     albertel 6554: =pod
                   6555: 
                   6556: =item get_codes
                   6557: 
1.424     albertel 6558:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6559:    set of remembered CODEs.
                   6560: 
                   6561:  Arguments:
                   6562:   $old_name - name of the set of remembered CODEs
                   6563:   $cdom     - domain of the course
                   6564:   $cnum     - internal course name
                   6565: 
                   6566:  Returns:
                   6567:   %allcodes - keys are the valid CODEs, values are all 1
                   6568: 
1.423     albertel 6569: =cut
                   6570: 
1.194     albertel 6571: sub get_codes {
1.280     foxr     6572:     my ($old_name, $cdom, $cnum) = @_;
                   6573:     if (!$old_name) {
                   6574: 	$old_name=$env{'form.scantron_CODElist'};
                   6575:     }
                   6576:     if (!$cdom) {
                   6577: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6578:     }
                   6579:     if (!$cnum) {
                   6580: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6581:     }
1.278     albertel 6582:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6583: 				    $cdom,$cnum);
                   6584:     my %allcodes;
                   6585:     if ($result{"type\0$old_name"} eq 'number') {
                   6586: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6587:     } else {
                   6588: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6589:     }
1.194     albertel 6590:     return %allcodes;
                   6591: }
                   6592: 
1.423     albertel 6593: =pod
                   6594: 
                   6595: =item scantron_validate_CODE
                   6596: 
1.424     albertel 6597:    Validates all scanlines in the selected file to not have any
                   6598:    invalid or underspecified CODEs and that none of the codes are
                   6599:    duplicated if this was requested.
                   6600: 
1.423     albertel 6601: =cut
                   6602: 
1.157     albertel 6603: sub scantron_validate_CODE {
                   6604:     my ($r,$currentphase) = @_;
1.257     albertel 6605:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6606:     if ($scantron_config{'CODElocation'} &&
                   6607: 	$scantron_config{'CODEstart'} &&
                   6608: 	$scantron_config{'CODElength'}) {
1.257     albertel 6609: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6610: 	    &FIXME_blow_up()
                   6611: 	}
                   6612:     } else {
                   6613: 	return (0,$currentphase+1);
                   6614:     }
                   6615:     
                   6616:     my %usedCODEs;
                   6617: 
1.194     albertel 6618:     my %allcodes=&get_codes();
1.186     albertel 6619: 
1.447     foxr     6620:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6621: 
1.186     albertel 6622:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6623:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6624: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6625: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6626: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6627: 						 $scan_data);
                   6628: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6629: 	my $error=0;
1.224     albertel 6630: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6631: 	    &scantron_get_correction($r,$i,$scan_record,
                   6632: 				     \%scantron_config,
                   6633: 				     $line,'incorrectCODE',\%allcodes);
                   6634: 	    return(1,$currentphase);
                   6635: 	}
1.221     albertel 6636: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6637: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6638: 	    &scantron_get_correction($r,$i,$scan_record,
                   6639: 				     \%scantron_config,
1.194     albertel 6640: 				     $line,'incorrectCODE',\%allcodes);
                   6641: 	    return(1,$currentphase);
1.186     albertel 6642: 	}
1.214     albertel 6643: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6644: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6645: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6646: 	    &scantron_get_correction($r,$i,$scan_record,
                   6647: 				     \%scantron_config,
1.194     albertel 6648: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6649: 	    return(1,$currentphase);
1.186     albertel 6650: 	}
1.194     albertel 6651: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6652:     }
1.157     albertel 6653:     return (0,$currentphase+1);
                   6654: }
                   6655: 
1.423     albertel 6656: =pod
                   6657: 
                   6658: =item scantron_validate_doublebubble
                   6659: 
1.424     albertel 6660:    Validates all scanlines in the selected file to not have any
                   6661:    bubble lines with multiple bubbles marked.
                   6662: 
1.423     albertel 6663: =cut
                   6664: 
1.157     albertel 6665: sub scantron_validate_doublebubble {
                   6666:     my ($r,$currentphase) = @_;
                   6667:     #get student info
                   6668:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6669:     my %idmap=&username_to_idmap($classlist);
                   6670: 
                   6671:     #get scantron line setup
1.257     albertel 6672:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6673:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6674: 
                   6675:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6676: 
1.157     albertel 6677:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6678: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6679: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6680: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6681: 						 $scan_data);
                   6682: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6683: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6684: 				 'doublebubble',
                   6685: 				 $$scan_record{'scantron.doubleerror'});
                   6686:     	return (1,$currentphase);
                   6687:     }
                   6688:     return (0,$currentphase+1);
                   6689: }
                   6690: 
1.423     albertel 6691: =pod
                   6692: 
                   6693: =item scantron_get_maxbubble
                   6694: 
1.424     albertel 6695:    Returns the maximum number of bubble lines that are expected to
                   6696:    occur. Does this by walking the selected sequence rendering the
                   6697:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6698:    for what the current value of the problem counter is.
                   6699: 
1.447     foxr     6700:    Caches the results to $env{'form.scantron_maxbubble'},
                   6701:    $env{'form.scantron.bubble_lines.n'} and 
                   6702:    $env{'form.scantron.first_bubble_line.n'}
                   6703:    which are the total number of bubble, lines, the number of bubble
                   6704:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6705: 
1.423     albertel 6706: =cut
                   6707: 
1.330     albertel 6708: sub scantron_get_maxbubble {    
1.448   ! foxr     6709:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6710:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6711: 	$env{'form.scantron_maxbubble'}) {
1.448   ! foxr     6712: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6713: 	&restore_bubble_lines();
1.257     albertel 6714: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6715:     }
1.448   ! foxr     6716:     &Apache::lonnet::logthis("computing");
1.330     albertel 6717: 
1.447     foxr     6718:     my (undef, undef, $sequence) =
1.257     albertel 6719: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6720: 
1.447     foxr     6721:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6722:     my $map=$navmap->getResourceByUrl($sequence);
                   6723:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6724: 
                   6725:     &Apache::lonxml::clear_problem_counter();
                   6726: 
1.435     foxr     6727:     my $uname       = $env{'form.student'};
                   6728:     my $udom        = $env{'form.userdom'};
                   6729:     my $cid         = $env{'request.course.id'};
                   6730:     my $total_lines = 0;
                   6731:     %bubble_lines_per_response = ();
1.447     foxr     6732:     %first_bubble_line         = ();
1.435     foxr     6733: 
1.447     foxr     6734:   
                   6735:     my $response_number = 0;
                   6736:     my $bubble_line     = 0;
1.191     albertel 6737:     foreach my $resource (@resources) {
1.435     foxr     6738: 	my $symb = $resource->symb();
1.447     foxr     6739: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6740: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6741: 					('symb' => $resource->symb()),
                   6742: 					('grade_target' => 'analyze'),
                   6743: 					('grade_courseid' => $cid),
                   6744: 					('grade_domain' => $udom),
                   6745: 					('grade_username' => $uname));
1.436     albertel 6746: 	my (undef, $an) =
1.435     foxr     6747: 	    split(/_HASH_REF__/,$result, 2);
                   6748: 
                   6749: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6750: 
                   6751: 
                   6752: 
                   6753: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6754: 	    my ($trash, $part) = split(/\./, $part_id);
                   6755: 
                   6756: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6757: 
                   6758: 	    # TODO - make this a persistent hash not an array.
                   6759: 
                   6760: 
                   6761: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6762: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6763: 	    $response_number++;
                   6764: 
                   6765: 	    $bubble_line +=  $lines;
                   6766: 	    $total_lines +=  $lines;
1.435     foxr     6767: 	}
                   6768: 
1.191     albertel 6769:     }
                   6770:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6771: 
                   6772:     &save_bubble_lines();
1.330     albertel 6773:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6774: 	$total_lines;
1.257     albertel 6775:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6776: }
                   6777: 
1.423     albertel 6778: =pod
                   6779: 
                   6780: =item scantron_validate_missingbubbles
                   6781: 
1.424     albertel 6782:    Validates all scanlines in the selected file to not have any
1.447     foxr     6783:     answers that don't have bubbles that have not been verified
                   6784:     to be bubble free.
1.424     albertel 6785: 
1.423     albertel 6786: =cut
                   6787: 
1.157     albertel 6788: sub scantron_validate_missingbubbles {
                   6789:     my ($r,$currentphase) = @_;
                   6790:     #get student info
                   6791:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6792:     my %idmap=&username_to_idmap($classlist);
                   6793: 
                   6794:     #get scantron line setup
1.257     albertel 6795:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6796:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6797:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6798:     if (!$max_bubble) { $max_bubble=2**31; }
                   6799:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6800: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6801: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6802: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6803: 						 $scan_data);
                   6804: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6805: 	my @to_correct;
                   6806: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6807: 	    if ($missing > $max_bubble) { next; }
                   6808: 	    push(@to_correct,$missing);
                   6809: 	}
                   6810: 	if (@to_correct) {
                   6811: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6812: 				     $line,'missingbubble',\@to_correct);
                   6813: 	    return (1,$currentphase);
                   6814: 	}
                   6815: 
                   6816:     }
                   6817:     return (0,$currentphase+1);
                   6818: }
                   6819: 
1.423     albertel 6820: =pod
                   6821: 
                   6822: =item scantron_process_students
                   6823: 
                   6824:    Routine that does the actual grading of the bubble sheet information.
                   6825: 
                   6826:    The parsed scanline hash is added to %env 
                   6827: 
                   6828:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6829:    foreach resource , with the form data of
                   6830: 
                   6831: 	'submitted'     =>'scantron' 
                   6832: 	'grade_target'  =>'grade',
                   6833: 	'grade_username'=> username of student
                   6834: 	'grade_domain'  => domain of student
                   6835: 	'grade_courseid'=> of course
                   6836: 	'grade_symb'    => symb of resource to grade
                   6837: 
                   6838:     This triggers a grading pass. The problem grading code takes care
                   6839:     of converting the bubbled letter information (now in %env) into a
                   6840:     valid submission.
                   6841: 
                   6842: =cut
                   6843: 
1.82      albertel 6844: sub scantron_process_students {
1.75      albertel 6845:     my ($r) = @_;
1.257     albertel 6846:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6847:     my ($symb)=&get_symb($r);
1.81      albertel 6848:     if (!$symb) {return '';}
1.324     albertel 6849:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6850: 
1.257     albertel 6851:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6852:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6853:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6854:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6855:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6856:     my $map=$navmap->getResourceByUrl($sequence);
                   6857:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6858: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6859:     my $result= <<SCANTRONFORM;
1.81      albertel 6860: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6861:   <input type="hidden" name="command" value="scantron_configphase" />
                   6862:   $default_form_data
                   6863: SCANTRONFORM
1.82      albertel 6864:     $r->print($result);
                   6865: 
                   6866:     my @delayqueue;
1.140     albertel 6867:     my %completedstudents;
                   6868:     
1.200     albertel 6869:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6870:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6871:  				    'Scantron Progress',$count,
1.195     albertel 6872: 				    'inline',undef,'scantronupload');
1.140     albertel 6873:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6874: 					  'Processing first student');
                   6875:     my $start=&Time::HiRes::time();
1.158     albertel 6876:     my $i=-1;
1.200     albertel 6877:     my ($uname,$udom,$started);
1.447     foxr     6878: 
                   6879:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6880: 
1.157     albertel 6881:     while ($i<$scanlines->{'count'}) {
                   6882:  	($uname,$udom)=('','');
                   6883:  	$i++;
1.200     albertel 6884:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6885:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6886: 	if ($started) {
                   6887: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6888: 						     'last student');
                   6889: 	}
                   6890: 	$started=1;
1.157     albertel 6891:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6892:  						 $scan_data);
                   6893:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6894:  					      \%idmap,$i)) {
                   6895:   	    &scantron_add_delay(\@delayqueue,$line,
                   6896:  				'Unable to find a student that matches',1);
                   6897:  	    next;
                   6898:   	}
                   6899:  	if (exists $completedstudents{$uname}) {
                   6900:  	    &scantron_add_delay(\@delayqueue,$line,
                   6901:  				'Student '.$uname.' has multiple sheets',2);
                   6902:  	    next;
                   6903:  	}
                   6904:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6905: 
                   6906: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6907:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6908: 
                   6909: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6910: 	    &scantron_putfile($scanlines,$scan_data);
                   6911: 	}
1.161     albertel 6912: 	
                   6913: 	my $i=0;
1.83      albertel 6914: 	foreach my $resource (@resources) {
1.85      albertel 6915: 	    $i++;
1.193     albertel 6916: 	    my %form=('submitted'     =>'scantron',
                   6917: 		      'grade_target'  =>'grade',
                   6918: 		      'grade_username'=>$uname,
                   6919: 		      'grade_domain'  =>$udom,
1.257     albertel 6920: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6921: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6922: 	    if (exists($scan_record->{'scantron.CODE'})
                   6923: 		&& 
                   6924: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6925: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6926: 	    } else {
                   6927: 		$form{'CODE'}='';
1.193     albertel 6928: 	    }
                   6929: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6930: 	    if ($result ne '') {
                   6931: 	    }
1.213     albertel 6932: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6933: 	}
1.140     albertel 6934: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6935: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6936:     } continue {
1.330     albertel 6937: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6938: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6939:     }
1.140     albertel 6940:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6941: #    my $lasttime = &Time::HiRes::time()-$start;
                   6942: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6943: 
1.200     albertel 6944:     $r->print("</form>");
1.324     albertel 6945:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6946:     return '';
1.75      albertel 6947: }
1.157     albertel 6948: 
1.423     albertel 6949: =pod
                   6950: 
                   6951: =item scantron_upload_scantron_data
                   6952: 
                   6953:     Creates the screen for adding a new bubble sheet data file to a course.
                   6954: 
                   6955: =cut
                   6956: 
1.157     albertel 6957: sub scantron_upload_scantron_data {
                   6958:     my ($r)=@_;
1.257     albertel 6959:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6960:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6961: 							  'domainid',
                   6962: 							  'coursename');
1.257     albertel 6963:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6964: 						   'domainid');
1.324     albertel 6965:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6966:     $r->print(<<UPLOAD);
                   6967: <script type="text/javascript" language="javascript">
                   6968:     function checkUpload(formname) {
                   6969: 	if (formname.upfile.value == "") {
                   6970: 	    alert("Please use the browse button to select a file from your local directory.");
                   6971: 	    return false;
                   6972: 	}
                   6973: 	formname.submit();
                   6974:     }
                   6975: </script>
                   6976: 
                   6977: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6978: $default_form_data
1.181     albertel 6979: <table>
                   6980: <tr><td>$select_link </td></tr>
                   6981: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6982: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6983: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6984: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6985: </table>
1.157     albertel 6986: <input name='command' value='scantronupload_save' type='hidden' />
                   6987: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6988: </form>
                   6989: UPLOAD
                   6990:     return '';
                   6991: }
                   6992: 
1.423     albertel 6993: =pod
                   6994: 
                   6995: =item scantron_upload_scantron_data_save
                   6996: 
                   6997:    Adds a provided bubble information data file to the course if user
                   6998:    has the correct privileges to do so.  
                   6999: 
                   7000: =cut
                   7001: 
1.157     albertel 7002: sub scantron_upload_scantron_data_save {
                   7003:     my($r)=@_;
1.324     albertel 7004:     my ($symb)=&get_symb($r,1);
1.182     albertel 7005:     my $doanotherupload=
                   7006: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7007: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7008: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7009: 	'</form>'."\n";
1.257     albertel 7010:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7011: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7012: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7013: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7014: 	if ($symb) {
1.324     albertel 7015: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7016: 	} else {
                   7017: 	    $r->print($doanotherupload);
                   7018: 	}
1.162     albertel 7019: 	return '';
                   7020:     }
1.257     albertel 7021:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7022:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7023:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7024:     #FIXME
                   7025:     #copied from lonnet::userfileupload()
                   7026:     #make that function able to target a specified course
                   7027:     # Replace Windows backslashes by forward slashes
                   7028:     $fname=~s/\\/\//g;
                   7029:     # Get rid of everything but the actual filename
                   7030:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7031:     # Replace spaces by underscores
                   7032:     $fname=~s/\s+/\_/g;
                   7033:     # Replace all other weird characters by nothing
                   7034:     $fname=~s/[^\w\.\-]//g;
                   7035:     # See if there is anything left
                   7036:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7037:     my $uploadedfile=$fname;
1.157     albertel 7038:     $fname='scantron_orig_'.$fname;
1.257     albertel 7039:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7040: 	$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 7041:     } else {
1.275     albertel 7042: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7043: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7044: 	    $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 7045: 	} else {
1.398     albertel 7046: 	    $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 7047: 	}
                   7048:     }
1.174     albertel 7049:     if ($symb) {
1.209     ng       7050: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7051:     } else {
1.182     albertel 7052: 	$r->print($doanotherupload);
1.174     albertel 7053:     }
1.157     albertel 7054:     return '';
                   7055: }
                   7056: 
1.423     albertel 7057: =pod
                   7058: 
                   7059: =item valid_file
                   7060: 
1.424     albertel 7061:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7062: 
                   7063: =cut
                   7064: 
1.202     albertel 7065: sub valid_file {
                   7066:     my ($requested_file)=@_;
                   7067:     foreach my $filename (sort(&scantron_filenames())) {
                   7068: 	if ($requested_file eq $filename) { return 1; }
                   7069:     }
                   7070:     return 0;
                   7071: }
                   7072: 
1.423     albertel 7073: =pod
                   7074: 
                   7075: =item scantron_download_scantron_data
                   7076: 
                   7077:    Shows a list of the three internal files (original, corrected,
                   7078:    skipped) for a specific bubble sheet data file that exists in the
                   7079:    course.
                   7080: 
                   7081: =cut
                   7082: 
1.202     albertel 7083: sub scantron_download_scantron_data {
                   7084:     my ($r)=@_;
1.324     albertel 7085:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7086:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7087:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7088:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7089:     if (! &valid_file($file)) {
                   7090: 	$r->print(<<ERROR);
                   7091: 	<p>
                   7092: 	    The requested file name was invalid.
                   7093:         </p>
                   7094: ERROR
1.324     albertel 7095: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7096: 	return;
                   7097:     }
                   7098:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7099:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7100:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7101:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7102:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7103:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7104:     $r->print(<<DOWNLOAD);
                   7105:     <p>
                   7106: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7107:     </p>
                   7108:     <p>
                   7109: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7110:     </p>
                   7111:     <p>
                   7112: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7113:     </p>
                   7114: DOWNLOAD
1.324     albertel 7115:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7116:     return '';
                   7117: }
1.157     albertel 7118: 
1.423     albertel 7119: =pod
                   7120: 
                   7121: =back
                   7122: 
                   7123: =cut
                   7124: 
1.75      albertel 7125: #-------- end of section for handling grading scantron forms -------
                   7126: #
                   7127: #-------------------------------------------------------------------
                   7128: 
1.72      ng       7129: #-------------------------- Menu interface -------------------------
                   7130: #
                   7131: #--- Show a Grading Menu button - Calls the next routine ---
                   7132: sub show_grading_menu_form {
1.324     albertel 7133:     my ($symb)=@_;
1.125     ng       7134:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7135: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7136: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7137: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7138: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7139: 	'</form>'."\n";
                   7140:     return $result;
                   7141: }
                   7142: 
1.77      ng       7143: # -- Retrieve choices for grading form
                   7144: sub savedState {
                   7145:     my %savedState = ();
1.257     albertel 7146:     if ($env{'form.saveState'}) {
                   7147: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7148: 	    my ($key,$value) = split(/=/,$_,2);
                   7149: 	    $savedState{$key} = $value;
                   7150: 	}
                   7151:     }
                   7152:     return \%savedState;
                   7153: }
1.76      ng       7154: 
1.443     banghart 7155: sub grading_menu {
                   7156:     my ($request) = @_;
                   7157:     my ($symb)=&get_symb($request);
                   7158:     if (!$symb) {return '';}
                   7159:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7160:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7161: 
                   7162:     #
                   7163:     # Define menu data
1.444     banghart 7164:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7165:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7166:     $request->print($table);
1.443     banghart 7167:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7168:                   'handgrade'=>$hdgrade,
                   7169:                   'probTitle'=>$probTitle,
                   7170:                   'command'=>'submit_options',
                   7171:                   'saveState'=>"",
                   7172:                   'gradingMenu'=>1,
                   7173:                   'showgrading'=>"yes");
                   7174:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7175:     my @menu = ({ url => $url,
                   7176:                      name => &mt('Manual Grading/View Submissions'),
                   7177:                      short_description => 
                   7178:     &mt('Start the process of hand grading submissions.'),
                   7179:                  });
                   7180:     $fields{'command'} = 'csvform';
                   7181:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7182:     push (@menu, { url => $url,
                   7183:                    name => &mt('Upload Scores'),
                   7184:                    short_description => 
                   7185:             &mt('Specify a file containing the class scores for current resource.')});
                   7186:     $fields{'command'} = 'processclicker';
                   7187:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7188:     push (@menu, { url => $url,
                   7189:                    name => &mt('Process Clicker'),
                   7190:                    short_description => 
                   7191:             &mt('Specify a file containing the clicker information for this resource.')});
                   7192:     $fields{'command'} = 'scantron_selectphase';
                   7193:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7194:     push (@menu, { url => $url,
                   7195:                    name => &mt('Grade Scantron Forms'),
                   7196:                    short_description => 
                   7197:             &mt('')});
                   7198:     $fields{'command'} = 'verify';
                   7199:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7200:     push (@menu, { url => "",
                   7201:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7202:                    name => &mt('Verify Receipt'),
                   7203:                    short_description => 
                   7204:             &mt('')});
                   7205:     $fields{'command'} = 'manage';
                   7206:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7207:     push (@menu, { url => $url,
                   7208:                    name => &mt('Manage Access Times'),
                   7209:                    short_description => 
                   7210:             &mt('')});
                   7211:     $fields{'command'} = 'view';
                   7212:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7213:     push (@menu, { url => $url,
                   7214:                    name => &mt('View Saved CODEs'),
                   7215:                    short_description => 
                   7216:             &mt('')});
                   7217: 
                   7218:     #
                   7219:     # Create the menu
                   7220:     my $Str;
1.444     banghart 7221:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7222:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7223:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7224:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7225: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7226: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7227: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7228: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7229: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7230: 
1.443     banghart 7231:     foreach my $menudata (@menu) {
1.445     banghart 7232:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7233:             $Str .='    <h3><a '.
                   7234:                 $menudata->{'jscript'}.
                   7235:                 ' href="'.
                   7236:                 $menudata->{'url'}.'" >'.
                   7237:                 $menudata->{'name'}."</a></h3>\n";
                   7238:         } else {
                   7239:             $Str .='    <h3><a '.
                   7240:                 $menudata->{'jscript'}.
1.446     banghart 7241:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7242:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7243:             $Str .= ('&nbsp;'x8).
                   7244:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7245:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7246:         }
1.443     banghart 7247:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7248:             "\n";
                   7249:     }
                   7250:     $Str .="</dl>\n";
1.444     banghart 7251:     $Str .="</form>\n";
1.443     banghart 7252:     $request->print(<<GRADINGMENUJS);
                   7253: <script type="text/javascript" language="javascript">
                   7254:     function checkChoice(formname,val,cmdx) {
                   7255: 	if (val <= 2) {
                   7256: 	    var cmd = radioSelection(formname.radioChoice);
                   7257: 	    var cmdsave = cmd;
                   7258: 	} else {
                   7259: 	    cmd = cmdx;
                   7260: 	    cmdsave = 'submission';
                   7261: 	}
                   7262: 	formname.command.value = cmd;
                   7263: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7264: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7265: 	if (val < 5) formname.submit();
                   7266: 	if (val == 5) {
                   7267: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7268: 	    formname.submit();
                   7269: 	}
                   7270: 	if (val < 7) formname.submit();
                   7271:     }
1.445     banghart 7272:     function checkChoice2(formname,val,cmdx) {
                   7273: 	if (val <= 2) {
                   7274: 	    var cmd = radioSelection(formname.radioChoice);
                   7275: 	    var cmdsave = cmd;
                   7276: 	} else {
                   7277: 	    cmd = cmdx;
                   7278: 	    cmdsave = 'submission';
                   7279: 	}
                   7280: 	formname.command.value = cmd;
                   7281: 	if (val < 5) formname.submit();
                   7282: 	if (val == 5) {
                   7283: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7284: 	    formname.submit();
                   7285: 	}
                   7286: 	if (val < 7) formname.submit();
                   7287:     }
1.443     banghart 7288: 
                   7289:     function checkReceiptNo(formname,nospace) {
                   7290: 	var receiptNo = formname.receipt.value;
                   7291: 	var checkOpt = false;
                   7292: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7293: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7294: 	if (checkOpt) {
                   7295: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7296: 	    formname.receipt.value = "";
                   7297: 	    formname.receipt.focus();
                   7298: 	    return false;
                   7299: 	}
                   7300: 	return true;
                   7301:     }
                   7302: </script>
                   7303: GRADINGMENUJS
                   7304:     &commonJSfunctions($request);
                   7305:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7306:     $result.=$table;
                   7307:     my (undef,$sections) = &getclasslist('all','0');
                   7308:     my $savedState = &savedState();
                   7309:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7310:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7311:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7312:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7313: 
                   7314:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7315: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7316: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7317: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7318: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7319: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7320: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7321: 
                   7322:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7323: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7324: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7325: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7326: 
                   7327:     $result.='<table width="100%" border="0">';
                   7328:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7329:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7330: #    $result.='<td>Groups</td>';
                   7331:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7332:     $result.='</tr>';
                   7333:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7334: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7335:     if (ref($sections)) {
                   7336: 	foreach (sort (@$sections)) {
                   7337: 	    $result.='<option value="'.$_.'" '.
                   7338: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7339: 	}
                   7340:     }
                   7341:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7342:     return $Str;    
                   7343: }
                   7344: 
                   7345: 
                   7346: #--- Displays the submissions first page -------
                   7347: sub submit_options {
1.72      ng       7348:     my ($request) = @_;
1.324     albertel 7349:     my ($symb)=&get_symb($request);
1.72      ng       7350:     if (!$symb) {return '';}
1.76      ng       7351:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7352: 
                   7353:     $request->print(<<GRADINGMENUJS);
                   7354: <script type="text/javascript" language="javascript">
1.116     ng       7355:     function checkChoice(formname,val,cmdx) {
                   7356: 	if (val <= 2) {
                   7357: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7358: 	    var cmdsave = cmd;
1.116     ng       7359: 	} else {
                   7360: 	    cmd = cmdx;
1.118     ng       7361: 	    cmdsave = 'submission';
1.116     ng       7362: 	}
                   7363: 	formname.command.value = cmd;
1.118     ng       7364: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7365: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7366: 	if (val < 5) formname.submit();
                   7367: 	if (val == 5) {
1.72      ng       7368: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7369: 	    formname.submit();
                   7370: 	}
1.238     albertel 7371: 	if (val < 7) formname.submit();
1.72      ng       7372:     }
                   7373: 
                   7374:     function checkReceiptNo(formname,nospace) {
                   7375: 	var receiptNo = formname.receipt.value;
                   7376: 	var checkOpt = false;
                   7377: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7378: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7379: 	if (checkOpt) {
                   7380: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7381: 	    formname.receipt.value = "";
                   7382: 	    formname.receipt.focus();
                   7383: 	    return false;
                   7384: 	}
                   7385: 	return true;
                   7386:     }
                   7387: </script>
                   7388: GRADINGMENUJS
1.118     ng       7389:     &commonJSfunctions($request);
1.398     albertel 7390:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7391:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7392:     $result.=$table;
1.76      ng       7393:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7394:     my $savedState = &savedState();
1.118     ng       7395:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7396:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7397:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7398:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7399: 
                   7400:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7401: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7402: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7403: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7404: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7405: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7406: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7407: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7408: 
1.446     banghart 7409:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7410: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7411: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7412: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7413: 
1.326     albertel 7414:     $result.='<table width="100%" border="0">';
1.442     banghart 7415:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7416:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7417:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7418:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7419:     $result.='</tr>';
1.116     ng       7420:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7421: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7422:     if (ref($sections)) {
1.155     albertel 7423: 	foreach (sort (@$sections)) {
                   7424: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7425: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7426: 	}
1.116     ng       7427:     }
1.401     albertel 7428:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7429:     $result.= '</td><td>'."\n";
                   7430:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7431:     $result.='</td><td>'."\n";
                   7432:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7433: 
1.116     ng       7434:     $result.='</td></tr>';
                   7435: 
1.442     banghart 7436:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7437: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7438: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7439: 	'</label> <select name="submitonly">'.
1.145     albertel 7440: 	'<option value="yes" '.
1.401     albertel 7441: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7442: 	'<option value="queued" '.
1.401     albertel 7443: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7444: 	'<option value="graded" '.
1.401     albertel 7445: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7446: 	'<option value="incorrect" '.
1.401     albertel 7447: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7448: 	'<option value="all" '.
1.401     albertel 7449: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7450: 
1.442     banghart 7451:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7452: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7453: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7454: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7455: 
1.442     banghart 7456:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7457: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7458: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7459: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7460: 
1.442     banghart 7461:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7462: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7463: 	'</td></tr></table>'."\n";
                   7464: 
1.446     banghart 7465:     $result.='</td>'; #<td valign="top">';
1.116     ng       7466: 
1.446     banghart 7467: #    $result.='<table width="100%" border="0">';
                   7468: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7469: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7470: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7471: #
                   7472: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7473: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7474: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7475: #
                   7476: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7477: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7478: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7479: #
                   7480: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7481: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7482: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7483: #	    ' '.&mt('receipt').': '.
                   7484: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7485: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7486: #	    '</td></tr>'."\n";
                   7487: #    } 
                   7488: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7489: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7490: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7491: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7492: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7493: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7494: #
                   7495: #    $result.='</table>'."\n".'</td>';
                   7496:     $result.= '</tr></table>'."\n".
1.401     albertel 7497: 	'</td></tr></table></form>'."\n";
1.44      ng       7498:     return $result;
1.2       albertel 7499: }
                   7500: 
1.285     albertel 7501: sub reset_perm {
                   7502:     undef(%perm);
                   7503: }
                   7504: 
                   7505: sub init_perm {
                   7506:     &reset_perm();
1.300     albertel 7507:     foreach my $test_perm ('vgr','mgr','opa') {
                   7508: 
                   7509: 	my $scope = $env{'request.course.id'};
                   7510: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7511: 
                   7512: 	    $scope .= '/'.$env{'request.course.sec'};
                   7513: 	    if ( $perm{$test_perm}=
                   7514: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7515: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7516: 	    } else {
                   7517: 		delete($perm{$test_perm});
                   7518: 	    }
1.285     albertel 7519: 	}
                   7520:     }
                   7521: }
                   7522: 
1.400     www      7523: sub gather_clicker_ids {
1.408     albertel 7524:     my %clicker_ids;
1.400     www      7525: 
                   7526:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7527: 
                   7528:     # Set up a couple variables.
1.407     albertel 7529:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7530:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7531:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7532: 
1.407     albertel 7533:     foreach my $student (keys(%$classlist)) {
1.438     www      7534:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7535:         my $username = $classlist->{$student}->[$username_idx];
                   7536:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7537:         my $clickers =
1.408     albertel 7538: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7539:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7540:             $id=~s/^[\#0]+//;
1.421     www      7541:             $id=~s/[\-\:]//g;
1.407     albertel 7542:             if (exists($clicker_ids{$id})) {
1.408     albertel 7543: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7544:             } else {
1.408     albertel 7545: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7546:             }
                   7547:         }
                   7548:     }
1.407     albertel 7549:     return %clicker_ids;
1.400     www      7550: }
                   7551: 
1.402     www      7552: sub gather_adv_clicker_ids {
1.408     albertel 7553:     my %clicker_ids;
1.402     www      7554:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7555:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7556:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7557:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7558:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7559:             my ($puname,$pudom)=split(/\:/,$person);
                   7560:             my $clickers =
1.408     albertel 7561: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7562:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7563: 		$id=~s/^[\#0]+//;
1.421     www      7564:                 $id=~s/[\-\:]//g;
1.408     albertel 7565: 		if (exists($clicker_ids{$id})) {
                   7566: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7567: 		} else {
                   7568: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7569: 		}
1.405     www      7570:             }
1.402     www      7571:         }
                   7572:     }
1.407     albertel 7573:     return %clicker_ids;
1.402     www      7574: }
                   7575: 
1.413     www      7576: sub clicker_grading_parameters {
                   7577:     return ('gradingmechanism' => 'scalar',
                   7578:             'upfiletype' => 'scalar',
                   7579:             'specificid' => 'scalar',
                   7580:             'pcorrect' => 'scalar',
                   7581:             'pincorrect' => 'scalar');
                   7582: }
                   7583: 
1.400     www      7584: sub process_clicker {
                   7585:     my ($r)=@_;
                   7586:     my ($symb)=&get_symb($r);
                   7587:     if (!$symb) {return '';}
                   7588:     my $result=&checkforfile_js();
                   7589:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7590:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7591:     $result.=$table;
                   7592:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7593:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7594:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7595:         '.</b></td></tr>'."\n";
                   7596:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7597: # Attempt to restore parameters from last session, set defaults if not present
                   7598:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7599:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7600:                                                  \%Saveable_Parameters);
                   7601:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7602:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7603:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7604:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7605: 
                   7606:     my %checked;
                   7607:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7608:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7609:           $checked{$gradingmechanism}="checked='checked'";
                   7610:        }
                   7611:     }
                   7612: 
1.400     www      7613:     my $upload=&mt("Upload File");
                   7614:     my $type=&mt("Type");
1.402     www      7615:     my $attendance=&mt("Award points just for participation");
                   7616:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7617:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7618:     my $pcorrect=&mt("Percentage points for correct solution");
                   7619:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7620:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7621: 						   ('iclicker' => 'i>clicker',
                   7622:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7623:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7624:     $result.=<<ENDUPFORM;
1.402     www      7625: <script type="text/javascript">
                   7626: function sanitycheck() {
                   7627: // Accept only integer percentages
                   7628:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7629:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7630: // Find out grading choice
                   7631:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7632:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7633:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7634:       }
                   7635:    }
                   7636: // By default, new choice equals user selection
                   7637:    newgradingchoice=gradingchoice;
                   7638: // Not good to give more points for false answers than correct ones
                   7639:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7640:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7641:    }
                   7642: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7643:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7644:       document.forms.gradesupload.pcorrect.value=100;
                   7645:       document.forms.gradesupload.pincorrect.value=100;
                   7646:    }
                   7647: // If the values are different, cannot be attendance only
                   7648:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7649:        (gradingchoice=='attendance')) {
                   7650:        newgradingchoice='personnel';
                   7651:    }
                   7652: // Change grading choice to new one
                   7653:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7654:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7655:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7656:       } else {
                   7657:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7658:       }
                   7659:    }
                   7660: // Remember the old state
                   7661:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7662: }
                   7663: </script>
1.400     www      7664: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7665: <input type="hidden" name="symb" value="$symb" />
                   7666: <input type="hidden" name="command" value="processclickerfile" />
                   7667: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7668: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7669: <input type="file" name="upfile" size="50" />
                   7670: <br /><label>$type: $selectform</label>
1.413     www      7671: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7672: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7673: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7674: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7675: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7676: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7677: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7678: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7679: </form>
                   7680: ENDUPFORM
                   7681:     $result.='</td></tr></table>'."\n".
                   7682:              '</td></tr></table><br /><br />'."\n";
                   7683:     $result.=&show_grading_menu_form($symb);
                   7684:     return $result;
                   7685: }
                   7686: 
                   7687: sub process_clicker_file {
                   7688:     my ($r)=@_;
                   7689:     my ($symb)=&get_symb($r);
                   7690:     if (!$symb) {return '';}
1.413     www      7691: 
                   7692:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7693:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7694:                                               \%Saveable_Parameters);
                   7695: 
1.400     www      7696:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7697:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7698: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7699: 	return $result.&show_grading_menu_form($symb);
1.404     www      7700:     }
1.407     albertel 7701:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7702:     my %correct_ids;
1.404     www      7703:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7704: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7705:     }
                   7706:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7707: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7708: 	   $correct_id=~tr/a-z/A-Z/;
                   7709: 	   $correct_id=~s/\s//gs;
                   7710: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7711:            $correct_id=~s/[\-\:]//g;
1.414     www      7712:            if ($correct_id) {
                   7713: 	      $correct_ids{$correct_id}='specified';
                   7714:            }
                   7715:         }
1.400     www      7716:     }
1.404     www      7717:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7718: 	$result.=&mt('Score based on attendance only');
1.404     www      7719:     } else {
1.408     albertel 7720: 	my $number=0;
1.411     www      7721: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7722: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7723: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7724: 	    if ($correct_ids{$id} eq 'specified') {
                   7725: 		$result.=&mt('specified');
                   7726: 	    } else {
                   7727: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7728: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7729: 	    }
                   7730: 	    $number++;
                   7731: 	}
1.411     www      7732:         $result.="</p>\n";
1.408     albertel 7733: 	if ($number==0) {
                   7734: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7735: 	    return $result.&show_grading_menu_form($symb);
                   7736: 	}
1.404     www      7737:     }
1.405     www      7738:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7739:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7740: 		     '<span class="LC_error">',
                   7741: 		     '</span>',
                   7742: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7743:         return $result.&show_grading_menu_form($symb);
                   7744:     }
1.410     www      7745: 
                   7746: # Were able to get all the info needed, now analyze the file
                   7747: 
1.411     www      7748:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7749:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7750:     my $heading=&mt('Scanning clicker file');
                   7751:     $result.=(<<ENDHEADER);
                   7752: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7753: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7754: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7755: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7756: <input type="hidden" name="symb" value="$symb" />
                   7757: <input type="hidden" name="command" value="assignclickergrades" />
                   7758: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7759: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7760: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7761: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7762: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7763: ENDHEADER
1.408     albertel 7764:     my %responses;
                   7765:     my @questiontitles;
1.405     www      7766:     my $errormsg='';
                   7767:     my $number=0;
                   7768:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7769: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7770:     }
1.419     www      7771:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7772:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7773:     }
1.411     www      7774:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7775:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7776:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7777:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7778:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7779:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7780:              '<br />';
1.414     www      7781: # Remember Question Titles
                   7782: # FIXME: Possibly need delimiter other than ":"
                   7783:     for (my $i=0;$i<$number;$i++) {
                   7784:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7785:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7786:     }
1.411     www      7787:     my $correct_count=0;
                   7788:     my $student_count=0;
                   7789:     my $unknown_count=0;
1.414     www      7790: # Match answers with usernames
                   7791: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7792:     foreach my $id (keys(%responses)) {
1.410     www      7793:        if ($correct_ids{$id}) {
1.414     www      7794:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7795:           $correct_count++;
1.410     www      7796:        } elsif ($clicker_ids{$id}) {
1.437     www      7797:           if ($clicker_ids{$id}=~/\,/) {
                   7798: # More than one user with the same clicker!
                   7799:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7800:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7801:                            "<select name='multi".$id."'>";
                   7802:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7803:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7804:              }
                   7805:              $result.='</select>';
                   7806:              $unknown_count++;
                   7807:           } else {
                   7808: # Good: found one and only one user with the right clicker
                   7809:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7810:              $student_count++;
                   7811:           }
1.410     www      7812:        } else {
1.411     www      7813:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7814:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7815:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7816:                    "\n".&mt("Domain").": ".
                   7817:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7818:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7819:           $unknown_count++;
1.410     www      7820:        }
1.405     www      7821:     }
1.412     www      7822:     $result.='<hr />'.
                   7823:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7824:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7825:        if ($correct_count==0) {
                   7826:           $errormsg.="Found no correct answers answers for grading!";
                   7827:        } elsif ($correct_count>1) {
1.414     www      7828:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7829:        }
                   7830:     }
1.428     www      7831:     if ($number<1) {
                   7832:        $errormsg.="Found no questions.";
                   7833:     }
1.412     www      7834:     if ($errormsg) {
                   7835:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7836:     } else {
                   7837:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7838:     }
                   7839:     $result.='</form></td></tr></table>'."\n".
1.410     www      7840:              '</td></tr></table><br /><br />'."\n";
1.404     www      7841:     return $result.&show_grading_menu_form($symb);
1.400     www      7842: }
                   7843: 
1.405     www      7844: sub iclicker_eval {
1.406     www      7845:     my ($questiontitles,$responses)=@_;
1.405     www      7846:     my $number=0;
                   7847:     my $errormsg='';
                   7848:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7849:         my %components=&Apache::loncommon::record_sep($line);
                   7850:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7851: 	if ($entries[0] eq 'Question') {
                   7852: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7853: 		$$questiontitles[$number]=$entries[$i];
                   7854: 		$number++;
                   7855: 	    }
                   7856: 	}
                   7857: 	if ($entries[0]=~/^\#/) {
                   7858: 	    my $id=$entries[0];
                   7859: 	    my @idresponses;
                   7860: 	    $id=~s/^[\#0]+//;
                   7861: 	    for (my $i=0;$i<$number;$i++) {
                   7862: 		my $idx=3+$i*6;
                   7863: 		push(@idresponses,$entries[$idx]);
                   7864: 	    }
                   7865: 	    $$responses{$id}=join(',',@idresponses);
                   7866: 	}
1.405     www      7867:     }
                   7868:     return ($errormsg,$number);
                   7869: }
                   7870: 
1.419     www      7871: sub interwrite_eval {
                   7872:     my ($questiontitles,$responses)=@_;
                   7873:     my $number=0;
                   7874:     my $errormsg='';
1.420     www      7875:     my $skipline=1;
                   7876:     my $questionnumber=0;
                   7877:     my %idresponses=();
1.419     www      7878:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7879:         my %components=&Apache::loncommon::record_sep($line);
                   7880:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7881:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7882:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7883:         next if $skipline;
                   7884:         if ($entries[0]!=$questionnumber) {
                   7885:            $questionnumber=$entries[0];
                   7886:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7887:            $number++;
1.419     www      7888:         }
1.420     www      7889:         my $id=$entries[4];
                   7890:         $id=~s/^[\#0]+//;
1.421     www      7891:         $id=~s/^v\d*\://i;
                   7892:         $id=~s/[\-\:]//g;
1.420     www      7893:         $idresponses{$id}[$number]=$entries[6];
                   7894:     }
                   7895:     foreach my $id (keys %idresponses) {
                   7896:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7897:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7898:     }
                   7899:     return ($errormsg,$number);
                   7900: }
                   7901: 
1.414     www      7902: sub assign_clicker_grades {
                   7903:     my ($r)=@_;
                   7904:     my ($symb)=&get_symb($r);
                   7905:     if (!$symb) {return '';}
1.416     www      7906: # See which part we are saving to
                   7907:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7908: # FIXME: This should probably look for the first handgradeable part
                   7909:     my $part=$$partlist[0];
                   7910: # Start screen output
1.414     www      7911:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7912: 
1.414     www      7913:     my $heading=&mt('Assigning grades based on clicker file');
                   7914:     $result.=(<<ENDHEADER);
                   7915: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7916: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7917: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7918: ENDHEADER
                   7919: # Get correct result
                   7920: # FIXME: Possibly need delimiter other than ":"
                   7921:     my @correct=();
1.415     www      7922:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7923:     my $number=$env{'form.number'};
                   7924:     if ($gradingmechanism ne 'attendance') {
1.414     www      7925:        foreach my $key (keys(%env)) {
                   7926:           if ($key=~/^form\.correct\:/) {
                   7927:              my @input=split(/\,/,$env{$key});
                   7928:              for (my $i=0;$i<=$#input;$i++) {
                   7929:                  if (($correct[$i]) && ($input[$i]) &&
                   7930:                      ($correct[$i] ne $input[$i])) {
                   7931:                     $result.='<br /><span class="LC_warning">'.
                   7932:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7933:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7934:                  } elsif ($input[$i]) {
                   7935:                     $correct[$i]=$input[$i];
                   7936:                  }
                   7937:              }
                   7938:           }
                   7939:        }
1.415     www      7940:        for (my $i=0;$i<$number;$i++) {
1.414     www      7941:           if (!$correct[$i]) {
                   7942:              $result.='<br /><span class="LC_error">'.
                   7943:                       &mt('No correct result given for question "[_1]"!',
                   7944:                           $env{'form.question:'.$i}).'</span>';
                   7945:           }
                   7946:        }
                   7947:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7948:     }
                   7949: # Start grading
1.415     www      7950:     my $pcorrect=$env{'form.pcorrect'};
                   7951:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7952:     my $storecount=0;
1.415     www      7953:     foreach my $key (keys(%env)) {
1.420     www      7954:        my $user='';
1.415     www      7955:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7956:           $user=$1;
                   7957:        }
                   7958:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7959:           my $id=$1;
                   7960:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7961:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7962:           } elsif ($env{'form.multi'.$id}) {
                   7963:              $user=$env{'form.multi'.$id};
1.420     www      7964:           }
                   7965:        }
                   7966:        if ($user) { 
1.415     www      7967:           my @answer=split(/\,/,$env{$key});
                   7968:           my $sum=0;
                   7969:           for (my $i=0;$i<$number;$i++) {
                   7970:              if ($answer[$i]) {
                   7971:                 if ($gradingmechanism eq 'attendance') {
                   7972:                    $sum+=$pcorrect;
                   7973:                 } else {
                   7974:                    if ($answer[$i] eq $correct[$i]) {
                   7975:                       $sum+=$pcorrect;
                   7976:                    } else {
                   7977:                       $sum+=$pincorrect;
                   7978:                    }
                   7979:                 }
                   7980:              }
                   7981:           }
1.416     www      7982:           my $ave=$sum/(100*$number);
                   7983: # Store
                   7984:           my ($username,$domain)=split(/\:/,$user);
                   7985:           my %grades=();
                   7986:           $grades{"resource.$part.solved"}='correct_by_override';
                   7987:           $grades{"resource.$part.awarded"}=$ave;
                   7988:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7989:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7990:                                                  $env{'request.course.id'},
                   7991:                                                  $domain,$username);
                   7992:           if ($returncode ne 'ok') {
                   7993:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7994:           } else {
                   7995:              $storecount++;
                   7996:           }
1.415     www      7997:        }
                   7998:     }
                   7999: # We are done
1.416     www      8000:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8001:              '</td></tr></table>'."\n".
1.414     www      8002:              '</td></tr></table><br /><br />'."\n";
                   8003:     return $result.&show_grading_menu_form($symb);
                   8004: }
                   8005: 
1.1       albertel 8006: sub handler {
1.41      ng       8007:     my $request=$_[0];
1.447     foxr     8008: 
1.434     albertel 8009:     &reset_caches();
1.257     albertel 8010:     if ($env{'browser.mathml'}) {
1.141     www      8011: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8012:     } else {
1.141     www      8013: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8014:     }
                   8015:     $request->send_http_header;
1.44      ng       8016:     return '' if $request->header_only;
1.41      ng       8017:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8018:     my $symb=&get_symb($request,1);
1.160     albertel 8019:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8020:     my $command=$commands[0];
1.447     foxr     8021: 
1.160     albertel 8022:     if ($#commands > 0) {
                   8023: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8024:     }
1.447     foxr     8025: 
                   8026: 
1.353     albertel 8027:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8028:     if ($symb eq '' && $command eq '') {
1.257     albertel 8029: 	if ($env{'user.adv'}) {
                   8030: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8031: 		($env{'form.codethree'})) {
                   8032: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8033: 		    $env{'form.codethree'};
1.41      ng       8034: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8035: 		    &Apache::lonnet::checkin($token);
                   8036: 		if ($tsymb) {
1.137     albertel 8037: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8038: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8039: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8040: 					  ('grade_username' => $tuname,
                   8041: 					   'grade_domain' => $tudom,
                   8042: 					   'grade_courseid' => $tcrsid,
                   8043: 					   'grade_symb' => $tsymb)));
1.41      ng       8044: 		    } else {
1.45      ng       8045: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8046: 		    }
1.41      ng       8047: 		} else {
1.45      ng       8048: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8049: 		}
1.14      www      8050: 	    } else {
1.41      ng       8051: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8052: 	    }
                   8053: 	}
                   8054:     } else {
1.285     albertel 8055: 	&init_perm();
1.104     albertel 8056: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8057: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8058: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8059: 	    &pickStudentPage($request);
1.103     albertel 8060: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8061: 	    &displayPage($request);
1.104     albertel 8062: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8063: 	    &updateGradeByPage($request);
1.104     albertel 8064: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8065: 	    &processGroup($request);
1.104     albertel 8066: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8067: 	    $request->print(&grading_menu($request));
                   8068: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8069: 	    $request->print(&submit_options($request));
1.104     albertel 8070: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8071: 	    $request->print(&viewgrades($request));
1.104     albertel 8072: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8073: 	    $request->print(&processHandGrade($request));
1.106     albertel 8074: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8075: 	    $request->print(&editgrades($request));
1.106     albertel 8076: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8077: 	    $request->print(&verifyreceipt($request));
1.400     www      8078:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8079:             $request->print(&process_clicker($request));
                   8080:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8081:             $request->print(&process_clicker_file($request));
1.414     www      8082:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8083:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8084: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8085: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8086: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8087: 	    $request->print(&csvupload($request));
1.106     albertel 8088: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8089: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8090: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8091: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8092: 		$request->print(&csvuploadoptions($request));
1.41      ng       8093: 	    } else {
1.257     albertel 8094: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8095: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8096: 		} else {
1.257     albertel 8097: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8098: 		}
                   8099: 		$request->print(&csvuploadmap($request));
                   8100: 	    }
1.246     albertel 8101: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8102: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8103: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8104: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8105: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8106:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8107:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8108: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8109: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8110: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8111: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8112:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8113:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8114: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8115:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8116:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8117:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8118: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8119:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8120:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8121: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8122:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8123: 	} elsif ($command) {
1.157     albertel 8124: 	    $request->print("Access Denied ($command)");
1.26      albertel 8125: 	}
1.2       albertel 8126:     }
1.353     albertel 8127:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8128:     &reset_caches();
1.44      ng       8129:     return '';
                   8130: }
                   8131: 
1.1       albertel 8132: 1;
                   8133: 
1.13      albertel 8134: __END__;

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