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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.452   ! banghart    4: # $Id: grades.pm,v 1.451 2007/10/09 23:42:49 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
1.447     foxr       50: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       51:                                    # index is "symb.part_id"
                     52: 
1.447     foxr       53: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     54: 
                     55: # Save and restore the bubble lines array to the form env.
                     56: 
                     57: 
                     58: sub save_bubble_lines {
1.448     foxr       59:     &Apache::lonnet::logthis("Saving bubble_lines...");
1.447     foxr       60:     foreach my $line (keys(%bubble_lines_per_response)) {
1.448     foxr       61: 	&Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
1.447     foxr       62: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     63: 	$env{"form.scantron.first_bubble_line.$line"} =
                     64: 	    $first_bubble_line{$line};
                     65:     }
                     66: }
                     67: 
                     68: 
                     69: sub restore_bubble_lines {
                     70:     my $line = 0;
                     71:     %bubble_lines_per_response = ();
                     72:     while ($env{"form.scantron.bubblelines.$line"}) {
                     73: 	my $value = $env{"form.scantron.bubblelines.$line"};
1.448     foxr       74: 	&Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
1.447     foxr       75: 	$bubble_lines_per_response{$line} = $value;
                     76: 	$first_bubble_line{$line}  =
                     77: 	    $env{"form.scantron.first_bubble_line.$line"};
                     78: 	$line++;
                     79:     }
                     80: 
                     81: }
                     82: 
                     83: #  Given the parsed scanline, get the response for 
                     84: #  'answer' number n:
                     85: 
                     86: sub get_response_bubbles {
                     87:     my ($parsed_line, $response)  = @_;
                     88: 
                     89:     my $bubble_line = $first_bubble_line{$response};
1.448     foxr       90:     my $bubble_lines= $bubble_lines_per_response{$response};
1.447     foxr       91:     my $selected = "";
                     92: 
                     93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                     94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
                     95: 	$bubble_line++;
                     96:     }
                     97:     return $selected;
                     98: }
                     99: 
1.1       albertel  100: 
1.68      ng        101: # ----- These first few routines are general use routines.----
1.447     foxr      102: 
                    103: # Return the number of occurences of a pattern in a string.
                    104: 
                    105: sub occurence_count {
                    106:     my ($string, $pattern) = @_;
                    107: 
                    108:     my @matches = ($string =~ /$pattern/g);
                    109: 
                    110:     return scalar(@matches);
                    111: }
                    112: 
                    113: 
                    114: # Take a string known to have digits and convert all the
                    115: # digits into letters in the range J,A..I.
                    116: 
                    117: sub digits_to_letters {
                    118:     my ($input) = @_;
                    119: 
                    120:     my @alphabet = ('J', 'A'..'I');
                    121: 
                    122:     my @input    = split(//, $input);
                    123:     my $output ='';
                    124:     for (my $i = 0; $i < scalar(@input); $i++) {
                    125: 	if ($input[$i] =~ /\d/) {
                    126: 	    $output .= $alphabet[$input[$i]];
                    127: 	} else {
                    128: 	    $output .= $input[$i];
                    129: 	}
                    130:     }
                    131:     return $output;
                    132: }
                    133: 
1.44      ng        134: #
1.146     albertel  135: # --- Retrieve the parts from the metadata file.---
1.44      ng        136: sub getpartlist {
1.324     albertel  137:     my ($symb) = @_;
1.439     albertel  138: 
                    139:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    140:     my $res      = $navmap->getBySymb($symb);
                    141:     my $partlist = $res->parts();
                    142:     my $url      = $res->src();
                    143:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    144: 
1.146     albertel  145:     my @stores;
1.439     albertel  146:     foreach my $part (@{ $partlist }) {
1.146     albertel  147: 	foreach my $key (@metakeys) {
                    148: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    149: 	}
                    150:     }
                    151:     return @stores;
1.2       albertel  152: }
                    153: 
1.44      ng        154: # --- Get the symbolic name of a problem and the url
1.324     albertel  155: sub get_symb {
1.173     albertel  156:     my ($request,$silent) = @_;
1.257     albertel  157:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  159:     if ($symb eq '') { 
                    160: 	if (!$silent) {
                    161: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    162: 	    return ();
                    163: 	}
                    164:     }
1.418     albertel  165:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  166:     return ($symb);
1.32      ng        167: }
                    168: 
1.129     ng        169: #--- Format fullname, username:domain if different for display
                    170: #--- Use anywhere where the student names are listed
                    171: sub nameUserString {
                    172:     my ($type,$fullname,$uname,$udom) = @_;
                    173:     if ($type eq 'header') {
1.398     albertel  174: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        175:     } else {
1.398     albertel  176: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    177: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        178:     }
                    179: }
                    180: 
1.44      ng        181: #--- Get the partlist and the response type for a given problem. ---
                    182: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        183: sub response_type {
1.324     albertel  184:     my ($symb) = shift;
1.377     albertel  185: 
                    186:     my $navmap = Apache::lonnavmaps::navmap->new();
                    187:     my $res = $navmap->getBySymb($symb);
                    188:     my $partlist = $res->parts();
1.392     albertel  189:     my %vPart = 
                    190: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  191:     my (%response_types,%handgrade);
                    192:     foreach my $part (@{ $partlist }) {
1.392     albertel  193: 	next if (%vPart && !exists($vPart{$part}));
                    194: 
1.377     albertel  195: 	my @types = $res->responseType($part);
                    196: 	my @ids = $res->responseIds($part);
                    197: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    198: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    199: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    200: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    201: 				     '.handgrade',$symb);
1.41      ng        202: 	}
                    203:     }
1.377     albertel  204:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        205: }
                    206: 
1.375     albertel  207: sub flatten_responseType {
                    208:     my ($responseType) = @_;
                    209:     my @part_response_id =
                    210: 	map { 
                    211: 	    my $part = $_;
                    212: 	    map {
                    213: 		[$part,$_]
                    214: 		} sort(keys(%{ $responseType->{$part} }));
                    215: 	} sort(keys(%$responseType));
                    216:     return @part_response_id;
                    217: }
                    218: 
1.207     albertel  219: sub get_display_part {
1.324     albertel  220:     my ($partID,$symb)=@_;
1.207     albertel  221:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    222:     if (defined($display) and $display ne '') {
1.398     albertel  223: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  224:     } else {
                    225: 	$display=$partID;
                    226:     }
                    227:     return $display;
                    228: }
1.269     raeburn   229: 
1.118     ng        230: #--- Show resource title
                    231: #--- and parts and response type
                    232: sub showResourceInfo {
1.324     albertel  233:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  234:     my $col=3;
                    235:     if ($checkboxes) { $col=4; }
1.398     albertel  236:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    237:     $result .='<table border="0">';
1.324     albertel  238:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        239:     my %resptype = ();
1.122     ng        240:     my $hdgrade='no';
1.154     albertel  241:     my %partsseen;
1.375     albertel  242:     foreach my $partID (sort keys(%$responseType)) {
                    243: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    244: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    245: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    246: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    247: 	    $result.='<tr>';
                    248: 	    if ($checkboxes) {
                    249: 		if (exists($partsseen{$partID})) {
                    250: 		    $result.="<td>&nbsp;</td>";
                    251: 		} else {
1.401     albertel  252: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  253: 		}
                    254: 		$partsseen{$partID}=1;
1.154     albertel  255: 	    }
1.375     albertel  256: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  257: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    258: 		$resID.'</span></td>'.
1.375     albertel  259: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    260: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  261: 	}
1.118     ng        262:     }
                    263:     $result.='</table>'."\n";
1.147     albertel  264:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        265: }
                    266: 
1.434     albertel  267: sub reset_caches {
                    268:     &reset_analyze_cache();
                    269:     &reset_perm();
                    270: }
                    271: 
                    272: {
                    273:     my %analyze_cache;
1.148     albertel  274: 
1.434     albertel  275:     sub reset_analyze_cache {
                    276: 	undef(%analyze_cache);
                    277:     }
                    278: 
                    279:     sub get_analyze {
                    280: 	my ($symb,$uname,$udom)=@_;
                    281: 	my $key = "$symb\0$uname\0$udom";
                    282: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    283: 
                    284: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    285: 	$url=&Apache::lonnet::clutter($url);
                    286: 	my $subresult=&Apache::lonnet::ssi($url,
                    287: 					   ('grade_target' => 'analyze'),
                    288: 					   ('grade_domain' => $udom),
                    289: 					   ('grade_symb' => $symb),
                    290: 					   ('grade_courseid' => 
                    291: 					    $env{'request.course.id'}),
                    292: 					   ('grade_username' => $uname));
                    293: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    294: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    295: 	return $analyze_cache{$key} = \%analyze;
                    296:     }
                    297: 
                    298:     sub get_order {
                    299: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    300: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    301: 	return $analyze->{"$partid.$respid.shown"};
                    302:     }
                    303: 
                    304:     sub get_radiobutton_correct_foil {
                    305: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    306: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    307: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    308: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    309: 		return $foil;
                    310: 	    }
                    311: 	}
                    312:     }
1.148     albertel  313: }
1.434     albertel  314: 
1.118     ng        315: #--- Clean response type for display
1.335     albertel  316: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    317: #        response types only.
1.118     ng        318: sub cleanRecord {
1.336     albertel  319:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    320: 	$uname,$udom) = @_;
1.398     albertel  321:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  322:     if ($response =~ /^(option|rank)$/) {
                    323: 	my %answer=&Apache::lonnet::str2hash($answer);
                    324: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    325: 	my ($toprow,$bottomrow);
                    326: 	foreach my $foil (@$order) {
                    327: 	    if ($grading{$foil} == 1) {
                    328: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    329: 	    } else {
                    330: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    331: 	    }
1.398     albertel  332: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  333: 	}
                    334: 	return '<blockquote><table border="1">'.
                    335: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  336: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  337: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    338:     } elsif ($response eq 'match') {
                    339: 	my %answer=&Apache::lonnet::str2hash($answer);
                    340: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    341: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    342: 	my ($toprow,$middlerow,$bottomrow);
                    343: 	foreach my $foil (@$order) {
                    344: 	    my $item=shift(@items);
                    345: 	    if ($grading{$foil} == 1) {
                    346: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  347: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  348: 	    } else {
                    349: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  350: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  351: 	    }
1.398     albertel  352: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        353: 	}
1.126     ng        354: 	return '<blockquote><table border="1">'.
1.148     albertel  355: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  356: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  357: 	    $middlerow.'</tr>'.
1.398     albertel  358: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  359: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    360:     } elsif ($response eq 'radiobutton') {
                    361: 	my %answer=&Apache::lonnet::str2hash($answer);
                    362: 	my ($toprow,$bottomrow);
1.434     albertel  363: 	my $correct = 
                    364: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    365: 	foreach my $foil (@$order) {
1.148     albertel  366: 	    if (exists($answer{$foil})) {
1.434     albertel  367: 		if ($foil eq $correct) {
1.148     albertel  368: 		    $toprow.='<td><b>true</b></td>';
                    369: 		} else {
                    370: 		    $toprow.='<td><i>true</i></td>';
                    371: 		}
                    372: 	    } else {
                    373: 		$toprow.='<td>false</td>';
                    374: 	    }
1.398     albertel  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  376: 	}
                    377: 	return '<blockquote><table border="1">'.
                    378: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  379: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    381:     } elsif ($response eq 'essay') {
1.257     albertel  382: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        386: 
1.257     albertel  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    392: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        393: 	}
1.166     albertel  394: 	$answer =~ s-\n-<br />-g;
                    395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  396:     } elsif ( $response eq 'organic') {
                    397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    400: 	return $result;
1.335     albertel  401:     } elsif ( $response eq 'Task') {
                    402: 	if ( $answer eq 'SUBMITTED') {
                    403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  405: 	    return $result;
                    406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    408: 			       keys(%{$record}));
                    409: 	    return join('<br />',($version,@matches));
                    410: 			       
                    411: 			       
                    412: 	} else {
                    413: 	    my $result =
                    414: 		'<p>'
                    415: 		.&mt('Overall result: [_1]',
                    416: 		     $record->{$version."resource.$respid.$partid.status"})
                    417: 		.'</p>';
                    418: 	    
                    419: 	    $result .= '<ul>';
                    420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    421: 			     keys(%{$record}));
                    422: 	    foreach my $grade (sort(@grade)) {
                    423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    425: 				     $dim, $record->{$grade}).
                    426: 			  '</li>';
                    427: 	    }
                    428: 	    $result.='</ul>';
                    429: 	    return $result;
                    430: 	}
1.440     albertel  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    432: 	$answer = 
                    433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    434: 							      $answer);
1.122     ng        435:     }
1.118     ng        436:     return $answer;
                    437: }
                    438: 
                    439: #-- A couple of common js functions
                    440: sub commonJSfunctions {
                    441:     my $request = shift;
                    442:     $request->print(<<COMMONJSFUNCTIONS);
                    443: <script type="text/javascript" language="javascript">
                    444:     function radioSelection(radioButton) {
                    445: 	var selection=null;
                    446: 	if (radioButton.length > 1) {
                    447: 	    for (var i=0; i<radioButton.length; i++) {
                    448: 		if (radioButton[i].checked) {
                    449: 		    return radioButton[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
                    453: 	    if (radioButton.checked) return radioButton.value;
                    454: 	}
                    455: 	return selection;
                    456:     }
                    457: 
                    458:     function pullDownSelection(selectOne) {
                    459: 	var selection="";
                    460: 	if (selectOne.length > 1) {
                    461: 	    for (var i=0; i<selectOne.length; i++) {
                    462: 		if (selectOne[i].selected) {
                    463: 		    return selectOne[i].value;
                    464: 		}
                    465: 	    }
                    466: 	} else {
1.138     albertel  467:             // only one value it must be the selected one
                    468: 	    return selectOne.value;
1.118     ng        469: 	}
                    470:     }
                    471: </script>
                    472: COMMONJSFUNCTIONS
                    473: }
                    474: 
1.44      ng        475: #--- Dumps the class list with usernames,list of sections,
                    476: #--- section, ids and fullnames for each user.
                    477: sub getclasslist {
1.449     banghart  478:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  479:     my @getsec;
1.450     banghart  480:     my @getgroup;
1.442     banghart  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  482:     if (!ref($getsec)) {
                    483: 	if ($getsec ne '' && $getsec ne 'all') {
                    484: 	    @getsec=($getsec);
                    485: 	}
                    486:     } else {
                    487: 	@getsec=@{$getsec};
                    488:     }
                    489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  490:     if (!ref($getgroup)) {
                    491: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    492: 	    @getgroup=($getgroup);
                    493: 	}
                    494:     } else {
                    495: 	@getgroup=@{$getgroup};
                    496:     }
                    497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  498: 
1.449     banghart  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  500:     # Bail out if we were unable to get the classlist
1.56      matthew   501:     return if (! defined($classlist));
1.449     banghart  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   503:     #
                    504:     my %sections;
                    505:     my %fullnames;
1.205     matthew   506:     foreach my $student (keys(%$classlist)) {
                    507:         my $end      = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    509:         my $start    = 
                    510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    511:         my $id       = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    513:         my $section  = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    515:         my $fullname = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    517:         my $status   = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  519:         my $group   = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        521: 	# filter students according to status selected
1.442     banghart  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    523: 	    if (!($stu_status =~ $status)) {
1.450     banghart  524: 		delete($classlist->{$student});
1.76      ng        525: 		next;
                    526: 	    }
                    527: 	}
1.450     banghart  528: 	# filter students according to groups selected
                    529: 	if (@getgroup) {
                    530: 	    my $exclude = 1;
                    531: 	    foreach my $grp(@getgroup) {
                    532: 	        if ($group eq $grp) {
                    533: 	            $exclude = 0;
1.452   ! banghart  534: 	        } elsif (($grp eq 'none') && !$group) {
        !           535: 	            $exclude = 0;
1.450     banghart  536: 	        }
                    537: 	    }
                    538: 	    if ($exclude) {
                    539: 	        delete($classlist->{$student});
                    540: 	    }
                    541: 	}
1.205     matthew   542: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  543: 	if (&canview($section)) {
1.291     albertel  544: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  545: 		$sections{$section}++;
1.450     banghart  546: 		if ($classlist->{$student}) {
                    547: 		    $fullnames{$student}=$fullname;
                    548: 		}
1.103     albertel  549: 	    } else {
1.205     matthew   550: 		delete($classlist->{$student});
1.103     albertel  551: 	    }
                    552: 	} else {
1.205     matthew   553: 	    delete($classlist->{$student});
1.103     albertel  554: 	}
1.44      ng        555:     }
                    556:     my %seen = ();
1.56      matthew   557:     my @sections = sort(keys(%sections));
                    558:     return ($classlist,\@sections,\%fullnames);
1.44      ng        559: }
                    560: 
1.103     albertel  561: sub canmodify {
                    562:     my ($sec)=@_;
                    563:     if ($perm{'mgr'}) {
                    564: 	if (!defined($perm{'mgr_section'})) {
                    565: 	    # can modify whole class
                    566: 	    return 1;
                    567: 	} else {
                    568: 	    if ($sec eq $perm{'mgr_section'}) {
                    569: 		#can modify the requested section
                    570: 		return 1;
                    571: 	    } else {
                    572: 		# can't modify the request section
                    573: 		return 0;
                    574: 	    }
                    575: 	}
                    576:     }
                    577:     #can't modify
                    578:     return 0;
                    579: }
                    580: 
                    581: sub canview {
                    582:     my ($sec)=@_;
                    583:     if ($perm{'vgr'}) {
                    584: 	if (!defined($perm{'vgr_section'})) {
                    585: 	    # can modify whole class
                    586: 	    return 1;
                    587: 	} else {
                    588: 	    if ($sec eq $perm{'vgr_section'}) {
                    589: 		#can modify the requested section
                    590: 		return 1;
                    591: 	    } else {
                    592: 		# can't modify the request section
                    593: 		return 0;
                    594: 	    }
                    595: 	}
                    596:     }
                    597:     #can't modify
                    598:     return 0;
                    599: }
                    600: 
1.44      ng        601: #--- Retrieve the grade status of a student for all the parts
                    602: sub student_gradeStatus {
1.324     albertel  603:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  604:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        605:     my %partstatus = ();
                    606:     foreach (@$partlist) {
1.128     ng        607: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        608: 	$status              = 'nothing' if ($status eq '');
                    609: 	$partstatus{$_}      = $status;
                    610: 	my $subkey           = "resource.$_.submitted_by";
                    611: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    612:     }
                    613:     return %partstatus;
                    614: }
                    615: 
1.45      ng        616: # hidden form and javascript that calls the form
                    617: # Use by verifyscript and viewgrades
                    618: # Shows a student's view of problem and submission
                    619: sub jscriptNform {
1.324     albertel  620:     my ($symb) = @_;
1.442     banghart  621:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        622:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    623: 	'    function viewOneStudent(user,domain) {'."\n".
                    624: 	'	document.onestudent.student.value = user;'."\n".
                    625: 	'	document.onestudent.userdom.value = domain;'."\n".
                    626: 	'	document.onestudent.submit();'."\n".
                    627: 	'    }'."\n".
                    628: 	'</script>'."\n";
                    629:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  630: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  631: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    632: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  633: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        634: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    635: 	'<input type="hidden" name="student" value="" />'."\n".
                    636: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    637: 	'</form>'."\n";
                    638:     return $jscript;
                    639: }
1.39      ng        640: 
1.447     foxr      641: 
                    642: 
1.315     bowersj2  643: # Given the score (as a number [0-1] and the weight) what is the final
                    644: # point value? This function will round to the nearest tenth, third,
                    645: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  646: sub compute_points {
1.315     bowersj2  647:     my ($score, $weight) = @_;
                    648:     
                    649:     my $tolerance = .00001;
                    650:     my $points = $score * $weight;
                    651: 
                    652:     # Check for nearness to 1/x.
                    653:     my $check_for_nearness = sub {
                    654:         my ($factor) = @_;
                    655:         my $num = ($points * $factor) + $tolerance;
                    656:         my $floored_num = floor($num);
1.316     albertel  657:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  658:             return $floored_num / $factor;
                    659:         }
                    660:         return $points;
                    661:     };
                    662: 
                    663:     $points = $check_for_nearness->(10);
                    664:     $points = $check_for_nearness->(3);
                    665:     $points = $check_for_nearness->(4);
                    666:     
                    667:     return $points;
                    668: }
                    669: 
1.44      ng        670: #------------------ End of general use routines --------------------
1.87      www       671: 
                    672: #
                    673: # Find most similar essay
                    674: #
                    675: 
                    676: sub most_similar {
1.426     albertel  677:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       678: 
                    679: # ignore spaces and punctuation
                    680: 
                    681:     $uessay=~s/\W+/ /gs;
                    682: 
1.282     www       683: # ignore empty submissions (occuring when only files are sent)
                    684: 
                    685:     unless ($uessay=~/\w+/) { return ''; }
                    686: 
1.87      www       687: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       688:     my $limit=0.6;
1.87      www       689:     my $sname='';
                    690:     my $sdom='';
                    691:     my $scrsid='';
                    692:     my $sessay='';
                    693: # go through all essays ...
1.426     albertel  694:     foreach my $tkey (keys(%$old_essays)) {
                    695: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       696: # ... except the same student
1.426     albertel  697:         next if (($tname eq $uname) && ($tdom eq $udom));
                    698: 	my $tessay=$old_essays->{$tkey};
                    699: 	$tessay=~s/\W+/ /gs;
1.87      www       700: # String similarity gives up if not even limit
1.426     albertel  701: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       702: # Found one
1.426     albertel  703: 	if ($tsimilar>$limit) {
                    704: 	    $limit=$tsimilar;
                    705: 	    $sname=$tname;
                    706: 	    $sdom=$tdom;
                    707: 	    $scrsid=$tcrsid;
                    708: 	    $sessay=$old_essays->{$tkey};
                    709: 	}
1.87      www       710:     }
1.88      www       711:     if ($limit>0.6) {
1.87      www       712:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    713:     } else {
                    714:        return ('','','','',0);
                    715:     }
                    716: }
                    717: 
1.44      ng        718: #-------------------------------------------------------------------
                    719: 
                    720: #------------------------------------ Receipt Verification Routines
1.45      ng        721: #
1.44      ng        722: #--- Check whether a receipt number is valid.---
                    723: sub verifyreceipt {
                    724:     my $request  = shift;
                    725: 
1.257     albertel  726:     my $courseid = $env{'request.course.id'};
1.184     www       727:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  728: 	$env{'form.receipt'};
1.44      ng        729:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  730:     my ($symb)   = &get_symb($request);
1.44      ng        731: 
1.398     albertel  732:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    733: 	$receipt.'</h3></span>'."\n".
                    734: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        735: 
                    736:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   737:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  738:     
                    739:     my $receiptparts=0;
1.390     albertel  740:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    741: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  742:     my $parts=['0'];
1.324     albertel  743:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  744:     foreach (sort 
                    745: 	     {
                    746: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    747: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    748: 		 }
                    749: 		 return $a cmp $b;
                    750: 	     } (keys(%$fullname))) {
1.44      ng        751: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  752: 	foreach my $part (@$parts) {
                    753: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    754: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    755: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  756: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  757: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    758: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    759: 		if ($receiptparts) {
                    760: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    761: 		}
                    762: 		$contents.='</tr>'."\n";
                    763: 		
                    764: 		$matches++;
                    765: 	    }
1.44      ng        766: 	}
                    767:     }
                    768:     if ($matches == 0) {
                    769: 	$string = $title.'No match found for the above receipt.';
                    770:     } else {
1.324     albertel  771: 	$string = &jscriptNform($symb).$title.
1.44      ng        772: 	    'The above receipt matches the following student'.
                    773: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    774: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    775: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    776: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    777: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  778: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    779: 	if ($receiptparts) {
                    780: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    781: 	}
                    782: 	$string.='</tr>'."\n".$contents.
1.44      ng        783: 	    '</table></td></tr></table>'."\n";
                    784:     }
1.324     albertel  785:     return $string.&show_grading_menu_form($symb);
1.44      ng        786: }
                    787: 
                    788: #--- This is called by a number of programs.
                    789: #--- Called from the Grading Menu - View/Grade an individual student
                    790: #--- Also called directly when one clicks on the subm button 
                    791: #    on the problem page.
1.30      ng        792: sub listStudents {
1.41      ng        793:     my ($request) = shift;
1.49      albertel  794: 
1.324     albertel  795:     my ($symb) = &get_symb($request);
1.257     albertel  796:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    797:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    798:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  799:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  800:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    801:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    802:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    803: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  804: 
1.398     albertel  805:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    806: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        807: 
1.324     albertel  808:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  809: 
1.45      ng        810:     $request->print(<<LISTJAVASCRIPT);
                    811: <script type="text/javascript" language="javascript">
1.110     ng        812:     function checkSelect(checkBox) {
                    813: 	var ctr=0;
                    814: 	var sense="";
                    815: 	if (checkBox.length > 1) {
                    816: 	    for (var i=0; i<checkBox.length; i++) {
                    817: 		if (checkBox[i].checked) {
                    818: 		    ctr++;
                    819: 		}
                    820: 	    }
                    821: 	    sense = "a student or group of students";
                    822: 	} else {
                    823: 	    if (checkBox.checked) {
                    824: 		ctr = 1;
                    825: 	    }
                    826: 	    sense = "the student";
                    827: 	}
                    828: 	if (ctr == 0) {
1.126     ng        829: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        830: 	    return false;
                    831: 	}
                    832: 	document.gradesub.submit();
                    833:     }
                    834: 
                    835:     function reLoadList(formname) {
1.112     ng        836: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        837: 	formname.command.value = 'submission';
                    838: 	formname.submit();
                    839:     }
1.45      ng        840: </script>
                    841: LISTJAVASCRIPT
                    842: 
1.118     ng        843:     &commonJSfunctions($request);
1.41      ng        844:     $request->print($result);
1.39      ng        845: 
1.401     albertel  846:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    847:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  848:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    849: 	"\n".$table.
1.401     albertel  850: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  851: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    852: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    853: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    854: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  855: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  856: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  857:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  858: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  859:     }
1.442     banghart  860:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    861:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  862:     $env{'form.Status'} = $saveStatus;
1.267     albertel  863:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    864: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    865: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  866: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    867:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    868:         '<option value="1">Whole Points</option>'.
                    869:         '<option value=".5">Half Points</option>'.
1.349     albertel  870:         '<option value=".25">Quarter Points</option>'.
                    871:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  872:         '</select>'.
1.432     banghart  873:         &build_section_inputs().
1.45      ng        874: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  875: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    876: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    877: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    878: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  879: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        880: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    881: 
1.257     albertel  882:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  883: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        884:     } else {
                    885: 	$gradeTable.='<b>Student Status:</b> '.
                    886: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    887:     }
1.112     ng        888: 
1.126     ng        889:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    890: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        891: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  892: 
                    893: # checkall buttons
                    894:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        895:     $gradeTable.='<input type="button" '."\n".
1.45      ng        896: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  897: 	'value="Next->" /> <br />'."\n";
                    898:     $gradeTable.=&check_buttons();
1.401     albertel  899:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.450     banghart  900:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.45      ng        901:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        902: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    903:     my $loop = 0;
                    904:     while ($loop < 2) {
1.126     ng        905: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  906: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  907: 	if ($env{'form.showgrading'} eq 'yes' 
                    908: 	    && $submitonly ne 'queued'
                    909: 	    && $submitonly ne 'all') {
1.110     ng        910: 	    foreach (sort(@$partlist)) {
1.324     albertel  911: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  912: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    913: 		    ' Status&nbsp;</b></td>';
1.110     ng        914: 	    }
1.301     albertel  915: 	} elsif ($submitonly eq 'queued') {
                    916: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        917: 	}
                    918: 	$loop++;
1.126     ng        919: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        920:     }
1.45      ng        921:     $gradeTable.='</tr>'."\n";
1.41      ng        922: 
1.45      ng        923:     my $ctr = 0;
1.294     albertel  924:     foreach my $student (sort 
                    925: 			 {
                    926: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    927: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    928: 			     }
                    929: 			     return $a cmp $b;
                    930: 			 }
                    931: 			 (keys(%$fullname))) {
1.41      ng        932: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  933: 
1.110     ng        934: 	my %status = ();
1.301     albertel  935: 
                    936: 	if ($submitonly eq 'queued') {
                    937: 	    my %queue_status = 
                    938: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    939: 							$udom,$uname);
                    940: 	    next if (!defined($queue_status{'gradingqueue'}));
                    941: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    942: 	}
                    943: 
                    944: 	if ($env{'form.showgrading'} eq 'yes' 
                    945: 	    && $submitonly ne 'queued'
                    946: 	    && $submitonly ne 'all') {
1.324     albertel  947: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  948: 	    my $submitted = 0;
1.164     albertel  949: 	    my $graded = 0;
1.248     albertel  950: 	    my $incorrect = 0;
1.110     ng        951: 	    foreach (keys(%status)) {
1.145     albertel  952: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  953: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    954: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    955: 		
1.110     ng        956: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    957: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  958: 		    $submitted = 0;
1.150     albertel  959: 		    my ($part)=split(/\./,$partid);
1.110     ng        960: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  961: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        962: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    963: 		}
1.41      ng        964: 	    }
1.248     albertel  965: 	    
1.156     albertel  966: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    967: 				     $submitonly eq 'incorrect' ||
                    968: 				     $submitonly eq 'graded'));
1.248     albertel  969: 	    next if (!$graded && ($submitonly eq 'graded'));
                    970: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        971: 	}
1.34      ng        972: 
1.45      ng        973: 	$ctr++;
1.249     albertel  974: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452   ! banghart  975:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel  976: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        977: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        978: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  979:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    980:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    981: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    982: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.452   ! banghart  983: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
1.110     ng        984: 
1.257     albertel  985: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        986: 		foreach (sort keys(%status)) {
                    987: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  988: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        989: 		}
1.41      ng        990: 	    }
1.126     ng        991: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        992: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        993: 	}
                    994:     }
1.110     ng        995:     if ($ctr%2 ==1) {
1.126     ng        996: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  997: 	    if ($env{'form.showgrading'} eq 'yes' 
                    998: 		&& $submitonly ne 'queued'
                    999: 		&& $submitonly ne 'all') {
1.110     ng       1000: 		foreach (@$partlist) {
                   1001: 		    $gradeTable.='<td>&nbsp;</td>';
                   1002: 		}
1.301     albertel 1003: 	    } elsif ($submitonly eq 'queued') {
                   1004: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1005: 	    }
                   1006: 	$gradeTable.='</tr>';
                   1007:     }
                   1008: 
1.249     albertel 1009:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng       1010: 	'<input type="button" '.
                   1011: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1012: 	'value="Next->" /></form>'."\n";
1.45      ng       1013:     if ($ctr == 0) {
1.96      albertel 1014: 	my $num_students=(scalar(keys(%$fullname)));
                   1015: 	if ($num_students eq 0) {
1.398     albertel 1016: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1017: 	} else {
1.171     albertel 1018: 	    my $submissions='submissions';
                   1019: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1020: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1021: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1022: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1023: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1024: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1025: 	}
1.46      ng       1026:     } elsif ($ctr == 1) {
                   1027: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1028:     }
1.324     albertel 1029:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1030:     $request->print($gradeTable);
1.44      ng       1031:     return '';
1.10      ng       1032: }
                   1033: 
1.44      ng       1034: #---- Called from the listStudents routine
1.249     albertel 1035: 
                   1036: sub check_script {
                   1037:     my ($form, $type)=@_;
                   1038:     my $chkallscript='<script type="text/javascript">
                   1039:     function checkall() {
                   1040:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1041:             ele = document.forms.'.$form.'.elements[i];
                   1042:             if (ele.name == "'.$type.'") {
                   1043:             document.forms.'.$form.'.elements[i].checked=true;
                   1044:                                        }
                   1045:         }
                   1046:     }
                   1047: 
                   1048:     function checksec() {
                   1049:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1050:             ele = document.forms.'.$form.'.elements[i];
                   1051:            string = document.forms.'.$form.'.chksec.value;
                   1052:            if
                   1053:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1054:               document.forms.'.$form.'.elements[i].checked=true;
                   1055:             }
                   1056:         }
                   1057:     }
                   1058: 
                   1059: 
                   1060:     function uncheckall() {
                   1061:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1062:             ele = document.forms.'.$form.'.elements[i];
                   1063:             if (ele.name == "'.$type.'") {
                   1064:             document.forms.'.$form.'.elements[i].checked=false;
                   1065:                                        }
                   1066:         }
                   1067:     }
                   1068: 
                   1069: </script>'."\n";
                   1070:     return $chkallscript;
                   1071: }
                   1072: 
                   1073: sub check_buttons {
                   1074:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1075:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1076:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1077:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1078:     return $buttons;
                   1079: }
                   1080: 
1.44      ng       1081: #     Displays the submissions for one student or a group of students
1.34      ng       1082: sub processGroup {
1.41      ng       1083:     my ($request)  = shift;
                   1084:     my $ctr        = 0;
1.155     albertel 1085:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1086:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1087: 
1.396     banghart 1088:     foreach my $student (@stuchecked) {
                   1089: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1090: 	$env{'form.student'}        = $uname;
                   1091: 	$env{'form.userdom'}        = $udom;
                   1092: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1093: 	&submission($request,$ctr,$total);
                   1094: 	$ctr++;
                   1095:     }
                   1096:     return '';
1.35      ng       1097: }
1.34      ng       1098: 
1.44      ng       1099: #------------------------------------------------------------------------------------
                   1100: #
                   1101: #-------------------------- Next few routines handles grading by student, essentially
                   1102: #                           handles essay response type problem/part
                   1103: #
                   1104: #--- Javascript to handle the submission page functionality ---
                   1105: sub sub_page_js {
                   1106:     my $request = shift;
                   1107:     $request->print(<<SUBJAVASCRIPT);
                   1108: <script type="text/javascript" language="javascript">
1.71      ng       1109:     function updateRadio(formname,id,weight) {
1.125     ng       1110: 	var gradeBox = formname["GD_BOX"+id];
                   1111: 	var radioButton = formname["RADVAL"+id];
                   1112: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1113: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1114: 	gradeBox.value = pts;
                   1115: 	var resetbox = false;
                   1116: 	if (isNaN(pts) || pts < 0) {
                   1117: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1118: 	    for (var i=0; i<radioButton.length; i++) {
                   1119: 		if (radioButton[i].checked) {
                   1120: 		    gradeBox.value = i;
                   1121: 		    resetbox = true;
                   1122: 		}
                   1123: 	    }
                   1124: 	    if (!resetbox) {
                   1125: 		formtextbox.value = "";
                   1126: 	    }
                   1127: 	    return;
1.44      ng       1128: 	}
1.71      ng       1129: 
                   1130: 	if (pts > weight) {
                   1131: 	    var resp = confirm("You entered a value ("+pts+
                   1132: 			       ") greater than the weight for the part. Accept?");
                   1133: 	    if (resp == false) {
1.125     ng       1134: 		gradeBox.value = oldpts;
1.71      ng       1135: 		return;
                   1136: 	    }
1.44      ng       1137: 	}
1.13      albertel 1138: 
1.71      ng       1139: 	for (var i=0; i<radioButton.length; i++) {
                   1140: 	    radioButton[i].checked=false;
                   1141: 	    if (pts == i && pts != "") {
                   1142: 		radioButton[i].checked=true;
                   1143: 	    }
                   1144: 	}
                   1145: 	updateSelect(formname,id);
1.125     ng       1146: 	formname["stores"+id].value = "0";
1.41      ng       1147:     }
1.5       albertel 1148: 
1.72      ng       1149:     function writeBox(formname,id,pts) {
1.125     ng       1150: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1151: 	if (checkSolved(formname,id) == 'update') {
                   1152: 	    gradeBox.value = pts;
                   1153: 	} else {
1.125     ng       1154: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1155: 	    gradeBox.value = oldpts;
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;
1.72      ng       1159: 		if (i == oldpts) {
1.71      ng       1160: 		    radioButton[i].checked=true;
                   1161: 		}
                   1162: 	    }
1.41      ng       1163: 	}
1.125     ng       1164: 	formname["stores"+id].value = "0";
1.71      ng       1165: 	updateSelect(formname,id);
                   1166: 	return;
1.41      ng       1167:     }
1.44      ng       1168: 
1.71      ng       1169:     function clearRadBox(formname,id) {
                   1170: 	if (checkSolved(formname,id) == 'noupdate') {
                   1171: 	    updateSelect(formname,id);
                   1172: 	    return;
                   1173: 	}
1.125     ng       1174: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1175: 	for (var i=0; i<gradeSelect.length; i++) {
                   1176: 	    if (gradeSelect[i].selected) {
                   1177: 		var selectx=i;
                   1178: 	    }
                   1179: 	}
1.125     ng       1180: 	var stores = formname["stores"+id];
1.71      ng       1181: 	if (selectx == stores.value) { return };
1.125     ng       1182: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1183: 	gradeBox.value = "";
1.125     ng       1184: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1185: 	for (var i=0; i<radioButton.length; i++) {
                   1186: 	    radioButton[i].checked=false;
                   1187: 	}
                   1188: 	stores.value = selectx;
                   1189:     }
1.5       albertel 1190: 
1.71      ng       1191:     function checkSolved(formname,id) {
1.125     ng       1192: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1193: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1194: 	    if (!reply) {return "noupdate";}
1.120     ng       1195: 	    formname.overRideScore.value = 'yes';
1.41      ng       1196: 	}
1.71      ng       1197: 	return "update";
1.13      albertel 1198:     }
1.71      ng       1199: 
                   1200:     function updateSelect(formname,id) {
1.125     ng       1201: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1202: 	return;
1.41      ng       1203:     }
1.33      ng       1204: 
1.121     ng       1205: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1206:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1207: 	formname.gradeOpt.value = val;
1.71      ng       1208: 	if (val == "Save & Next") {
                   1209: 	    for (i=0;i<=total;i++) {
                   1210: 		for (j=0;j<parttot;j++) {
1.125     ng       1211: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1212: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1213: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1214: 			if (points == "") {
1.125     ng       1215: 			    var name = formname["name"+i].value;
1.129     ng       1216: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1217: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1218: 					       ", part "+partid+". Continue?");
1.71      ng       1219: 			    if (resp == false) {
1.125     ng       1220: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1221: 				return false;
                   1222: 			    }
                   1223: 			}
                   1224: 		    }
                   1225: 		    
                   1226: 		}
                   1227: 	    }
                   1228: 	    
                   1229: 	}
1.121     ng       1230: 	if (val == "Grade Student") {
                   1231: 	    formname.showgrading.value = "yes";
                   1232: 	    if (formname.Status.value == "") {
                   1233: 		formname.Status.value = "Active";
                   1234: 	    }
                   1235: 	    formname.studentNo.value = total;
                   1236: 	}
1.120     ng       1237: 	formname.submit();
                   1238:     }
                   1239: 
1.71      ng       1240: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1241:     function checkSubmitPage(formname,total) {
                   1242: 	noscore = new Array(100);
                   1243: 	var ptr = 0;
                   1244: 	for (i=1;i<total;i++) {
1.125     ng       1245: 	    var partid = formname["q_"+i].value;
1.127     ng       1246: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1247: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1248: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1249: 		if (points == "" && status != "correct_by_student") {
                   1250: 		    noscore[ptr] = i;
                   1251: 		    ptr++;
                   1252: 		}
                   1253: 	    }
                   1254: 	}
                   1255: 	if (ptr != 0) {
                   1256: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1257: 	    var prolist = "";
                   1258: 	    if (ptr == 1) {
                   1259: 		prolist = noscore[0];
                   1260: 	    } else {
                   1261: 		var i = 0;
                   1262: 		while (i < ptr-1) {
                   1263: 		    prolist += noscore[i]+", ";
                   1264: 		    i++;
                   1265: 		}
                   1266: 		prolist += "and "+noscore[i];
                   1267: 	    }
                   1268: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1269: 	    if (resp == false) {
                   1270: 		return false;
                   1271: 	    }
                   1272: 	}
1.45      ng       1273: 
1.71      ng       1274: 	formname.submit();
                   1275:     }
                   1276: </script>
                   1277: SUBJAVASCRIPT
                   1278: }
1.45      ng       1279: 
1.71      ng       1280: #--- javascript for essay type problem --
                   1281: sub sub_page_kw_js {
                   1282:     my $request = shift;
1.80      ng       1283:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1284:     &commonJSfunctions($request);
1.350     albertel 1285: 
1.351     albertel 1286:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1287:     <script text="text/javascript">
                   1288:     function checkInput() {
                   1289:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1290:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1291:       var usrctr = document.msgcenter.usrctr.value;
                   1292:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1293:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1294: 
                   1295:       var msgchk = "";
                   1296:       if (document.msgcenter.subchk.checked) {
                   1297:          msgchk = "msgsub,";
                   1298:       }
                   1299:       var includemsg = 0;
                   1300:       for (var i=1; i<=nmsg; i++) {
                   1301:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1302:           var frmmsg = document.msgcenter["msg"+i];
                   1303:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1304:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1305:           showflg.value = "1";
                   1306:           var chkbox = document.msgcenter["msgn"+i];
                   1307:           if (chkbox.checked) {
                   1308:              msgchk += "savemsg"+i+",";
                   1309:              includemsg = 1;
                   1310:           }
                   1311:       }
                   1312:       if (document.msgcenter.newmsgchk.checked) {
                   1313:          msgchk += "newmsg"+usrctr;
                   1314:          includemsg = 1;
                   1315:       }
                   1316:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1317:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1318:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1319:       includemsg.value = msgchk;
                   1320: 
                   1321:       self.close()
                   1322: 
                   1323:     }
                   1324:     </script>
                   1325: INNERJS
                   1326: 
1.351     albertel 1327:     my $inner_js_highlight_central=<<INNERJS;
                   1328:  <script type="text/javascript">
                   1329:     function updateChoice(flag) {
                   1330:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1331:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1332:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1333:       opener.document.SCORE.refresh.value = "on";
                   1334:       if (opener.document.SCORE.keywords.value!=""){
                   1335:          opener.document.SCORE.submit();
                   1336:       }
                   1337:       self.close()
                   1338:     }
                   1339: </script>
                   1340: INNERJS
                   1341: 
                   1342:     my $start_page_msg_central = 
                   1343:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1344: 				       {'js_ready'  => 1,
                   1345: 					'only_body' => 1,
                   1346: 					'bgcolor'   =>'#FFFFFF',});
                   1347:     my $end_page_msg_central = 
                   1348: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1349: 
                   1350: 
                   1351:     my $start_page_highlight_central = 
                   1352:         &Apache::loncommon::start_page('Highlight Central',
                   1353: 				       $inner_js_highlight_central,
1.350     albertel 1354: 				       {'js_ready'  => 1,
                   1355: 					'only_body' => 1,
                   1356: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1357:     my $end_page_highlight_central = 
1.350     albertel 1358: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1359: 
1.219     www      1360:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1361:     $docopen=~s/^document\.//;
1.71      ng       1362:     $request->print(<<SUBJAVASCRIPT);
                   1363: <script type="text/javascript" language="javascript">
1.45      ng       1364: 
1.44      ng       1365: //===================== Show list of keywords ====================
1.122     ng       1366:   function keywords(formname) {
                   1367:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1368:     if (nret==null) return;
1.122     ng       1369:     formname.keywords.value = nret;
1.44      ng       1370: 
1.122     ng       1371:     if (formname.keywords.value != "") {
1.128     ng       1372: 	formname.refresh.value = "on";
1.122     ng       1373: 	formname.submit();
1.44      ng       1374:     }
                   1375:     return;
                   1376:   }
                   1377: 
                   1378: //===================== Script to view submitted by ==================
                   1379:   function viewSubmitter(submitter) {
                   1380:     document.SCORE.refresh.value = "on";
                   1381:     document.SCORE.NCT.value = "1";
                   1382:     document.SCORE.unamedom0.value = submitter;
                   1383:     document.SCORE.submit();
                   1384:     return;
                   1385:   }
                   1386: 
                   1387: //===================== Script to add keyword(s) ==================
                   1388:   function getSel() {
                   1389:     if (document.getSelection) txt = document.getSelection();
                   1390:     else if (document.selection) txt = document.selection.createRange().text;
                   1391:     else return;
                   1392:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1393:     if (cleantxt=="") {
1.46      ng       1394: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1395: 	return;
                   1396:     }
                   1397:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1398:     if (nret==null) return;
1.127     ng       1399:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1400:     if (document.SCORE.keywords.value != "") {
1.127     ng       1401: 	document.SCORE.refresh.value = "on";
1.44      ng       1402: 	document.SCORE.submit();
                   1403:     }
                   1404:     return;
                   1405:   }
                   1406: 
                   1407: //====================== Script for composing message ==============
1.80      ng       1408:    // preload images
                   1409:    img1 = new Image();
                   1410:    img1.src = "$iconpath/mailbkgrd.gif";
                   1411:    img2 = new Image();
                   1412:    img2.src = "$iconpath/mailto.gif";
                   1413: 
1.44      ng       1414:   function msgCenter(msgform,usrctr,fullname) {
                   1415:     var Nmsg  = msgform.savemsgN.value;
                   1416:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1417:     var subject = msgform.msgsub.value;
1.127     ng       1418:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1419:     re = /msgsub/;
                   1420:     var shwsel = "";
                   1421:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1422:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1423:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1424:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1425: 	var testmsg = "savemsg"+i+",";
                   1426: 	re = new RegExp(testmsg,"g");
1.44      ng       1427: 	shwsel = "";
                   1428: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1429: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1430: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1431: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1432: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1433:     }
1.125     ng       1434:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1435:     shwsel = "";
                   1436:     re = /newmsg/;
                   1437:     if (re.test(msgchk)) { shwsel = "checked" }
                   1438:     newMsg(newmsg,shwsel);
                   1439:     msgTail(); 
                   1440:     return;
                   1441:   }
                   1442: 
1.123     ng       1443:   function checkEntities(strx) {
                   1444:     if (strx.length == 0) return strx;
                   1445:     var orgStr = ["&", "<", ">", '"']; 
                   1446:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1447:     var counter = 0;
                   1448:     while (counter < 4) {
                   1449: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1450: 	counter++;
                   1451:     }
                   1452:     return strx;
                   1453:   }
                   1454: 
                   1455:   function strReplace(strx, orgStr, newStr) {
                   1456:     return strx.split(orgStr).join(newStr);
                   1457:   }
                   1458: 
1.44      ng       1459:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1460:     var height = 70*Nmsg+250;
1.44      ng       1461:     var scrollbar = "no";
                   1462:     if (height > 600) {
                   1463: 	height = 600;
                   1464: 	scrollbar = "yes";
                   1465:     }
1.118     ng       1466:     var xpos = (screen.width-600)/2;
                   1467:     xpos = (xpos < 0) ? '0' : xpos;
                   1468:     var ypos = (screen.height-height)/2-30;
                   1469:     ypos = (ypos < 0) ? '0' : ypos;
                   1470: 
1.206     albertel 1471:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1472:     pWin.focus();
                   1473:     pDoc = pWin.document;
1.219     www      1474:     pDoc.$docopen;
1.351     albertel 1475:     pDoc.write('$start_page_msg_central');
1.76      ng       1476: 
                   1477:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1478:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1479:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1480: 
                   1481:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1482:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1483:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1484: }
                   1485:     function displaySubject(msg,shwsel) {
1.76      ng       1486:     pDoc = pWin.document;
                   1487:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1488:     pDoc.write("<td>Subject</td>");
                   1489:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1490:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1491: }
                   1492: 
1.72      ng       1493:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1494:     pDoc = pWin.document;
                   1495:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1496:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1497:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1498:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1499: }
                   1500: 
                   1501:   function newMsg(newmsg,shwsel) {
1.76      ng       1502:     pDoc = pWin.document;
                   1503:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1504:     pDoc.write("<td align=\\"center\\">New</td>");
                   1505:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1506:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1507: }
                   1508: 
                   1509:   function msgTail() {
1.76      ng       1510:     pDoc = pWin.document;
                   1511:     pDoc.write("</table>");
                   1512:     pDoc.write("</td></tr></table>&nbsp;");
                   1513:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1514:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1515:     pDoc.write("</form>");
1.351     albertel 1516:     pDoc.write('$end_page_msg_central');
1.128     ng       1517:     pDoc.close();
1.44      ng       1518: }
                   1519: 
                   1520: //====================== Script for keyword highlight options ==============
                   1521:   function kwhighlight() {
                   1522:     var kwclr    = document.SCORE.kwclr.value;
                   1523:     var kwsize   = document.SCORE.kwsize.value;
                   1524:     var kwstyle  = document.SCORE.kwstyle.value;
                   1525:     var redsel = "";
                   1526:     var grnsel = "";
                   1527:     var blusel = "";
                   1528:     if (kwclr=="red")   {var redsel="checked"};
                   1529:     if (kwclr=="green") {var grnsel="checked"};
                   1530:     if (kwclr=="blue")  {var blusel="checked"};
                   1531:     var sznsel = "";
                   1532:     var sz1sel = "";
                   1533:     var sz2sel = "";
                   1534:     if (kwsize=="0")  {var sznsel="checked"};
                   1535:     if (kwsize=="+1") {var sz1sel="checked"};
                   1536:     if (kwsize=="+2") {var sz2sel="checked"};
                   1537:     var synsel = "";
                   1538:     var syisel = "";
                   1539:     var sybsel = "";
                   1540:     if (kwstyle=="")    {var synsel="checked"};
                   1541:     if (kwstyle=="<i>") {var syisel="checked"};
                   1542:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1543:     highlightCentral();
                   1544:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1545:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1546:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1547:     highlightend();
                   1548:     return;
                   1549:   }
                   1550: 
                   1551:   function highlightCentral() {
1.76      ng       1552: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1553:     var xpos = (screen.width-400)/2;
                   1554:     xpos = (xpos < 0) ? '0' : xpos;
                   1555:     var ypos = (screen.height-330)/2-30;
                   1556:     ypos = (ypos < 0) ? '0' : ypos;
                   1557: 
1.206     albertel 1558:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1559:     hwdWin.focus();
                   1560:     var hDoc = hwdWin.document;
1.219     www      1561:     hDoc.$docopen;
1.351     albertel 1562:     hDoc.write('$start_page_highlight_central');
1.76      ng       1563:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1564:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1565: 
                   1566:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1567:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1568:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1569:   }
                   1570: 
                   1571:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1572:     var hDoc = hwdWin.document;
                   1573:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1574:     hDoc.write("<td align=\\"left\\">");
                   1575:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1576:     hDoc.write("<td align=\\"left\\">");
                   1577:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1578:     hDoc.write("<td align=\\"left\\">");
                   1579:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1580:     hDoc.write("</tr>");
1.44      ng       1581:   }
                   1582: 
                   1583:   function highlightend() { 
1.76      ng       1584:     var hDoc = hwdWin.document;
                   1585:     hDoc.write("</table>");
                   1586:     hDoc.write("</td></tr></table>&nbsp;");
                   1587:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1588:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1589:     hDoc.write("</form>");
1.351     albertel 1590:     hDoc.write('$end_page_highlight_central');
1.128     ng       1591:     hDoc.close();
1.44      ng       1592:   }
                   1593: 
                   1594: </script>
                   1595: SUBJAVASCRIPT
                   1596: }
                   1597: 
1.349     albertel 1598: sub get_increment {
1.348     bowersj2 1599:     my $increment = $env{'form.increment'};
                   1600:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1601:         $increment != .1) {
                   1602:         $increment = 1;
                   1603:     }
                   1604:     return $increment;
                   1605: }
                   1606: 
1.71      ng       1607: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1608: sub gradeBox {
1.322     albertel 1609:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1610:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1611: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1612: 	'/check.gif" height="16" border="0" />';
                   1613:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1614:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1615: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1616:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1617:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1618: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1619:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1620:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1621:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1622: 				       [$partid]);
                   1623:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1624:     if ($last_resets{$partid}) {
                   1625:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1626:     }
1.71      ng       1627:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1628: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1629:     my $ctr = 0;
1.348     bowersj2 1630:     my $thisweight = 0;
1.349     albertel 1631:     my $increment = &get_increment();
1.71      ng       1632:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1633:     while ($thisweight<=$wgt) {
1.381     albertel 1634: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1635: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1636: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1637: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1638: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1639:         $thisweight += $increment;
1.71      ng       1640: 	$ctr++;
                   1641:     }
                   1642:     $result.='</tr></table>';
                   1643:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1644:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1645: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1646: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1647: 	$wgt.')" /></td>'."\n";
                   1648:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1649: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1650: 	' </td><td>'."\n";
                   1651:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1652: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1653:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1654: 	$result.='<option></option>'.
1.401     albertel 1655: 	    '<option selected="selected">excused</option>';
1.71      ng       1656:     } else {
1.401     albertel 1657: 	$result.='<option selected="selected"></option>'.
1.125     ng       1658: 	    '<option>excused</option>';
1.71      ng       1659:     }
1.125     ng       1660:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1661:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1662:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1663: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1664: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1665: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1666:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1667:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1668:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1669:         $aggtries.'" />'."\n";
1.71      ng       1670:     $result.='</td></tr></table>'."\n";
1.323     banghart 1671:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1672:     return $result;
                   1673: }
1.322     albertel 1674: 
                   1675: sub handback_box {
1.323     banghart 1676:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1677:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1678:     my (@respids);
1.375     albertel 1679:      my @part_response_id = &flatten_responseType($responseType);
                   1680:     foreach my $part_response_id (@part_response_id) {
                   1681:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1682:         if ($part eq $partid) {
1.375     albertel 1683:             push(@respids,$resp);
1.323     banghart 1684:         }
                   1685:     }
1.318     banghart 1686:     my $result;
1.323     banghart 1687:     foreach my $respid (@respids) {
1.322     albertel 1688: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1689: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1690: 	next if (!@$files);
                   1691: 	my $file_counter = 1;
1.313     banghart 1692: 	foreach my $file (@$files) {
1.368     banghart 1693: 	    if ($file =~ /\/portfolio\//) {
                   1694:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1695:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1696:     	        $file_disp = "$name.$ext";
                   1697:     	        $file = $file_path.$file_disp;
                   1698:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1699:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1700:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1701:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1702:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1703:     	        $file_counter++;
                   1704: 	    }
1.322     albertel 1705: 	}
1.313     banghart 1706:     }
1.318     banghart 1707:     return $result;    
1.71      ng       1708: }
1.44      ng       1709: 
1.58      albertel 1710: sub show_problem {
1.382     albertel 1711:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1712:     my $rendered;
1.382     albertel 1713:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1714:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1715:     if ($mode eq 'both' or $mode eq 'text') {
                   1716: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1717: 						       $env{'request.course.id'},
                   1718: 						       undef,\%form);
1.144     albertel 1719:     }
1.58      albertel 1720:     if ($removeform) {
                   1721: 	$rendered=~s|<form(.*?)>||g;
                   1722: 	$rendered=~s|</form>||g;
1.374     albertel 1723: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1724:     }
1.144     albertel 1725:     my $companswer;
                   1726:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1727: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1728: 	$companswer=
                   1729: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1730: 						    $env{'request.course.id'},
                   1731: 						    %form);
1.144     albertel 1732:     }
1.58      albertel 1733:     if ($removeform) {
                   1734: 	$companswer=~s|<form(.*?)>||g;
                   1735: 	$companswer=~s|</form>||g;
1.144     albertel 1736: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1737:     }
                   1738:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1739:     $result.='<table border="0" width="100%">';
1.144     albertel 1740:     if ($viewon) {
                   1741: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1742: 	if ($mode eq 'both' or $mode eq 'text') {
                   1743: 	    $result.='View of the problem - ';
                   1744: 	} else {
                   1745: 	    $result.='Correct answer: ';
                   1746: 	}
1.257     albertel 1747: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1748:     }
                   1749:     if ($mode eq 'both') {
                   1750: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1751: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1752:     } elsif ($mode eq 'text') {
                   1753: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1754:     } elsif ($mode eq 'answer') {
                   1755: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1756:     }
1.58      albertel 1757:     $result.='</td></tr></table>';
                   1758:     $result.='</td></tr></table><br />';
1.71      ng       1759:     return $result;
1.58      albertel 1760: }
1.397     albertel 1761: 
1.396     banghart 1762: sub files_exist {
                   1763:     my ($r, $symb) = @_;
                   1764:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1765: 
1.396     banghart 1766:     foreach my $student (@students) {
                   1767:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1768:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1769: 					      $udom,$uname);
1.396     banghart 1770:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1771:         foreach my $submission (@$string) {
                   1772:             my ($partid,$respid) =
                   1773: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1774:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1775: 					   \%record);
                   1776:             return 1 if (@$files);
1.396     banghart 1777:         }
                   1778:     }
1.397     albertel 1779:     return 0;
1.396     banghart 1780: }
1.397     albertel 1781: 
1.394     banghart 1782: sub download_all_link {
                   1783:     my ($r,$symb) = @_;
1.395     albertel 1784:     my $all_students = 
                   1785: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1786: 
                   1787:     my $parts =
                   1788: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1789: 
1.394     banghart 1790:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1791:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1792:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1793:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1794:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1795: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1796:     return
                   1797: }
1.395     albertel 1798: 
1.432     banghart 1799: sub build_section_inputs {
                   1800:     my $section_inputs;
                   1801:     if ($env{'form.section'} eq '') {
                   1802:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1803:     } else {
                   1804:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1805:         foreach my $section (@sections) {
1.432     banghart 1806:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1807:         }
                   1808:     }
                   1809:     return $section_inputs;
                   1810: }
                   1811: 
1.44      ng       1812: # --------------------------- show submissions of a student, option to grade 
                   1813: sub submission {
                   1814:     my ($request,$counter,$total) = @_;
1.257     albertel 1815:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1816:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1817:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1818:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1819:     my $symb = &get_symb($request); 
                   1820:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1821: 
                   1822:     if (!&canview($usec)) {
1.398     albertel 1823: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1824: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1825: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1826: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1827: 	return;
                   1828:     }
                   1829: 
1.257     albertel 1830:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1831:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1832:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1833:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1834:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1835: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1836: 	'/check.gif" height="16" border="0" />';
1.41      ng       1837: 
1.426     albertel 1838:     my %old_essays;
1.41      ng       1839:     # header info
                   1840:     if ($counter == 0) {
                   1841: 	&sub_page_js($request);
1.257     albertel 1842: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1843: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1844: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1845: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1846: 	    &download_all_link($request, $symb);
                   1847: 	}
1.398     albertel 1848: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1849: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1850: 
1.257     albertel 1851: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1852: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1853: 		$checkIcon.' symbol.'."\n";
                   1854: 	    $request->print($checkMark);
                   1855: 	}
1.41      ng       1856: 
1.44      ng       1857: 	# option to display problem, only once else it cause problems 
                   1858:         # with the form later since the problem has a form.
1.257     albertel 1859: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1860: 	    my $mode;
1.257     albertel 1861: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1862: 		$mode='both';
1.257     albertel 1863: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1864: 		$mode='text';
1.257     albertel 1865: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1866: 		$mode='answer';
                   1867: 	    }
1.329     albertel 1868: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1869: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1870: 	}
1.441     www      1871: 
1.44      ng       1872: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1873:         # if this subroutine has been called once.
1.41      ng       1874: 	my %keyhash = ();
1.257     albertel 1875: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1876: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1877: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1878: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1879: 
1.257     albertel 1880: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1881: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1882: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1883: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1884: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1885: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1886: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1887: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1888: 	}
1.257     albertel 1889: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1890: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1891: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1892: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1893: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1894: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1895: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1896: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1897: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1898: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1899: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1900: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1901: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1902: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1903: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1904: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1905: 			&build_section_inputs().
1.326     albertel 1906: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1907: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1908: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1909: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1910: 	if ($env{'form.handgrade'} eq 'yes') {
                   1911: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1912: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1913: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1914: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1915: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1916: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1917: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1918: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1919: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1920: 	    }
1.123     ng       1921: 	}
1.41      ng       1922: 	
                   1923: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1924: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1925: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1926: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1927: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1928: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1929: 		'" />'."\n".
                   1930: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1931: 	    $cts++;
                   1932: 	}
                   1933: 	$request->print($prnmsg);
1.32      ng       1934: 
1.257     albertel 1935: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1936: #
                   1937: # Print out the keyword options line
                   1938: #
1.41      ng       1939: 	    $request->print(<<KEYWORDS);
1.38      ng       1940: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1941: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1942: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1943:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1944: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1945: KEYWORDS
1.88      www      1946: #
                   1947: # Load the other essays for similarity check
                   1948: #
1.324     albertel 1949:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1950: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1951: 	    $apath=&escape($apath);
1.88      www      1952: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1953: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1954:         }
                   1955:     }
1.44      ng       1956: 
1.441     www      1957: # This is where output for one specific student would start
                   1958:     my $bgcolor='#DDEEDD';
                   1959:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1960:     $request->print("\n\n".
                   1961:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1962: 
1.257     albertel 1963:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1964: 	my $mode;
1.257     albertel 1965: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1966: 	    $mode='both';
1.257     albertel 1967: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1968: 	    $mode='text';
1.257     albertel 1969: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1970: 	    $mode='answer';
                   1971: 	}
1.329     albertel 1972: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1973: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1974:     }
1.144     albertel 1975: 
1.257     albertel 1976:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1977:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1978: 
1.44      ng       1979:     # Display student info
1.41      ng       1980:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1981:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1982: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1983: 
1.257     albertel 1984:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1985:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1986: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1987: 
1.118     ng       1988:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1989:     my @col_fullnames;
1.56      matthew  1990:     my ($classlist,$fullname);
1.257     albertel 1991:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1992: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1993: 	for (keys (%$handgrade)) {
1.44      ng       1994: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1995: 					    '.maxcollaborators',
                   1996:                                             $symb,$udom,$uname);
                   1997: 	    next if ($ncol <= 0);
                   1998:             s/\_/\./g;
                   1999:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       2000:             my @goodcollaborators = ();
                   2001:             my @badcollaborators  = ();
                   2002: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   2003: 		$_ =~ s/[\$\^\(\)]//g;
                   2004: 		next if ($_ eq '');
1.80      ng       2005: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       2006: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       2007: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       2008: 		# Doing this grep allows 'fuzzy' specification
                   2009: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   2010: 		if (! scalar(@Matches)) {
                   2011: 		    push @badcollaborators,$_;
                   2012: 		} else {
                   2013: 		    push @goodcollaborators, @Matches;
                   2014: 		}
1.80      ng       2015: 	    }
1.86      ng       2016:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  2017:                 $result.='<b>Collaborators: </b>';
1.86      ng       2018:                 foreach (@goodcollaborators) {
                   2019: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   2020: 		    push @col_fullnames, $givenn.' '.$lastname;
                   2021: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   2022: 		}
1.57      matthew  2023:                 $result.='<br />'."\n";
1.150     albertel 2024: 		my ($part)=split(/\./,$_);
1.86      ng       2025: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 2026: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2027: 		    "\n";
1.86      ng       2028: 	    }
                   2029: 	    if (scalar(@badcollaborators) > 0) {
                   2030: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2031: 		$result.='This student has submitted ';
                   2032: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2033: 		$result .= ': '.join(', ',@badcollaborators);
                   2034: 		$result .= '</td></tr></table>';
                   2035: 	    }         
                   2036: 	    if (scalar(@badcollaborators > $ncol)) {
                   2037: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2038: 		$result .= 'This student has submitted too many '.
                   2039: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2040: 		$result .= '</td></tr></table>';
                   2041: 	    }
1.41      ng       2042: 	}
                   2043:     }
1.44      ng       2044:     $request->print($result."\n");
1.33      ng       2045: 
1.44      ng       2046:     # print student answer/submission
                   2047:     # Options are (1) Handgaded submission only
                   2048:     #             (2) Last submission, includes submission that is not handgraded 
                   2049:     #                  (for multi-response type part)
                   2050:     #             (3) Last submission plus the parts info
                   2051:     #             (4) The whole record for this student
1.257     albertel 2052:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2053: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2054: 	my $lastsubonly=''.
                   2055: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2056: 	     $$timestamp)."</td></tr>\n";
                   2057: 	if ($$timestamp eq '') {
                   2058: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2059: 	} else {
                   2060: 	    my %seenparts;
1.375     albertel 2061: 	    my @part_response_id = &flatten_responseType($responseType);
                   2062: 	    foreach my $part (@part_response_id) {
1.393     albertel 2063: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2064: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2065: 
1.375     albertel 2066: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2067: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2068: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2069: 		    if (exists($seenparts{$partid})) { next; }
                   2070: 		    $seenparts{$partid}=1;
1.207     albertel 2071: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2072: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2073: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2074: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2075: 			'\');" target="_self">'.
1.257     albertel 2076: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2077: 		    $request->print($submitby);
                   2078: 		    next;
                   2079: 		}
                   2080: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2081: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2082: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2083: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2084: 			' )</span>&nbsp; &nbsp;'.
                   2085: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2086: 		    next;
                   2087: 		}
                   2088: 		foreach (@$string) {
                   2089: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2090: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2091: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2092: 		    # Similarity check
                   2093: 		    my $similar='';
1.257     albertel 2094: 		    if($env{'form.checkPlag'}){
1.151     albertel 2095: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2096: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2097: 			if ($osim) {
                   2098: 			    $osim=int($osim*100.0);
1.426     albertel 2099: 			    my %old_course_desc = 
                   2100: 				&Apache::lonnet::coursedescription($ocrsid,
                   2101: 								   {'one_time' => 1});
                   2102: 
                   2103: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2104: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2105: 				    $osim,
                   2106: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2107: 				    $oname,$odom,
1.426     albertel 2108: 				    $old_course_desc{'description'},
1.427     albertel 2109: 				    $old_course_desc{'num'},
1.426     albertel 2110: 				    $old_course_desc{'domain'}).
1.398     albertel 2111: 				'</span></h3><blockquote><i>'.
1.151     albertel 2112: 				&keywords_highlight($oessay).
                   2113: 				'</i></blockquote><hr />';
                   2114: 			}
1.150     albertel 2115: 		    }
1.151     albertel 2116: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2117: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2118: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2119: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2120: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2121: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2122: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2123: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2124: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2125: 			if (@$files) {
1.398     albertel 2126: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2127: 			    my $file_counter = 0;
1.313     banghart 2128: 			    foreach my $file (@$files) {
1.303     banghart 2129: 			        $file_counter ++;
1.232     albertel 2130: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2131: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2132: 			    }
1.236     albertel 2133: 			    $lastsubonly.='<br />';
1.41      ng       2134: 			}
1.151     albertel 2135: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2136: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2137: 					 $respid,\%record,$order);
                   2138: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2139: 		    }
                   2140: 		}
                   2141: 	    }
1.151     albertel 2142: 	}
                   2143: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2144: 	$request->print($lastsubonly);
1.257     albertel 2145:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2146: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2147: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2148:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2149: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2150: 								 $env{'request.course.id'},
1.44      ng       2151: 								 $last,'.submission',
                   2152: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2153:     }
1.120     ng       2154: 
1.121     ng       2155:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2156: 	.$udom.'" />'."\n");
1.41      ng       2157:     
1.44      ng       2158:     # return if view submission with no grading option
1.257     albertel 2159:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2160: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2161: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2162: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2163: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2164: 	if (($env{'form.command'} eq 'submission') || 
                   2165: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2166: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2167: 	}
1.180     albertel 2168: 	$request->print($toGrade);
1.41      ng       2169: 	return;
1.180     albertel 2170:     } else {
                   2171: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2172:     }
1.33      ng       2173: 
1.121     ng       2174:     # essay grading message center
1.257     albertel 2175:     if ($env{'form.handgrade'} eq 'yes') {
                   2176: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2177: 	my $msgfor = $givenn.' '.$lastname;
                   2178: 	if (scalar(@col_fullnames) > 0) {
                   2179: 	    my $lastone = pop @col_fullnames;
                   2180: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2181: 	}
                   2182: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2183: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2184: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2185: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2186: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2187: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2188: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2189: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2190: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2191: 	    '<br />&nbsp;('.
                   2192: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2193: 	$request->print($result);
1.118     ng       2194:     }
1.300     albertel 2195:     if ($perm{'vgr'}) {
1.297     www      2196: 	$request->print('<br />'.
1.300     albertel 2197: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2198: 						   $uname,$udom,'check'));
1.297     www      2199:     }
1.300     albertel 2200:     if ($perm{'opa'}) {
1.297     www      2201: 	$request->print('<br />'.
1.300     albertel 2202: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2203: 					 $uname,$udom,$symb,'check'));
1.297     www      2204:     }
1.41      ng       2205: 
                   2206:     my %seen = ();
                   2207:     my @partlist;
1.129     ng       2208:     my @gradePartRespid;
1.375     albertel 2209:     my @part_response_id = &flatten_responseType($responseType);
                   2210:     foreach my $part_response_id (@part_response_id) {
                   2211:     	my ($partid,$respid) = @{ $part_response_id };
                   2212: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2213: 	next if ($seen{$partid} > 0);
1.41      ng       2214: 	$seen{$partid}++;
1.393     albertel 2215: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2216: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2217: 	push @partlist,$partid;
1.129     ng       2218: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2219: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2220:     }
1.45      ng       2221:     $result='<input type="hidden" name="partlist'.$counter.
                   2222: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2223:     $result.='<input type="hidden" name="gradePartRespid'.
                   2224: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2225:     my $ctr = 0;
                   2226:     while ($ctr < scalar(@partlist)) {
                   2227: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2228: 	    $partlist[$ctr].'" />'."\n";
                   2229: 	$ctr++;
                   2230:     }
                   2231:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2232: 
1.441     www      2233: # Done with printing info for one student
                   2234: 
                   2235:     $request->print('</td></tr></table></p>');
                   2236: 
                   2237: 
1.41      ng       2238:     # print end of form
                   2239:     if ($counter == $total) {
1.297     www      2240: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2241: 	$endform.='<input type="button" value="Save & Next" '.
                   2242: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2243: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2244: 	my $ntstu ='<select name="NTSTU">'.
                   2245: 	    '<option>1</option><option>2</option>'.
                   2246: 	    '<option>3</option><option>5</option>'.
                   2247: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2248: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2249: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2250: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2251: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2252: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2253: 	    '<input type="button" value="Next" '.
1.417     albertel 2254: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2255: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2256:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2257:             "' name='increment' />";
1.45      ng       2258: 	$endform.='</td><tr></table></form>';
1.324     albertel 2259: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2260: 	$request->print($endform);
                   2261:     }
                   2262:     return '';
1.38      ng       2263: }
                   2264: 
1.44      ng       2265: #--- Retrieve the last submission for all the parts
1.38      ng       2266: sub get_last_submission {
1.119     ng       2267:     my ($returnhash)=@_;
1.46      ng       2268:     my (@string,$timestamp);
1.119     ng       2269:     if ($$returnhash{'version'}) {
1.46      ng       2270: 	my %lasthash=();
                   2271: 	my ($version);
1.119     ng       2272: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2273: 	    foreach my $key (sort(split(/\:/,
                   2274: 					$$returnhash{$version.':keys'}))) {
                   2275: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2276: 		$timestamp = 
                   2277: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2278: 	    }
                   2279: 	}
1.397     albertel 2280: 	foreach my $key (keys(%lasthash)) {
                   2281: 	    next if ($key !~ /\.submission$/);
                   2282: 
                   2283: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2284: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2285: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2286: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2287: 	}
                   2288:     }
1.397     albertel 2289:     if (!@string) {
                   2290: 	$string[0] =
1.398     albertel 2291: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2292:     }
                   2293:     return (\@string,\$timestamp);
1.38      ng       2294: }
1.35      ng       2295: 
1.44      ng       2296: #--- High light keywords, with style choosen by user.
1.38      ng       2297: sub keywords_highlight {
1.44      ng       2298:     my $string    = shift;
1.257     albertel 2299:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2300:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2301:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2302:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2303:     foreach my $keyword (@keylist) {
                   2304: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2305:     }
                   2306:     return $string;
1.38      ng       2307: }
1.36      ng       2308: 
1.44      ng       2309: #--- Called from submission routine
1.38      ng       2310: sub processHandGrade {
1.41      ng       2311:     my ($request) = shift;
1.324     albertel 2312:     my $symb   = &get_symb($request);
                   2313:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2314:     my $button = $env{'form.gradeOpt'};
                   2315:     my $ngrade = $env{'form.NCT'};
                   2316:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2317:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2318:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2319: 
1.44      ng       2320:     if ($button eq 'Save & Next') {
                   2321: 	my $ctr = 0;
                   2322: 	while ($ctr < $ngrade) {
1.257     albertel 2323: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2324: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2325: 	    if ($errorflag eq 'no_score') {
                   2326: 		$ctr++;
                   2327: 		next;
                   2328: 	    }
1.104     albertel 2329: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2330: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2331: 		$ctr++;
                   2332: 		next;
                   2333: 	    }
1.257     albertel 2334: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2335: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2336: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2337:             my ($feedurl,$showsymb) =
                   2338: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2339: 	    my $messagetail;
1.62      albertel 2340: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2341: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2342: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2343: 		$subject.=' ['.$restitle.']';
1.44      ng       2344: 		my (@msgnum) = split(/,/,$includemsg);
                   2345: 		foreach (@msgnum) {
1.257     albertel 2346: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2347: 		}
1.80      ng       2348: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2349: 		if ($env{'form.withgrades'.$ctr}) {
                   2350: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2351: 		    $messagetail = " for <a href=\"".
1.418     albertel 2352: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2353: 		}
                   2354: 		$msgstatus = 
                   2355:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2356: 						     $message.$messagetail,
1.418     albertel 2357:                                                      undef,$feedurl,undef,
1.386     raeburn  2358:                                                      undef,undef,$showsymb,
                   2359:                                                      $restitle);
                   2360: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2361: 				$msgstatus);
1.44      ng       2362: 	    }
1.257     albertel 2363: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2364: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2365: 		foreach my $collabstr (@collabstrs) {
                   2366: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2367: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2368: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2369: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2370: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2371: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2372: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2373: 			    next;
1.418     albertel 2374: 			} elsif ($message ne '') {
                   2375: 			    my ($baseurl,$showsymb) = 
                   2376: 				&get_feedurl_and_symb($symb,$collaborator,
                   2377: 						      $udom);
                   2378: 			    if ($env{'form.withgrades'.$ctr}) {
                   2379: 				$messagetail = " for <a href=\"".
1.386     raeburn  2380:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2381: 			    }
1.418     albertel 2382: 			    $msgstatus = 
                   2383: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2384: 			}
1.44      ng       2385: 		    }
                   2386: 		}
                   2387: 	    }
                   2388: 	    $ctr++;
                   2389: 	}
                   2390:     }
                   2391: 
1.257     albertel 2392:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2393: 	# Keywords sorted in alphabatical order
1.257     albertel 2394: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2395: 	my %keyhash = ();
1.257     albertel 2396: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2397: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2398: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2399: 	$env{'form.keywords'} = join(' ',@keywords);
                   2400: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2401: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2402: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2403: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2404: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2405: 
                   2406: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2407: 	# New messages are saved in env for the next student.
1.119     ng       2408: 	# All messages are saved in nohist_handgrade.db
                   2409: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2410: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2411: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2412: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2413: 		$idx++;
                   2414: 	    }
                   2415: 	    $ctr++;
1.41      ng       2416: 	}
1.119     ng       2417: 	$ctr = 0;
                   2418: 	while ($ctr < $ngrade) {
1.257     albertel 2419: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2420: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2421: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2422: 		$idx++;
                   2423: 	    }
                   2424: 	    $ctr++;
1.41      ng       2425: 	}
1.257     albertel 2426: 	$env{'form.savemsgN'} = --$idx;
                   2427: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2428: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2429: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2430:     }
1.44      ng       2431:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2432:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2433:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2434: 	my ($ctr,$total) = (0,0);
                   2435: 	while ($ctr < $ngrade) {
1.257     albertel 2436: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2437: 	    $ctr++;
                   2438: 	}
1.257     albertel 2439: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2440: 	$ctr = 0;
                   2441: 	while ($ctr < $total) {
1.257     albertel 2442: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2443: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2444: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2445: 	    &submission($request,$ctr,$total-1);
1.41      ng       2446: 	    $ctr++;
                   2447: 	}
                   2448: 	return '';
                   2449:     }
1.36      ng       2450: 
1.121     ng       2451: # Go directly to grade student - from submission or link from chart page
1.120     ng       2452:     if ($button eq 'Grade Student') {
1.324     albertel 2453: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2454: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2455: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2456: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2457: 	&submission($request,0,0);
                   2458: 	return '';
                   2459:     }
                   2460: 
1.44      ng       2461:     # Get the next/previous one or group of students
1.257     albertel 2462:     my $firststu = $env{'form.unamedom0'};
                   2463:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2464:     my $ctr = 2;
1.41      ng       2465:     while ($laststu eq '') {
1.257     albertel 2466: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2467: 	$ctr++;
                   2468: 	$laststu = $firststu if ($ctr > $ngrade);
                   2469:     }
1.44      ng       2470: 
1.41      ng       2471:     my (@parsedlist,@nextlist);
                   2472:     my ($nextflg) = 0;
1.294     albertel 2473:     foreach (sort 
                   2474: 	     {
                   2475: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2476: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2477: 		 }
                   2478: 		 return $a cmp $b;
                   2479: 	     } (keys(%$fullname))) {
1.41      ng       2480: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2481: 	    push @parsedlist,$_;
                   2482: 	}
                   2483: 	$nextflg = 1 if ($_ eq $laststu);
                   2484: 	if ($button eq 'Previous') {
                   2485: 	    last if ($_ eq $firststu);
                   2486: 	    push @parsedlist,$_;
                   2487: 	}
                   2488:     }
                   2489:     $ctr = 0;
                   2490:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2491:     my ($partlist) = &response_type($symb);
1.41      ng       2492:     foreach my $student (@parsedlist) {
1.257     albertel 2493: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2494: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2495: 	
                   2496: 	if ($submitonly eq 'queued') {
                   2497: 	    my %queue_status = 
                   2498: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2499: 							$udom,$uname);
                   2500: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2501: 	}
                   2502: 
1.156     albertel 2503: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2504: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2505: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2506: 	    my $submitted = 0;
1.248     albertel 2507: 	    my $ungraded = 0;
                   2508: 	    my $incorrect = 0;
1.145     albertel 2509: 	    foreach (keys(%status)) {
                   2510: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2511: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2512: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2513: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2514: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2515: 		    $submitted = 0;
                   2516: 		}
1.41      ng       2517: 	    }
1.156     albertel 2518: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2519: 				     $submitonly eq 'incorrect' ||
                   2520: 				     $submitonly eq 'graded'));
1.248     albertel 2521: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2522: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2523: 	}
                   2524: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2525: 	last if ($ctr == $ntstu);
1.41      ng       2526: 	$ctr++;
                   2527:     }
1.36      ng       2528: 
1.41      ng       2529:     $ctr = 0;
                   2530:     my $total = scalar(@nextlist)-1;
1.39      ng       2531: 
1.41      ng       2532:     foreach (sort @nextlist) {
                   2533: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2534: 	$env{'form.student'}  = $uname;
                   2535: 	$env{'form.userdom'}  = $udom;
                   2536: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2537: 	&submission($request,$ctr,$total);
                   2538: 	$ctr++;
                   2539:     }
                   2540:     if ($total < 0) {
1.398     albertel 2541: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2542: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2543: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2544: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2545: 	$request->print($the_end);
                   2546:     }
                   2547:     return '';
1.38      ng       2548: }
1.36      ng       2549: 
1.44      ng       2550: #---- Save the score and award for each student, if changed
1.38      ng       2551: sub saveHandGrade {
1.324     albertel 2552:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2553:     my @version_parts;
1.104     albertel 2554:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2555: 					   $env{'request.course.id'});
1.104     albertel 2556:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2557:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2558:     my @parts_graded;
1.77      ng       2559:     my %newrecord  = ();
                   2560:     my ($pts,$wgt) = ('','');
1.269     raeburn  2561:     my %aggregate = ();
                   2562:     my $aggregateflag = 0;
1.301     albertel 2563:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2564:     foreach my $new_part (@parts) {
1.337     banghart 2565: 	#collaborator ($submi may vary for different parts
1.259     banghart 2566: 	if ($submitter && $new_part ne $part) { next; }
                   2567: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2568: 	if ($dropMenu eq 'excused') {
1.259     banghart 2569: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2570: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2571: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2572: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2573: 		}
1.364     banghart 2574: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2575: 	    }
1.125     ng       2576: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2577: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2578: 	    foreach my $key (keys (%record)) {
1.259     banghart 2579: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2580: 	    }
1.259     banghart 2581: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2582: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2583:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2584: 
                   2585:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2586: 					       [$new_part]);
                   2587:             my $aggtries =$totaltries;
1.269     raeburn  2588:             if ($last_resets{$new_part}) {
1.270     albertel 2589:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2590: 					   $new_part);
1.269     raeburn  2591:             }
1.270     albertel 2592: 
                   2593:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2594:             if ($aggtries > 0) {
1.327     albertel 2595:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2596:                 $aggregateflag = 1;
                   2597:             }
1.125     ng       2598: 	} elsif ($dropMenu eq '') {
1.259     banghart 2599: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2600: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2601: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2602: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2603: 		next;
                   2604: 	    }
1.259     banghart 2605: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2606: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2607: 	    my $partial= $pts/$wgt;
1.259     banghart 2608: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2609: 		#do not update score for part if not changed.
1.346     banghart 2610:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2611: 		next;
1.251     banghart 2612: 	    } else {
1.259     banghart 2613: 	        push @parts_graded, $new_part;
1.153     albertel 2614: 	    }
1.259     banghart 2615: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2616: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2617: 	    }
1.259     banghart 2618: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2619: 	    if ($partial == 0) {
1.153     albertel 2620: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2621: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2622: 		}
1.41      ng       2623: 	    } else {
1.153     albertel 2624: 		if ($record{$reckey} ne 'correct_by_override') {
                   2625: 		    $newrecord{$reckey} = 'correct_by_override';
                   2626: 		}
                   2627: 	    }	    
                   2628: 	    if ($submitter && 
1.259     banghart 2629: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2630: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2631: 	    }
1.259     banghart 2632: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2633: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2634: 	}
1.259     banghart 2635: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2636: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2637: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2638: 	        $dropMenu eq 'reset status')
                   2639: 	   {
1.342     banghart 2640: 	    push (@version_parts,$new_part);
1.259     banghart 2641: 	}
1.41      ng       2642:     }
1.301     albertel 2643:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2644:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2645: 
1.344     albertel 2646:     if (%newrecord) {
                   2647:         if (@version_parts) {
1.364     banghart 2648:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2649:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2650: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2651: 	    foreach my $new_part (@version_parts) {
                   2652: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2653: 				$new_part,\%newrecord);
                   2654: 	    }
1.259     banghart 2655:         }
1.44      ng       2656: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2657: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2658: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2659: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2660:     }
1.269     raeburn  2661:     if ($aggregateflag) {
                   2662:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2663: 			      $cdom,$cnum);
1.269     raeburn  2664:     }
1.301     albertel 2665:     return ('',$pts,$wgt);
1.36      ng       2666: }
1.322     albertel 2667: 
1.380     albertel 2668: sub check_and_remove_from_queue {
                   2669:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2670:     my @ungraded_parts;
                   2671:     foreach my $part (@{$parts}) {
                   2672: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2673: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2674: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2675: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2676: 		) {
                   2677: 	    push(@ungraded_parts, $part);
                   2678: 	}
                   2679:     }
                   2680:     if ( !@ungraded_parts ) {
                   2681: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2682: 					       $cnum,$domain,$stuname);
                   2683:     }
                   2684: }
                   2685: 
1.337     banghart 2686: sub handback_files {
                   2687:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2688:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2689:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2690: 
                   2691:     my @part_response_id = &flatten_responseType($responseType);
                   2692:     foreach my $part_response_id (@part_response_id) {
                   2693:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2694: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2695:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2696:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2697:                 my $file_counter = 1;
1.367     albertel 2698: 		my $file_msg;
1.337     banghart 2699:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2700:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2701:                     my ($directory,$answer_file) = 
                   2702:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2703:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2704: 		        &file_name_version_ext($answer_file);
1.355     banghart 2705: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2706: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2707: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2708:                     # fix file name
                   2709:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2710:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2711:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2712:             	                                $save_file_name);
1.337     banghart 2713:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2714:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2715:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2716:                     } else {
1.360     banghart 2717:                         # mark the file as read only
                   2718:                         my @files = ($save_file_name);
1.372     albertel 2719:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2720:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2721: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2722: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2723: 			}
                   2724:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2725: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2726: 
1.337     banghart 2727:                     }
                   2728:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2729:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2730:                     $file_counter++;
                   2731:                 }
1.367     albertel 2732: 		my $subject = "File Handed Back by Instructor ";
                   2733: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2734: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2735: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2736: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2737: 		my ($feedurl,$showsymb) = 
                   2738: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2739:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2740: 		my $msgstatus = 
                   2741:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2742: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2743:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2744:             }
                   2745:         }
1.338     banghart 2746:     return;
1.337     banghart 2747: }
                   2748: 
1.418     albertel 2749: sub get_feedurl_and_symb {
                   2750:     my ($symb,$uname,$udom) = @_;
                   2751:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2752:     $url = &Apache::lonnet::clutter($url);
                   2753:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2754: 					$symb,$udom,$uname);
                   2755:     if ($encrypturl =~ /^yes$/i) {
                   2756: 	&Apache::lonenc::encrypted(\$url,1);
                   2757: 	&Apache::lonenc::encrypted(\$symb,1);
                   2758:     }
                   2759:     return ($url,$symb);
                   2760: }
                   2761: 
1.313     banghart 2762: sub get_submitted_files {
                   2763:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2764:     my @files;
                   2765:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2766:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2767:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2768:     	    push(@files,$file_url.$file);
                   2769:         }
                   2770:     }
                   2771:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2772:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2773:     }
                   2774:     return (\@files);
                   2775: }
1.322     albertel 2776: 
1.269     raeburn  2777: # ----------- Provides number of tries since last reset.
                   2778: sub get_num_tries {
                   2779:     my ($record,$last_reset,$part) = @_;
                   2780:     my $timestamp = '';
                   2781:     my $num_tries = 0;
                   2782:     if ($$record{'version'}) {
                   2783:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2784:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2785:                 $timestamp = $$record{$version.':timestamp'};
                   2786:                 if ($timestamp > $last_reset) {
                   2787:                     $num_tries ++;
                   2788:                 } else {
                   2789:                     last;
                   2790:                 }
                   2791:             }
                   2792:         }
                   2793:     }
                   2794:     return $num_tries;
                   2795: }
                   2796: 
                   2797: # ----------- Determine decrements required in aggregate totals 
                   2798: sub decrement_aggs {
                   2799:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2800:     my %decrement = (
                   2801:                         attempts => 0,
                   2802:                         users => 0,
                   2803:                         correct => 0
                   2804:                     );
                   2805:     $decrement{'attempts'} = $aggtries;
                   2806:     if ($solvedstatus =~ /^correct/) {
                   2807:         $decrement{'correct'} = 1;
                   2808:     }
                   2809:     if ($aggtries == $totaltries) {
                   2810:         $decrement{'users'} = 1;
                   2811:     }
                   2812:     foreach my $type (keys (%decrement)) {
                   2813:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2814:     }
                   2815:     return;
                   2816: }
                   2817: 
                   2818: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2819: sub get_last_resets {
1.270     albertel 2820:     my ($symb,$courseid,$partids) =@_;
                   2821:     my %last_resets;
1.269     raeburn  2822:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2823:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2824:     my @keys;
                   2825:     foreach my $part (@{$partids}) {
                   2826: 	push(@keys,"$symb\0$part\0resettime");
                   2827:     }
                   2828:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2829: 				     $cdom,$cname);
                   2830:     foreach my $part (@{$partids}) {
                   2831: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2832:     }
1.270     albertel 2833:     return %last_resets;
1.269     raeburn  2834: }
                   2835: 
1.251     banghart 2836: # ----------- Handles creating versions for portfolio files as answers
                   2837: sub version_portfiles {
1.343     banghart 2838:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2839:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2840:     my @returned_keys;
1.255     banghart 2841:     my $parts = join('|', @$parts_graded);
1.359     www      2842:     my $portfolio_root = &propath($domain,$stu_name).
                   2843: 	'/userfiles/portfolio';
1.277     albertel 2844:     foreach my $key (keys(%$record)) {
1.259     banghart 2845:         my $new_portfiles;
1.263     banghart 2846:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2847:             my @versioned_portfiles;
1.367     albertel 2848:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2849:             foreach my $file (@portfiles) {
1.306     banghart 2850:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2851:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2852: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2853: 		    &file_name_version_ext($answer_file);
1.306     banghart 2854:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2855:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2856:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2857:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2858:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2859:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2860:                         [$directory.$new_answer],
1.306     banghart 2861:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2862:                 }
1.252     banghart 2863:             }
1.343     banghart 2864:             $$record{$key} = join(',',@versioned_portfiles);
                   2865:             push(@returned_keys,$key);
1.251     banghart 2866:         }
                   2867:     } 
1.343     banghart 2868:     return (@returned_keys);   
1.305     banghart 2869: }
                   2870: 
1.307     banghart 2871: sub get_next_version {
1.341     banghart 2872:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2873:     my $version;
                   2874:     foreach my $row (@$dir_list) {
                   2875:         my ($file) = split(/\&/,$row,2);
                   2876:         my ($file_name,$file_version,$file_ext) =
                   2877: 	    &file_name_version_ext($file);
                   2878:         if (($file_name eq $answer_name) && 
                   2879: 	    ($file_ext eq $answer_ext)) {
                   2880:                 # gets here if filename and extension match, regardless of version
                   2881:                 if ($file_version ne '') {
                   2882:                 # a versioned file is found  so save it for later
                   2883:                 if ($file_version > $version) {
                   2884: 		    $version = $file_version;
                   2885: 	        }
                   2886:             }
                   2887:         }
                   2888:     } 
                   2889:     $version ++;
                   2890:     return($version);
                   2891: }
                   2892: 
1.305     banghart 2893: sub version_selected_portfile {
1.306     banghart 2894:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2895:     my ($answer_name,$answer_ver,$answer_ext) =
                   2896:         &file_name_version_ext($file_name);
                   2897:     my $new_answer;
                   2898:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2899:     if($env{'form.copy'} eq '-1') {
                   2900:         $new_answer = 'problem getting file';
                   2901:     } else {
                   2902:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2903:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2904:                             $stu_name,$domain,'copy',
                   2905: 		        '/portfolio'.$directory.$new_answer);
                   2906:     }    
                   2907:     return ($new_answer);
1.251     banghart 2908: }
                   2909: 
1.304     albertel 2910: sub file_name_version_ext {
                   2911:     my ($file)=@_;
                   2912:     my @file_parts = split(/\./, $file);
                   2913:     my ($name,$version,$ext);
                   2914:     if (@file_parts > 1) {
                   2915: 	$ext=pop(@file_parts);
                   2916: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2917: 	    $version=pop(@file_parts);
                   2918: 	}
                   2919: 	$name=join('.',@file_parts);
                   2920:     } else {
                   2921: 	$name=join('.',@file_parts);
                   2922:     }
                   2923:     return($name,$version,$ext);
                   2924: }
                   2925: 
1.44      ng       2926: #--------------------------------------------------------------------------------------
                   2927: #
                   2928: #-------------------------- Next few routines handles grading by section or whole class
                   2929: #
                   2930: #--- Javascript to handle grading by section or whole class
1.42      ng       2931: sub viewgrades_js {
                   2932:     my ($request) = shift;
                   2933: 
1.41      ng       2934:     $request->print(<<VIEWJAVASCRIPT);
                   2935: <script type="text/javascript" language="javascript">
1.45      ng       2936:    function writePoint(partid,weight,point) {
1.125     ng       2937: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2938: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2939: 	if (point == "textval") {
1.125     ng       2940: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2941: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2942: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2943: 		var resetbox = false;
                   2944: 		for (var i=0; i<radioButton.length; i++) {
                   2945: 		    if (radioButton[i].checked) {
                   2946: 			textbox.value = i;
                   2947: 			resetbox = true;
                   2948: 		    }
                   2949: 		}
                   2950: 		if (!resetbox) {
                   2951: 		    textbox.value = "";
                   2952: 		}
                   2953: 		return;
                   2954: 	    }
1.109     matthew  2955: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2956: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2957: 				   ") greater than the weight for the part. Accept?");
                   2958: 		if (resp == false) {
                   2959: 		    textbox.value = "";
                   2960: 		    return;
                   2961: 		}
                   2962: 	    }
1.42      ng       2963: 	    for (var i=0; i<radioButton.length; i++) {
                   2964: 		radioButton[i].checked=false;
1.109     matthew  2965: 		if (parseFloat(point) == i) {
1.42      ng       2966: 		    radioButton[i].checked=true;
                   2967: 		}
                   2968: 	    }
1.41      ng       2969: 
1.42      ng       2970: 	} else {
1.125     ng       2971: 	    textbox.value = parseFloat(point);
1.42      ng       2972: 	}
1.41      ng       2973: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2974: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2975: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2976: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2977: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2978: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2979: 	    if (saveval != "correct") {
                   2980: 		scorename.value = point;
1.43      ng       2981: 		if (selname[0].selected != true) {
                   2982: 		    selname[0].selected = true;
                   2983: 		}
1.42      ng       2984: 	    }
                   2985: 	}
1.125     ng       2986: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2987:     }
                   2988: 
                   2989:     function writeRadText(partid,weight) {
1.125     ng       2990: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2991: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2992:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2993: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2994: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2995: 	    for (var i=0; i<radioButton.length; i++) {
                   2996: 		radioButton[i].checked=false;
                   2997: 
                   2998: 	    }
                   2999: 	    textbox.value = "";
                   3000: 
                   3001: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3002: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3003: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3004: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3005: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3006: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3007: 		if ((saveval != "correct") || override) {
1.42      ng       3008: 		    scorename.value = "";
1.125     ng       3009: 		    if (selval[1].selected) {
                   3010: 			selname[1].selected = true;
                   3011: 		    } else {
                   3012: 			selname[2].selected = true;
                   3013: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3014: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3015: 		    }
1.42      ng       3016: 		}
                   3017: 	    }
1.43      ng       3018: 	} else {
                   3019: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3020: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3021: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3022: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3023: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3024: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3025: 		if ((saveval != "correct") || override) {
1.125     ng       3026: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3027: 		    selname[0].selected = true;
                   3028: 		}
                   3029: 	    }
                   3030: 	}	    
1.42      ng       3031:     }
                   3032: 
                   3033:     function changeSelect(partid,user) {
1.125     ng       3034: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3035: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3036: 	var point  = textbox.value;
1.125     ng       3037: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3038: 
1.109     matthew  3039: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3040: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3041: 	    textbox.value = "";
                   3042: 	    return;
                   3043: 	}
1.109     matthew  3044: 	if (parseFloat(point) > parseFloat(weight)) {
                   3045: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3046: 			       ") greater than the weight of the part. Accept?");
                   3047: 	    if (resp == false) {
                   3048: 		textbox.value = "";
                   3049: 		return;
                   3050: 	    }
                   3051: 	}
1.42      ng       3052: 	selval[0].selected = true;
                   3053:     }
                   3054: 
                   3055:     function changeOneScore(partid,user) {
1.125     ng       3056: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3057: 	if (selval[1].selected || selval[2].selected) {
                   3058: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3059: 	    if (selval[2].selected) {
                   3060: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3061: 	    }
1.269     raeburn  3062:         }
1.42      ng       3063:     }
                   3064: 
                   3065:     function resetEntry(numpart) {
                   3066: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3067: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3068: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3069: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3070: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3071: 	    for (var i=0; i<radioButton.length; i++) {
                   3072: 		radioButton[i].checked=false;
                   3073: 
                   3074: 	    }
                   3075: 	    textbox.value = "";
                   3076: 	    selval[0].selected = true;
                   3077: 
                   3078: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3079: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3080: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3081: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3082: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3083: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3084: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3085: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3086: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3087: 		if (saveselval == "excused") {
1.43      ng       3088: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3089: 		} else {
1.43      ng       3090: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3091: 		}
                   3092: 	    }
1.41      ng       3093: 	}
1.42      ng       3094:     }
                   3095: 
1.41      ng       3096: </script>
                   3097: VIEWJAVASCRIPT
1.42      ng       3098: }
                   3099: 
1.44      ng       3100: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3101: sub viewgrades {
                   3102:     my ($request) = shift;
                   3103:     &viewgrades_js($request);
1.41      ng       3104: 
1.324     albertel 3105:     my ($symb) = &get_symb($request);
1.168     albertel 3106:     #need to make sure we have the correct data for later EXT calls, 
                   3107:     #thus invalidate the cache
                   3108:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3109:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3110:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3111:     &Apache::lonnet::clear_EXT_cache_status();
                   3112: 
1.398     albertel 3113:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3114:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3115: 
                   3116:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3117:     $result.=&jscriptNform($symb);
1.41      ng       3118: 
1.44      ng       3119:     #beginning of class grading form
1.442     banghart 3120:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3121:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3122: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3123: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3124: 	&build_section_inputs().
1.257     albertel 3125: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3126: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3127: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3128: 
1.126     ng       3129:     my $sectionClass;
1.430     banghart 3130:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3131:     if ($env{'form.section'} eq 'all') {
1.126     ng       3132: 	$sectionClass='Class </h3>';
1.257     albertel 3133:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3134: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3135:     } else {
1.431     banghart 3136: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3137:     }
1.431     banghart 3138:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3139:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3140: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3141:     #radio buttons/text box for assigning points for a section or class.
                   3142:     #handles different parts of a problem
1.375     albertel 3143:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3144:     my %weight = ();
                   3145:     my $ctsparts = 0;
1.41      ng       3146:     $result.='<table border="0">';
1.45      ng       3147:     my %seen = ();
1.375     albertel 3148:     my @part_response_id = &flatten_responseType($responseType);
                   3149:     foreach my $part_response_id (@part_response_id) {
                   3150:     	my ($partid,$respid) = @{ $part_response_id };
                   3151: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3152: 	next if $seen{$partid};
                   3153: 	$seen{$partid}++;
1.375     albertel 3154: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3155: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3156: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3157: 
1.44      ng       3158: 	$result.='<input type="hidden" name="partid_'.
                   3159: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3160: 	$result.='<input type="hidden" name="weight_'.
                   3161: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3162: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3163: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3164: 	$result.='<table border="0"><tr>';  
1.41      ng       3165: 	my $ctr = 0;
1.42      ng       3166: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3167: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3168: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3169: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3170: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3171: 	    $ctr++;
                   3172: 	}
                   3173: 	$result.='</tr></table>';
1.44      ng       3174: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3175: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3176: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3177: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3178: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3179: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3180: 		$weight{$partid}.')"> '.
1.401     albertel 3181: 	    '<option selected="selected"> </option>'.
1.125     ng       3182: 	    '<option>excused</option>'.
1.265     www      3183: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3184:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3185: 	$ctsparts++;
1.41      ng       3186:     }
1.52      albertel 3187:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3188: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3189:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3190: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3191: 
1.44      ng       3192:     #table listing all the students in a section/class
                   3193:     #header of table
1.126     ng       3194:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3195:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3196: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3197: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3198:     my (@parts) = sort(&getpartlist($symb));
                   3199:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3200:     my @partids = ();
1.41      ng       3201:     foreach my $part (@parts) {
                   3202: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3203: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3204: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3205: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3206:         push(@partids, $partid);
1.324     albertel 3207: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3208: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3209: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3210: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3211: 	    next;
1.207     albertel 3212: 	} else {
                   3213: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3214: 	}
1.53      albertel 3215: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3216: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3217:     }
                   3218:     $result.='</tr>';
1.44      ng       3219: 
1.270     albertel 3220:     my %last_resets = 
                   3221: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3222: 
1.41      ng       3223:     #get info for each student
1.44      ng       3224:     #list all the students - with points and grade status
1.257     albertel 3225:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3226:     my $ctr = 0;
1.294     albertel 3227:     foreach (sort 
                   3228: 	     {
                   3229: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3230: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3231: 		 }
                   3232: 		 return $a cmp $b;
                   3233: 	     } (keys(%$fullname))) {
1.126     ng       3234: 	$ctr++;
1.324     albertel 3235: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3236: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3237:     }
                   3238:     $result.='</table></td></tr></table>';
                   3239:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3240:     $result.='<input type="button" value="Save" '.
1.417     albertel 3241: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3242:     if (scalar(%$fullname) eq 0) {
                   3243: 	my $colspan=3+scalar(@parts);
1.433     banghart 3244: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3245:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3246: 	$result='<span class="LC_warning">'.
                   3247: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3248: 	        $section_display, $stu_status).
1.433     banghart 3249: 	    '</span>';
1.96      albertel 3250:     }
1.324     albertel 3251:     $result.=&show_grading_menu_form($symb);
1.41      ng       3252:     return $result;
                   3253: }
                   3254: 
1.44      ng       3255: #--- call by previous routine to display each student
1.41      ng       3256: sub viewstudentgrade {
1.324     albertel 3257:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3258:     my ($uname,$udom) = split(/:/,$student);
                   3259:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3260:     my %aggregates = (); 
1.233     albertel 3261:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3262: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3263: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3264: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3265: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3266: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3267:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3268:     foreach my $apart (@$parts) {
                   3269: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3270: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3271:         $result.='<td align="center">';
1.269     raeburn  3272:         my ($aggtries,$totaltries);
                   3273:         unless (exists($aggregates{$part})) {
1.270     albertel 3274: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3275: 
                   3276: 	    $aggtries = $totaltries;
1.269     raeburn  3277:             if ($$last_resets{$part}) {  
1.270     albertel 3278:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3279: 					   $part);
                   3280:             }
1.269     raeburn  3281:             $result.='<input type="hidden" name="'.
                   3282:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3283:             $result.='<input type="hidden" name="'.
                   3284:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3285:             $aggregates{$part} = 1;
                   3286:         }
1.41      ng       3287: 	if ($type eq 'awarded') {
1.320     albertel 3288: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3289: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3290: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3291: 	    $result.='<input type="text" name="'.
1.89      albertel 3292: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3293: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3294: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3295: 	} elsif ($type eq 'solved') {
                   3296: 	    my ($status,$foo)=split(/_/,$score,2);
                   3297: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3298: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3299: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3300: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3301: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3302: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3303: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3304: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3305: 	    $result.='<option>reset status</option>';
1.126     ng       3306: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3307: 	} else {
                   3308: 	    $result.='<input type="hidden" name="'.
                   3309: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3310: 		    "\n";
1.233     albertel 3311: 	    $result.='<input type="text" name="'.
1.122     ng       3312: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3313: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3314: 	}
                   3315:     }
                   3316:     $result.='</tr>';
                   3317:     return $result;
1.38      ng       3318: }
                   3319: 
1.44      ng       3320: #--- change scores for all the students in a section/class
                   3321: #    record does not get update if unchanged
1.38      ng       3322: sub editgrades {
1.41      ng       3323:     my ($request) = @_;
                   3324: 
1.324     albertel 3325:     my $symb=&get_symb($request);
1.433     banghart 3326:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3327:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3328:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3329:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3330: 
1.44      ng       3331:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3332:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3333: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3334: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3335: 
                   3336:     my %scoreptr = (
                   3337: 		    'correct'  =>'correct_by_override',
                   3338: 		    'incorrect'=>'incorrect_by_override',
                   3339: 		    'excused'  =>'excused',
                   3340: 		    'ungraded' =>'ungraded_attempted',
                   3341: 		    'nothing'  => '',
                   3342: 		    );
1.257     albertel 3343:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3344: 
1.44      ng       3345:     my (@partid);
                   3346:     my %weight = ();
1.54      albertel 3347:     my %columns = ();
1.44      ng       3348:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3349: 
1.324     albertel 3350:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3351:     my $header;
1.257     albertel 3352:     while ($ctr < $env{'form.totalparts'}) {
                   3353: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3354: 	push @partid,$partid;
1.257     albertel 3355: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3356: 	$ctr++;
1.54      albertel 3357:     }
1.324     albertel 3358:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3359:     foreach my $partid (@partid) {
                   3360: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3361: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3362: 	$columns{$partid}=2;
                   3363: 	foreach my $stores (@parts) {
                   3364: 	    my ($part,$type) = &split_part_type($stores);
                   3365: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3366: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3367: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3368: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3369: 	    $display =~ s/Number of Attempts/Tries/;
                   3370: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3371: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3372: 	    $columns{$partid}+=2;
                   3373: 	}
                   3374:     }
                   3375:     foreach my $partid (@partid) {
1.324     albertel 3376: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3377: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3378: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3379: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3380: 
1.44      ng       3381:     }
                   3382:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3383:     $result .= $header;
1.44      ng       3384:     $result .= '</tr>'."\n";
1.93      albertel 3385:     my $noupdate;
1.126     ng       3386:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3387:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3388: 	my $line;
1.257     albertel 3389: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3390: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3391: 	my %newrecord;
                   3392: 	my $updateflag = 0;
1.281     albertel 3393: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3394: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3395: 	if (!&canmodify($usec)) {
1.126     ng       3396: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3397: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3398: 	    next;
                   3399: 	}
1.269     raeburn  3400:         my %aggregate = ();
                   3401:         my $aggregateflag = 0;
1.281     albertel 3402: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3403: 	foreach (@partid) {
1.257     albertel 3404: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3405: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3406: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3407: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3408: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3409: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3410: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3411: 	    my $score;
                   3412: 	    if ($partial eq '') {
1.257     albertel 3413: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3414: 	    } elsif ($partial > 0) {
                   3415: 		$score = 'correct_by_override';
                   3416: 	    } elsif ($partial == 0) {
                   3417: 		$score = 'incorrect_by_override';
                   3418: 	    }
1.257     albertel 3419: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3420: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3421: 
1.292     albertel 3422: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3423: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3424: 	    if ($dropMenu eq 'reset status' &&
                   3425: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3426: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3427: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3428: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3429: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3430: 		$updateflag = 1;
1.269     raeburn  3431:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3432:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3433:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3434:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3435:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3436:                     $aggregateflag = 1;
                   3437:                 }
1.139     albertel 3438: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3439: 		$updateflag = 1;
                   3440: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3441: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3442: 		$rec_update++;
1.125     ng       3443: 	    }
                   3444: 
1.93      albertel 3445: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3446: 		'<td align="center">'.$awarded.
                   3447: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3448: 
1.54      albertel 3449: 
                   3450: 	    my $partid=$_;
                   3451: 	    foreach my $stores (@parts) {
                   3452: 		my ($part,$type) = &split_part_type($stores);
                   3453: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3454: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3455: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3456: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3457: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3458: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3459: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3460: 		    $updateflag=1;
                   3461: 		}
1.93      albertel 3462: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3463: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3464: 	    }
1.44      ng       3465: 	}
1.93      albertel 3466: 	$line.='</tr>'."\n";
1.301     albertel 3467: 
                   3468: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3469: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3470: 
1.44      ng       3471: 	if ($updateflag) {
                   3472: 	    $count++;
1.257     albertel 3473: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3474: 				    $udom,$uname);
1.301     albertel 3475: 
                   3476: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3477: 					      $cnum,$udom,$uname)) {
                   3478: 		# need to figure out if should be in queue.
                   3479: 		my %record =  
                   3480: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3481: 					     $udom,$uname);
                   3482: 		my $all_graded = 1;
                   3483: 		my $none_graded = 1;
                   3484: 		foreach my $part (@parts) {
                   3485: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3486: 			$all_graded = 0;
                   3487: 		    } else {
                   3488: 			$none_graded = 0;
                   3489: 		    }
                   3490: 		}
                   3491: 
                   3492: 		if ($all_graded || $none_graded) {
                   3493: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3494: 							   $symb,$cdom,$cnum,
                   3495: 							   $udom,$uname);
                   3496: 		}
                   3497: 	    }
                   3498: 
1.126     ng       3499: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3500: 	    $updateCtr++;
1.93      albertel 3501: 	} else {
1.126     ng       3502: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3503: 	    $noupdateCtr++;
1.44      ng       3504: 	}
1.269     raeburn  3505:         if ($aggregateflag) {
                   3506:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3507: 				  $cdom,$cnum);
1.269     raeburn  3508:         }
1.93      albertel 3509:     }
                   3510:     if ($noupdate) {
1.126     ng       3511: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3512: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3513: 	$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       3514:     }
1.72      ng       3515:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3516: 	&show_grading_menu_form ($symb);
1.125     ng       3517:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3518: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3519: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3520:     return $title.$msg.$result;
1.5       albertel 3521: }
1.54      albertel 3522: 
                   3523: sub split_part_type {
                   3524:     my ($partstr) = @_;
                   3525:     my ($temp,@allparts)=split(/_/,$partstr);
                   3526:     my $type=pop(@allparts);
1.439     albertel 3527:     my $part=join('_',@allparts);
1.54      albertel 3528:     return ($part,$type);
                   3529: }
                   3530: 
1.44      ng       3531: #------------- end of section for handling grading by section/class ---------
                   3532: #
                   3533: #----------------------------------------------------------------------------
                   3534: 
1.5       albertel 3535: 
1.44      ng       3536: #----------------------------------------------------------------------------
                   3537: #
                   3538: #-------------------------- Next few routines handles grading by csv upload
                   3539: #
                   3540: #--- Javascript to handle csv upload
1.27      albertel 3541: sub csvupload_javascript_reverse_associate {
1.246     albertel 3542:     my $error1=&mt('You need to specify the username or ID');
                   3543:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3544:   return(<<ENDPICK);
                   3545:   function verify(vf) {
                   3546:     var foundsomething=0;
                   3547:     var founduname=0;
1.243     albertel 3548:     var foundID=0;
1.27      albertel 3549:     for (i=0;i<=vf.nfields.value;i++) {
                   3550:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3551:       if (i==0 && tw!=0) { foundID=1; }
                   3552:       if (i==1 && tw!=0) { founduname=1; }
                   3553:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3554:     }
1.246     albertel 3555:     if (founduname==0 && foundID==0) {
                   3556: 	alert('$error1');
                   3557: 	return;
1.27      albertel 3558:     }
                   3559:     if (foundsomething==0) {
1.246     albertel 3560: 	alert('$error2');
                   3561: 	return;
1.27      albertel 3562:     }
                   3563:     vf.submit();
                   3564:   }
                   3565:   function flip(vf,tf) {
                   3566:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3567:     var i;
                   3568:     for (i=0;i<=vf.nfields.value;i++) {
                   3569:       //can not pick the same destination field for both name and domain
                   3570:       if (((i ==0)||(i ==1)) && 
                   3571:           ((tf==0)||(tf==1)) && 
                   3572:           (i!=tf) &&
                   3573:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3574:         eval('vf.f'+i+'.selectedIndex=0;')
                   3575:       }
                   3576:     }
                   3577:   }
                   3578: ENDPICK
                   3579: }
                   3580: 
                   3581: sub csvupload_javascript_forward_associate {
1.246     albertel 3582:     my $error1=&mt('You need to specify the username or ID');
                   3583:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3584:   return(<<ENDPICK);
                   3585:   function verify(vf) {
                   3586:     var foundsomething=0;
                   3587:     var founduname=0;
1.243     albertel 3588:     var foundID=0;
1.27      albertel 3589:     for (i=0;i<=vf.nfields.value;i++) {
                   3590:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3591:       if (tw==1) { foundID=1; }
                   3592:       if (tw==2) { founduname=1; }
                   3593:       if (tw>3) { foundsomething=1; }
1.27      albertel 3594:     }
1.246     albertel 3595:     if (founduname==0 && foundID==0) {
                   3596: 	alert('$error1');
                   3597: 	return;
1.27      albertel 3598:     }
                   3599:     if (foundsomething==0) {
1.246     albertel 3600: 	alert('$error2');
                   3601: 	return;
1.27      albertel 3602:     }
                   3603:     vf.submit();
                   3604:   }
                   3605:   function flip(vf,tf) {
                   3606:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3607:     var i;
                   3608:     //can not pick the same destination field twice
                   3609:     for (i=0;i<=vf.nfields.value;i++) {
                   3610:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3611:         eval('vf.f'+i+'.selectedIndex=0;')
                   3612:       }
                   3613:     }
                   3614:   }
                   3615: ENDPICK
                   3616: }
                   3617: 
1.26      albertel 3618: sub csvuploadmap_header {
1.324     albertel 3619:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3620:     my $javascript;
1.257     albertel 3621:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3622: 	$javascript=&csvupload_javascript_reverse_associate();
                   3623:     } else {
                   3624: 	$javascript=&csvupload_javascript_forward_associate();
                   3625:     }
1.45      ng       3626: 
1.324     albertel 3627:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3628:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3629:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3630:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3631:     $request->print(<<ENDPICK);
1.26      albertel 3632: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3633: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3634: $result
1.326     albertel 3635: <hr />
1.26      albertel 3636: <h3>Identify fields</h3>
                   3637: Total number of records found in file: $distotal <hr />
                   3638: Enter as many fields as you can. The system will inform you and bring you back
                   3639: to this page if the data selected is insufficient to run your class.<hr />
                   3640: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3641: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3642: <input type="hidden" name="associate"  value="" />
                   3643: <input type="hidden" name="phase"      value="three" />
                   3644: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3645: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3646: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3647: <input type="hidden" name="upfile_associate" 
1.257     albertel 3648:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3649: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3650: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3651: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3652: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3653: <hr />
                   3654: <script type="text/javascript" language="Javascript">
                   3655: $javascript
                   3656: </script>
                   3657: ENDPICK
1.118     ng       3658:     return '';
1.26      albertel 3659: 
                   3660: }
                   3661: 
                   3662: sub csvupload_fields {
1.324     albertel 3663:     my ($symb) = @_;
                   3664:     my (@parts) = &getpartlist($symb);
1.243     albertel 3665:     my @fields=(['ID','Student ID'],
                   3666: 		['username','Student Username'],
                   3667: 		['domain','Student Domain']);
1.324     albertel 3668:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3669:     foreach my $part (sort(@parts)) {
                   3670: 	my @datum;
                   3671: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3672: 	my $name=$part;
                   3673: 	if  (!$display) { $display = $name; }
                   3674: 	@datum=($name,$display);
1.244     albertel 3675: 	if ($name=~/^stores_(.*)_awarded/) {
                   3676: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3677: 	}
1.41      ng       3678: 	push(@fields,\@datum);
                   3679:     }
                   3680:     return (@fields);
1.26      albertel 3681: }
                   3682: 
                   3683: sub csvuploadmap_footer {
1.41      ng       3684:     my ($request,$i,$keyfields) =@_;
                   3685:     $request->print(<<ENDPICK);
1.26      albertel 3686: </table>
                   3687: <input type="hidden" name="nfields" value="$i" />
                   3688: <input type="hidden" name="keyfields" value="$keyfields" />
                   3689: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3690: </form>
                   3691: ENDPICK
                   3692: }
                   3693: 
1.283     albertel 3694: sub checkforfile_js {
1.86      ng       3695:     my $result =<<CSVFORMJS;
                   3696: <script type="text/javascript" language="javascript">
                   3697:     function checkUpload(formname) {
                   3698: 	if (formname.upfile.value == "") {
                   3699: 	    alert("Please use the browse button to select a file from your local directory.");
                   3700: 	    return false;
                   3701: 	}
                   3702: 	formname.submit();
                   3703:     }
                   3704:     </script>
                   3705: CSVFORMJS
1.283     albertel 3706:     return $result;
                   3707: }
                   3708: 
                   3709: sub upcsvScores_form {
                   3710:     my ($request) = shift;
1.324     albertel 3711:     my ($symb)=&get_symb($request);
1.283     albertel 3712:     if (!$symb) {return '';}
                   3713:     my $result=&checkforfile_js();
1.257     albertel 3714:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3715:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3716:     $result.=$table;
1.326     albertel 3717:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3718:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3719:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3720: 	'.</b></td></tr>'."\n";
                   3721:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3722:     my $upload=&mt("Upload Scores");
1.86      ng       3723:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3724:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3725:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3726:     $result.=<<ENDUPFORM;
1.106     albertel 3727: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3728: <input type="hidden" name="symb" value="$symb" />
                   3729: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3730: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3731: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3732: $upfile_select
1.370     www      3733: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3734: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3735: </form>
                   3736: ENDUPFORM
1.370     www      3737:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3738:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3739:     .'</td></tr></table>'."\n";
1.86      ng       3740:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3741:     $result.=&show_grading_menu_form($symb);
1.86      ng       3742:     return $result;
                   3743: }
                   3744: 
                   3745: 
1.26      albertel 3746: sub csvuploadmap {
1.41      ng       3747:     my ($request)= @_;
1.324     albertel 3748:     my ($symb)=&get_symb($request);
1.41      ng       3749:     if (!$symb) {return '';}
1.72      ng       3750: 
1.41      ng       3751:     my $datatoken;
1.257     albertel 3752:     if (!$env{'form.datatoken'}) {
1.41      ng       3753: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3754:     } else {
1.257     albertel 3755: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3756: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3757:     }
1.41      ng       3758:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3759:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3760:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3761:     my ($i,$keyfields);
                   3762:     if (@records) {
1.324     albertel 3763: 	my @fields=&csvupload_fields($symb);
1.45      ng       3764: 
1.257     albertel 3765: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3766: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3767: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3768: 							  \@fields);
                   3769: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3770: 	    chop($keyfields);
                   3771: 	} else {
                   3772: 	    unshift(@fields,['none','']);
                   3773: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3774: 							    \@fields);
1.311     banghart 3775:             foreach my $rec (@records) {
                   3776:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3777:                 if (%temp) {
                   3778:                     $keyfields=join(',',sort(keys(%temp)));
                   3779:                     last;
                   3780:                 }
                   3781:             }
1.41      ng       3782: 	}
                   3783:     }
                   3784:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3785:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3786: 
1.41      ng       3787:     return '';
1.27      albertel 3788: }
                   3789: 
1.246     albertel 3790: sub csvuploadoptions {
1.41      ng       3791:     my ($request)= @_;
1.324     albertel 3792:     my ($symb)=&get_symb($request);
1.257     albertel 3793:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3794:     my $ignore=&mt('Ignore First Line');
                   3795:     $request->print(<<ENDPICK);
                   3796: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3797: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3798: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3799: <!--
1.246     albertel 3800: <p>
                   3801: <label>
                   3802:    <input type="checkbox" name="show_full_results" />
                   3803:    Show a table of all changes
                   3804: </label>
                   3805: </p>
1.302     albertel 3806: -->
1.246     albertel 3807: <p>
                   3808: <label>
                   3809:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3810:    Overwrite any existing score
                   3811: </label>
                   3812: </p>
                   3813: ENDPICK
                   3814:     my %fields=&get_fields();
                   3815:     if (!defined($fields{'domain'})) {
1.257     albertel 3816: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3817: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3818:     }
1.257     albertel 3819:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3820: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3821: 	my $cleankey=$1;
                   3822: 	if ($cleankey eq 'command') { next; }
                   3823: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3824: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3825:     }
                   3826:     # FIXME do a check for any duplicated user ids...
                   3827:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3828:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3829: <hr /></form>'."\n");
1.324     albertel 3830:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3831:     return '';
                   3832: }
                   3833: 
                   3834: sub get_fields {
                   3835:     my %fields;
1.257     albertel 3836:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3837:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3838: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3839: 	    if ($env{'form.f'.$i} ne 'none') {
                   3840: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3841: 	    }
                   3842: 	} else {
1.257     albertel 3843: 	    if ($env{'form.f'.$i} ne 'none') {
                   3844: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3845: 	    }
                   3846: 	}
1.27      albertel 3847:     }
1.246     albertel 3848:     return %fields;
                   3849: }
                   3850: 
                   3851: sub csvuploadassign {
                   3852:     my ($request)= @_;
1.324     albertel 3853:     my ($symb)=&get_symb($request);
1.246     albertel 3854:     if (!$symb) {return '';}
1.345     bowersj2 3855:     my $error_msg = '';
1.246     albertel 3856:     &Apache::loncommon::load_tmp_file($request);
                   3857:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3858:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3859:     my %fields=&get_fields();
1.41      ng       3860:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3861:     my $courseid=$env{'request.course.id'};
1.97      albertel 3862:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3863:     my @notallowed;
1.41      ng       3864:     my @skipped;
                   3865:     my $countdone=0;
                   3866:     foreach my $grade (@gradedata) {
                   3867: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3868: 	my $domain;
                   3869: 	if ($entries{$fields{'domain'}}) {
                   3870: 	    $domain=$entries{$fields{'domain'}};
                   3871: 	} else {
1.257     albertel 3872: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3873: 	}
1.243     albertel 3874: 	$domain=~s/\s//g;
1.41      ng       3875: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3876: 	$username=~s/\s//g;
1.243     albertel 3877: 	if (!$username) {
                   3878: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3879: 	    $id=~s/\s//g;
1.243     albertel 3880: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3881: 	    $username=$ids{$id};
                   3882: 	}
1.41      ng       3883: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3884: 	    my $id=$entries{$fields{'ID'}};
                   3885: 	    $id=~s/\s//g;
                   3886: 	    if ($id) {
                   3887: 		push(@skipped,"$id:$domain");
                   3888: 	    } else {
                   3889: 		push(@skipped,"$username:$domain");
                   3890: 	    }
1.41      ng       3891: 	    next;
                   3892: 	}
1.108     albertel 3893: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3894: 	if (!&canmodify($usec)) {
                   3895: 	    push(@notallowed,"$username:$domain");
                   3896: 	    next;
                   3897: 	}
1.244     albertel 3898: 	my %points;
1.41      ng       3899: 	my %grades;
                   3900: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3901: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3902: 		$dest eq 'domain') { next; }
                   3903: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3904: 	    if ($dest=~/stores_(.*)_points/) {
                   3905: 		my $part=$1;
                   3906: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3907: 					      $symb,$domain,$username);
1.345     bowersj2 3908:                 if ($wgt) {
                   3909:                     $entries{$fields{$dest}}=~s/\s//g;
                   3910:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3911:                     my $award='correct_by_override';
                   3912:                     $grades{"resource.$part.awarded"}=$pcr;
                   3913:                     $grades{"resource.$part.solved"}=$award;
                   3914:                     $points{$part}=1;
                   3915:                 } else {
                   3916:                     $error_msg = "<br />" .
                   3917:                         &mt("Some point values were assigned"
                   3918:                             ." for problems with a weight "
                   3919:                             ."of zero. These values were "
                   3920:                             ."ignored.");
                   3921:                 }
1.244     albertel 3922: 	    } else {
                   3923: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3924: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3925: 		my $store_key=$dest;
                   3926: 		$store_key=~s/^stores/resource/;
                   3927: 		$store_key=~s/_/\./g;
                   3928: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3929: 	    }
1.41      ng       3930: 	}
1.398     albertel 3931: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3932: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3933: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3934: 					   $env{'request.course.id'},
                   3935: 					   $domain,$username);
                   3936: 	if ($result eq 'ok') {
                   3937: 	    $request->print('.');
                   3938: 	} else {
                   3939: 	    $request->print("<p>
1.398     albertel 3940:                               <span class=\"LC_error\">
                   3941:                                  Failed to save student $username:$domain.
                   3942:                                  Message when trying to save was ($result)
                   3943:                               </span>
1.302     albertel 3944:                              </p>" );
                   3945: 	}
1.41      ng       3946: 	$request->rflush();
                   3947: 	$countdone++;
                   3948:     }
1.398     albertel 3949:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3950:     if (@skipped) {
1.398     albertel 3951: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3952: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3953:     }
                   3954:     if (@notallowed) {
1.398     albertel 3955: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3956: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3957:     }
1.106     albertel 3958:     $request->print("<br />\n");
1.324     albertel 3959:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3960:     return $error_msg;
1.26      albertel 3961: }
1.44      ng       3962: #------------- end of section for handling csv file upload ---------
                   3963: #
                   3964: #-------------------------------------------------------------------
                   3965: #
1.122     ng       3966: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3967: #
                   3968: #--- Select a page/sequence and a student to grade
1.68      ng       3969: sub pickStudentPage {
                   3970:     my ($request) = shift;
                   3971: 
                   3972:     $request->print(<<LISTJAVASCRIPT);
                   3973: <script type="text/javascript" language="javascript">
                   3974: 
                   3975: function checkPickOne(formname) {
1.76      ng       3976:     if (radioSelection(formname.student) == null) {
1.68      ng       3977: 	alert("Please select the student you wish to grade.");
                   3978: 	return;
                   3979:     }
1.125     ng       3980:     ptr = pullDownSelection(formname.selectpage);
                   3981:     formname.page.value = formname["page"+ptr].value;
                   3982:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3983:     formname.submit();
                   3984: }
                   3985: 
                   3986: </script>
                   3987: LISTJAVASCRIPT
1.118     ng       3988:     &commonJSfunctions($request);
1.324     albertel 3989:     my ($symb) = &get_symb($request);
1.257     albertel 3990:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3991:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3992:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3993: 
1.398     albertel 3994:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3995: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3996: 
1.80      ng       3997:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3998:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3999:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4000:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4001: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4002: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4003:     my $ctr=0;
1.68      ng       4004:     foreach (@$titles) {
                   4005: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4006: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4007: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4008: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4009: 	$ctr++;
1.68      ng       4010:     }
1.326     albertel 4011:     $result.= '</select>'."<br />\n";
1.70      ng       4012:     $ctr=0;
                   4013:     foreach (@$titles) {
                   4014: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4015: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4016: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4017: 	$ctr++;
                   4018:     }
1.72      ng       4019:     $result.='<input type="hidden" name="page" />'."\n".
                   4020: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4021: 
1.401     albertel 4022:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4023: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4024: 
1.71      ng       4025:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4026: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4027: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4028: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4029:     
                   4030:     $result.=&build_section_inputs();
1.442     banghart 4031:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4032:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4033: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4034: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4035: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4036: 
1.382     albertel 4037:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4038: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4039: 
1.80      ng       4040:     $result.='&nbsp;<input type="button" '.
1.126     ng       4041: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4042: 
1.68      ng       4043:     $request->print($result);
                   4044: 
1.326     albertel 4045:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4046: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4047: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4048: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4049: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4050: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4051: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4052:  
1.76      ng       4053:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4054:     my $ptr = 1;
1.294     albertel 4055:     foreach my $student (sort 
                   4056: 			 {
                   4057: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4058: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4059: 			     }
                   4060: 			     return $a cmp $b;
                   4061: 			 } (keys(%$fullname))) {
1.68      ng       4062: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4063: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4064: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4065: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4066: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4067: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4068: 	$ptr++;
                   4069:     }
1.381     albertel 4070:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4071:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4072:     $studentTable.='<input type="button" '.
                   4073: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4074: 
1.324     albertel 4075:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4076:     $request->print($studentTable);
                   4077: 
                   4078:     return '';
                   4079: }
                   4080: 
                   4081: sub getSymbMap {
1.132     bowersj2 4082:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4083: 
                   4084:     my %symbx = ();
                   4085:     my @titles = ();
1.117     bowersj2 4086:     my $minder = 0;
                   4087: 
                   4088:     # Gather every sequence that has problems.
1.240     albertel 4089:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4090: 					       1,0,1);
1.117     bowersj2 4091:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4092: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4093: 	    my $title = $minder.'.'.
                   4094: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4095: 	    push(@titles, $title); # minder in case two titles are identical
                   4096: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4097: 	    $minder++;
1.241     albertel 4098: 	}
1.68      ng       4099:     }
                   4100:     return \@titles,\%symbx;
                   4101: }
                   4102: 
1.72      ng       4103: #
                   4104: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4105: sub displayPage {
                   4106:     my ($request) = shift;
                   4107: 
1.324     albertel 4108:     my ($symb) = &get_symb($request);
1.257     albertel 4109:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4110:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4111:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4112:     my $pageTitle = $env{'form.page'};
1.103     albertel 4113:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4114:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4115:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4116: 
                   4117:     #need to make sure we have the correct data for later EXT calls, 
                   4118:     #thus invalidate the cache
                   4119:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4120:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4121:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4122:     &Apache::lonnet::clear_EXT_cache_status();
                   4123: 
1.103     albertel 4124:     if (!&canview($usec)) {
1.398     albertel 4125: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4126: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4127: 	return;
                   4128:     }
1.398     albertel 4129:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4130:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4131: 	'</h3>'."\n";
1.382     albertel 4132:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4133: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4134:     } else {
                   4135: 	delete($env{'form.CODE'});
                   4136:     }
1.71      ng       4137:     &sub_page_js($request);
                   4138:     $request->print($result);
                   4139: 
1.132     bowersj2 4140:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4141:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4142:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4143:     if (!$map) {
1.398     albertel 4144: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4145: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4146: 	return; 
                   4147:     }
1.68      ng       4148:     my $iterator = $navmap->getIterator($map->map_start(),
                   4149: 					$map->map_finish());
                   4150: 
1.71      ng       4151:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4152: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4153: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4154: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4155: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4156: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4157: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4158: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4159: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4160: 
1.382     albertel 4161:     if (defined($env{'form.CODE'})) {
                   4162: 	$studentTable.=
                   4163: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4164:     }
1.381     albertel 4165:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4166: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4167: 	'/check.gif" height="16" border="0" />';
                   4168: 
1.118     ng       4169:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4170: 	' symbol.'."\n".
1.71      ng       4171: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4172: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4173: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4174: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4175: 
1.329     albertel 4176:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4177:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4178:     $iterator->next(); # skip the first BEGIN_MAP
                   4179:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4180:     while ($depth > 0) {
1.68      ng       4181:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4182:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4183: 
1.385     albertel 4184:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4185: 	    my $parts = $curRes->parts();
1.68      ng       4186:             my $title = $curRes->compTitle();
1.71      ng       4187: 	    my $symbx = $curRes->symb();
1.196     albertel 4188: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4189: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4190: 	    $studentTable.='<td valign="top">';
1.382     albertel 4191: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4192: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4193: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4194: 					     undef,'both',\%form);
1.71      ng       4195: 	    } else {
1.382     albertel 4196: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4197: 		$companswer =~ s|<form(.*?)>||g;
                   4198: 		$companswer =~ s|</form>||g;
1.71      ng       4199: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4200: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4201: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4202: #		}
1.116     ng       4203: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4204: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4205: 	    }
                   4206: 
1.257     albertel 4207: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4208: 
1.257     albertel 4209: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4210: 		if ($record{'version'} eq '') {
1.398     albertel 4211: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4212: 		} else {
1.116     ng       4213: 		    my %responseType = ();
                   4214: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4215: 			my @responseIds =$curRes->responseIds($partid);
                   4216: 			my @responseType =$curRes->responseType($partid);
                   4217: 			my %responseIds;
                   4218: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4219: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4220: 			}
                   4221: 			$responseType{$partid} = \%responseIds;
1.116     ng       4222: 		    }
1.148     albertel 4223: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4224: 
1.71      ng       4225: 		}
1.257     albertel 4226: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4227: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4228: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4229: 									$env{'request.course.id'},
1.71      ng       4230: 									'','.submission');
                   4231:  
                   4232: 	    }
1.103     albertel 4233: 	    if (&canmodify($usec)) {
                   4234: 		foreach my $partid (@{$parts}) {
                   4235: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4236: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4237: 		    $question++;
                   4238: 		}
1.196     albertel 4239: 		$prob++;
1.71      ng       4240: 	    }
                   4241: 	    $studentTable.='</td></tr>';
1.68      ng       4242: 
1.103     albertel 4243: 	}
1.68      ng       4244:         $curRes = $iterator->next();
                   4245:     }
                   4246: 
1.381     albertel 4247:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4248: 	'<input type="button" value="Save" '.
1.381     albertel 4249: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4250: 	'</form>'."\n";
1.324     albertel 4251:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4252:     $request->print($studentTable);
                   4253: 
                   4254:     return '';
1.119     ng       4255: }
                   4256: 
                   4257: sub displaySubByDates {
1.148     albertel 4258:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4259:     my $isCODE=0;
1.335     albertel 4260:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4261:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4262:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4263: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4264: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4265: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4266: 	'<td><b>Submission</b></td>'.
                   4267: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4268:     my ($version);
                   4269:     my %mark;
1.148     albertel 4270:     my %orders;
1.119     ng       4271:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4272:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4273: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4274:     }
1.335     albertel 4275: 
                   4276:     my $interaction;
1.119     ng       4277:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4278: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4279: 	if (exists($$record{$version.':resource.0.version'})) {
                   4280: 	    $interaction = $$record{$version.':resource.0.version'};
                   4281: 	}
                   4282: 
                   4283: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4284: 		             : "$version:resource");
1.119     ng       4285: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4286: 	if ($isCODE) {
                   4287: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4288: 	}
1.119     ng       4289: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4290: 	my @displaySub = ();
                   4291: 	foreach my $partid (@{$parts}) {
1.335     albertel 4292: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4293: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4294: 	    
                   4295: 
1.122     ng       4296: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4297: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4298: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4299: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4300: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4301: 
                   4302: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4303: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4304: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4305: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4306: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4307: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4308: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4309: 		    } else {
                   4310: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4311: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4312: 		    }
1.335     albertel 4313: 		    my $responseType=($isTask ? 'Task'
                   4314:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4315: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4316: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4317: 			$orders{$partid}->{$responseId}=
                   4318: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4319: 		    }
1.147     albertel 4320: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4321: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4322: 		}
                   4323: 	    }
1.335     albertel 4324: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4325: 		$displaySub[1].='Checked in by '.
                   4326: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4327: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4328: 		    '<br />';
                   4329: 	    }
                   4330: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4331: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4332: 		    lc($$record{"$where.$partid.award"}).' '.
                   4333: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4334: 		    '<br />';
                   4335: 	    }
1.335     albertel 4336: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4337: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4338: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4339: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4340: 		$displaySub[2].=
                   4341: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4342: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4343: 	    }
                   4344: 	}
                   4345: 	# needed because old essay regrader has not parts info
                   4346: 	if (exists $$record{"$version:resource.regrader"}) {
                   4347: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4348: 	}
                   4349: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4350: 	if ($displaySub[2]) {
                   4351: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4352: 	}
1.382     albertel 4353: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4354:     
1.119     ng       4355:     }
                   4356:     $studentTable.='</table></td></tr></table>';
                   4357:     return $studentTable;
1.71      ng       4358: }
                   4359: 
                   4360: sub updateGradeByPage {
                   4361:     my ($request) = shift;
                   4362: 
1.257     albertel 4363:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4364:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4365:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4366:     my $pageTitle = $env{'form.page'};
1.103     albertel 4367:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4368:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4369:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4370:     if (!&canmodify($usec)) {
1.398     albertel 4371: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4372: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4373: 	return;
                   4374:     }
1.398     albertel 4375:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4376:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4377: 	'</h3>'."\n";
1.70      ng       4378: 
1.68      ng       4379:     $request->print($result);
                   4380: 
1.132     bowersj2 4381:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4382:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4383:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4384:     if (!$map) {
1.398     albertel 4385: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4386: 	my ($symb)=&get_symb($request);
                   4387: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4388: 	return; 
                   4389:     }
1.71      ng       4390:     my $iterator = $navmap->getIterator($map->map_start(),
                   4391: 					$map->map_finish());
1.70      ng       4392: 
1.71      ng       4393:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4394: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4395: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4396: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4397: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4398: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4399: 
                   4400:     $iterator->next(); # skip the first BEGIN_MAP
                   4401:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4402:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4403:     while ($depth > 0) {
1.71      ng       4404:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4405:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4406: 
1.385     albertel 4407:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4408: 	    my $parts = $curRes->parts();
1.71      ng       4409:             my $title = $curRes->compTitle();
                   4410: 	    my $symbx = $curRes->symb();
1.196     albertel 4411: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4412: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4413: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4414: 
                   4415: 	    my %newrecord=();
                   4416: 	    my @displayPts=();
1.269     raeburn  4417:             my %aggregate = ();
                   4418:             my $aggregateflag = 0;
1.71      ng       4419: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4420: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4421: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4422: 
1.257     albertel 4423: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4424: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4425: 		my $partial = $newpts/$wgt;
                   4426: 		my $score;
                   4427: 		if ($partial > 0) {
                   4428: 		    $score = 'correct_by_override';
1.125     ng       4429: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4430: 		    $score = 'incorrect_by_override';
                   4431: 		}
1.257     albertel 4432: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4433: 		if ($dropMenu eq 'excused') {
1.71      ng       4434: 		    $partial = '';
                   4435: 		    $score = 'excused';
1.125     ng       4436: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4437: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4438: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4439: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4440: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4441: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4442: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4443: 		    $changeflag++;
                   4444: 		    $newpts = '';
1.269     raeburn  4445:                     
                   4446:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4447:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4448:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4449:                     if ($aggtries > 0) {
                   4450:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4451:                         $aggregateflag = 1;
                   4452:                     }
1.71      ng       4453: 		}
1.324     albertel 4454: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4455: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4456: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4457: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4458: 		    '&nbsp;<br />';
1.207     albertel 4459: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4460: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4461: 		    '&nbsp;<br />';
1.71      ng       4462: 		$question++;
1.380     albertel 4463: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4464: 
1.71      ng       4465: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4466: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4467: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4468: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4469: 
                   4470: 		$changeflag++;
                   4471: 	    }
                   4472: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4473: 		my %record = 
                   4474: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4475: 					     $udom,$uname);
                   4476: 
                   4477: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4478: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4479: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4480: 		    $newrecord{'resource.CODE'} = '';
                   4481: 		}
1.257     albertel 4482: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4483: 					$udom,$uname);
1.382     albertel 4484: 		%record = &Apache::lonnet::restore($symbx,
                   4485: 						   $env{'request.course.id'},
                   4486: 						   $udom,$uname);
1.380     albertel 4487: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4488: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4489: 	    }
1.380     albertel 4490: 	    
1.269     raeburn  4491:             if ($aggregateflag) {
                   4492:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4493:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4494:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4495:             }
1.125     ng       4496: 
1.71      ng       4497: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4498: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4499: 		'</tr>';
1.68      ng       4500: 
1.196     albertel 4501: 	    $prob++;
1.68      ng       4502: 	}
1.71      ng       4503:         $curRes = $iterator->next();
1.68      ng       4504:     }
1.98      albertel 4505: 
1.71      ng       4506:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4507:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4508:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4509: 		  'The scores were changed for '.
                   4510: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4511:     $request->print($grademsg.$studentTable);
1.68      ng       4512: 
1.70      ng       4513:     return '';
                   4514: }
                   4515: 
1.72      ng       4516: #-------- end of section for handling grading by page/sequence ---------
                   4517: #
                   4518: #-------------------------------------------------------------------
                   4519: 
1.75      albertel 4520: #--------------------Scantron Grading-----------------------------------
                   4521: #
                   4522: #------ start of section for handling grading by page/sequence ---------
                   4523: 
1.423     albertel 4524: =pod
                   4525: 
                   4526: =head1 Bubble sheet grading routines
                   4527: 
1.424     albertel 4528:   For this documentation:
                   4529: 
                   4530:    'scanline' refers to the full line of characters
                   4531:    from the file that we are parsing that represents one entire sheet
                   4532: 
                   4533:    'bubble line' refers to the data
                   4534:    representing the line of bubbles that are on the physical bubble sheet
                   4535: 
                   4536: 
                   4537: The overall process is that a scanned in bubble sheet data is uploaded
                   4538: into a course. When a user wants to grade, they select a
                   4539: sequence/folder of resources, a file of bubble sheet info, and pick
                   4540: one of the predefined configurations for what each scanline looks
                   4541: like.
                   4542: 
                   4543: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4544: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4545: because too light bubbling), 'double bubble' (each bubble line should
                   4546: have no more that one letter picked), invalid or duplicated CODE,
                   4547: invalid student ID
                   4548: 
                   4549: If the CODE option is used that determines the randomization of the
                   4550: homework problems, either way the student ID is looked up into a
                   4551: username:domain.
                   4552: 
                   4553: During the validation phase the instructor can choose to skip scanlines. 
                   4554: 
1.435     foxr     4555: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4556: 
                   4557:   scantron_original_filename (unmodified original file)
                   4558:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4559:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4560: 
                   4561: Also there is a separate hash nohist_scantrondata that contains extra
                   4562: correction information that isn't representable in the bubble sheet
                   4563: file (see &scantron_getfile() for more information)
                   4564: 
                   4565: After all scanlines are either valid, marked as valid or skipped, then
                   4566: foreach line foreach problem in the picked sequence, an ssi request is
                   4567: made that simulates a user submitting their selected letter(s) against
                   4568: the homework problem.
1.423     albertel 4569: 
                   4570: =over 4
                   4571: 
                   4572: 
                   4573: 
                   4574: =item defaultFormData
                   4575: 
                   4576:   Returns html hidden inputs used to hold context/default values.
                   4577: 
                   4578:  Arguments:
                   4579:   $symb - $symb of the current resource 
                   4580: 
                   4581: =cut
1.422     foxr     4582: 
1.81      albertel 4583: sub defaultFormData {
1.324     albertel 4584:     my ($symb)=@_;
1.447     foxr     4585:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4586:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4587:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4588: }
                   4589: 
1.447     foxr     4590: 
1.423     albertel 4591: =pod 
                   4592: 
                   4593: =item getSequenceDropDown
                   4594: 
                   4595:    Return html dropdown of possible sequences to grade
                   4596:  
                   4597:  Arguments:
                   4598:    $symb - $symb of the current resource 
                   4599: 
                   4600: =cut
1.422     foxr     4601: 
1.75      albertel 4602: sub getSequenceDropDown {
1.423     albertel 4603:     my ($symb)=@_;
1.75      albertel 4604:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4605:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4606:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4607:     my $ctr=0;
                   4608:     foreach (@$titles) {
                   4609: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4610: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4611: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4612: 	    '>'.$showtitle.'</option>'."\n";
                   4613: 	$ctr++;
                   4614:     }
                   4615:     $result.= '</select>';
                   4616:     return $result;
                   4617: }
                   4618: 
1.423     albertel 4619: 
                   4620: =pod 
                   4621: 
                   4622: =item scantron_filenames
                   4623: 
                   4624:    Returns a list of the scantron files in the current course 
                   4625: 
                   4626: =cut
1.422     foxr     4627: 
1.202     albertel 4628: sub scantron_filenames {
1.257     albertel 4629:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4630:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4631:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4632: 				    &propath($cdom,$cname));
1.202     albertel 4633:     my @possiblenames;
1.201     albertel 4634:     foreach my $filename (sort(@files)) {
1.157     albertel 4635: 	($filename)=split(/&/,$filename);
                   4636: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4637: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4638: 	push(@possiblenames,$filename);
                   4639:     }
                   4640:     return @possiblenames;
                   4641: }
                   4642: 
1.423     albertel 4643: =pod 
                   4644: 
                   4645: =item scantron_uploads
                   4646: 
                   4647:    Returns  html drop-down list of scantron files in current course.
                   4648: 
                   4649:  Arguments:
                   4650:    $file2grade - filename to set as selected in the dropdown
                   4651: 
                   4652: =cut
1.422     foxr     4653: 
1.202     albertel 4654: sub scantron_uploads {
1.209     ng       4655:     my ($file2grade) = @_;
1.202     albertel 4656:     my $result=	'<select name="scantron_selectfile">';
                   4657:     $result.="<option></option>";
                   4658:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4659: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4660:     }
                   4661:     $result.="</select>";
                   4662:     return $result;
                   4663: }
                   4664: 
1.423     albertel 4665: =pod 
                   4666: 
                   4667: =item scantron_scantab
                   4668: 
                   4669:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4670:   file.
                   4671: 
                   4672: =cut
1.422     foxr     4673: 
1.82      albertel 4674: sub scantron_scantab {
                   4675:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4676:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4677:     $result.='<option></option>'."\n";
1.82      albertel 4678:     foreach my $line (<$fh>) {
                   4679: 	my ($name,$descrip)=split(/:/,$line);
                   4680: 	if ($name =~ /^\#/) { next; }
                   4681: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4682:     }
                   4683:     $result.='</select>'."\n";
                   4684: 
                   4685:     return $result;
                   4686: }
                   4687: 
1.423     albertel 4688: =pod 
                   4689: 
                   4690: =item scantron_CODElist
                   4691: 
                   4692:   Returns html drop down of the saved CODE lists from current course,
                   4693:   generated from earlier printings.
                   4694: 
                   4695: =cut
1.422     foxr     4696: 
1.186     albertel 4697: sub scantron_CODElist {
1.257     albertel 4698:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4699:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4700:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4701:     my $namechoice='<option></option>';
1.225     albertel 4702:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4703: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4704: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4705: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4706:     }
                   4707:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4708:     return $namechoice;
                   4709: }
                   4710: 
1.423     albertel 4711: =pod 
                   4712: 
                   4713: =item scantron_CODEunique
                   4714: 
                   4715:   Returns the html for "Each CODE to be used once" radio.
                   4716: 
                   4717: =cut
1.422     foxr     4718: 
1.186     albertel 4719: sub scantron_CODEunique {
1.381     albertel 4720:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4721:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4722:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4723:                 </span>
                   4724:                 <span style="white-space: nowrap;">
1.272     albertel 4725:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4726:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4727:                 </span>';
1.186     albertel 4728:     return $result;
                   4729: }
1.423     albertel 4730: 
                   4731: =pod 
                   4732: 
                   4733: =item scantron_selectphase
                   4734: 
                   4735:   Generates the initial screen to start the bubble sheet process.
                   4736:   Allows for - starting a grading run.
1.424     albertel 4737:              - downloading existing scan data (original, corrected
1.423     albertel 4738:                                                 or skipped info)
                   4739: 
                   4740:              - uploading new scan data
                   4741: 
                   4742:  Arguments:
                   4743:   $r          - The Apache request object
                   4744:   $file2grade - name of the file that contain the scanned data to score
                   4745: 
                   4746: =cut
1.186     albertel 4747: 
1.75      albertel 4748: sub scantron_selectphase {
1.209     ng       4749:     my ($r,$file2grade) = @_;
1.324     albertel 4750:     my ($symb)=&get_symb($r);
1.75      albertel 4751:     if (!$symb) {return '';}
1.423     albertel 4752:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4753:     my $default_form_data=&defaultFormData($symb);
                   4754:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4755:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4756:     my $format_selector=&scantron_scantab();
1.186     albertel 4757:     my $CODE_selector=&scantron_CODElist();
                   4758:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4759:     my $result;
1.422     foxr     4760: 
                   4761:     # Chunk of form to prompt for a file to grade and how:
                   4762: 
1.75      albertel 4763:     $result.= <<SCANTRONFORM;
1.162     albertel 4764:     <table width="100%" border="0">
1.75      albertel 4765:     <tr>
1.226     albertel 4766:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4767:       <td bgcolor="#777777">
1.203     albertel 4768:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4769:         $default_form_data
1.75      albertel 4770:         <table width="100%" border="0">
                   4771:           <tr bgcolor="#e6ffff">
1.174     albertel 4772:             <td colspan="2">
                   4773:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4774:             </td>
                   4775:           </tr>
                   4776:           <tr bgcolor="#ffffe6">
1.174     albertel 4777:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4778:           </tr>
                   4779:           <tr bgcolor="#ffffe6">
1.174     albertel 4780:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4781:           </tr>
1.82      albertel 4782:           <tr bgcolor="#ffffe6">
1.174     albertel 4783:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4784:           </tr>
1.157     albertel 4785:           <tr bgcolor="#ffffe6">
1.186     albertel 4786:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4787:           </tr>
                   4788:           <tr bgcolor="#ffffe6">
                   4789:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4790:           </tr>
                   4791:           <tr bgcolor="#ffffe6">
1.187     albertel 4792: 	    <td> Options: </td>
                   4793:             <td>
1.272     albertel 4794: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4795:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4796:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4797: 	    </td>
                   4798:           </tr>
                   4799:           <tr bgcolor="#ffffe6">
1.174     albertel 4800:             <td colspan="2">
1.265     www      4801:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4802:             </td>
                   4803:           </tr>
                   4804:         </table>
1.226     albertel 4805:        </td>
                   4806:      </form>
1.162     albertel 4807:     </tr>
                   4808: SCANTRONFORM
                   4809:    
                   4810:     $r->print($result);
                   4811: 
1.257     albertel 4812:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4813:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4814: 
1.422     foxr     4815: 	# Chunk of form to prompt for a scantron file upload.
                   4816: 
1.162     albertel 4817:         $r->print(<<SCANTRONFORM);
                   4818:     <tr>
                   4819:       <td bgcolor="#777777">
                   4820:         <table width="100%" border="0">
                   4821:           <tr bgcolor="#e6ffff">
                   4822:             <td>
1.174     albertel 4823:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4824:             </td>
                   4825:           </tr>
                   4826:           <tr bgcolor="#ffffe6">
                   4827:             <td>
                   4828: SCANTRONFORM
1.324     albertel 4829:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4830:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4831:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4832:     $r->print(<<UPLOAD);
                   4833:               <script type="text/javascript" language="javascript">
                   4834:     function checkUpload(formname) {
                   4835: 	if (formname.upfile.value == "") {
                   4836: 	    alert("Please use the browse button to select a file from your local directory.");
                   4837: 	    return false;
                   4838: 	}
                   4839: 	formname.submit();
                   4840:     }
                   4841:               </script>
                   4842: 
                   4843:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4844:                 $default_form_data
                   4845:                 <input name='courseid' type='hidden' value='$cnum' />
                   4846:                 <input name='domainid' type='hidden' value='$cdom' />
                   4847:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4848:                 File to upload:<input type="file" name="upfile" size="50" />
                   4849:                 <br />
                   4850:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4851:               </form>
                   4852: UPLOAD
1.162     albertel 4853: 
                   4854:         $r->print(<<SCANTRONFORM);
                   4855:             </td>
                   4856:           </tr>
1.75      albertel 4857:         </table>
                   4858:       </td>
                   4859:     </tr>
1.162     albertel 4860: SCANTRONFORM
                   4861:     }
1.422     foxr     4862: 
                   4863:     # Chunk of the form that prompts to view a scoring office file,
                   4864:     # corrected file, skipped records in a file.
                   4865: 
1.187     albertel 4866:     $r->print(<<SCANTRONFORM);
                   4867:     <tr>
1.226     albertel 4868:       <form action='/adm/grades' name='scantron_download'>
                   4869:         <td bgcolor="#777777">
1.379     albertel 4870: 	  $default_form_data
1.187     albertel 4871:           <input type="hidden" name="command" value="scantron_download" />
                   4872:           <table width="100%" border="0">
                   4873:             <tr bgcolor="#e6ffff">
                   4874:               <td colspan="2">
                   4875:                 &nbsp;<b>Download a scoring office file</b>
                   4876:               </td>
                   4877:             </tr>
                   4878:             <tr bgcolor="#ffffe6">
                   4879:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4880:             </tr>
                   4881:             <tr bgcolor="#ffffe6">
                   4882:               <td colspan="2">
1.293     www      4883:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4884:               </td>
                   4885:             </tr>
                   4886:           </table>
1.226     albertel 4887:         </td>
                   4888:       </form>
1.187     albertel 4889:     </tr>
                   4890: SCANTRONFORM
1.162     albertel 4891: 
                   4892:     $r->print(<<SCANTRONFORM);
1.75      albertel 4893:   </table>
1.81      albertel 4894: $grading_menu_button
1.75      albertel 4895: SCANTRONFORM
                   4896: 
1.162     albertel 4897:     return
1.75      albertel 4898: }
                   4899: 
1.423     albertel 4900: =pod
                   4901: 
                   4902: =item get_scantron_config
                   4903: 
                   4904:    Parse and return the scantron configuration line selected as a
                   4905:    hash of configuration file fields.
                   4906: 
                   4907:  Arguments:
                   4908:     which - the name of the configuration to parse from the file.
                   4909: 
                   4910: 
                   4911:  Returns:
                   4912:             If the named configuration is not in the file, an empty
                   4913:             hash is returned.
                   4914:     a hash with the fields
                   4915:       name         - internal name for the this configuration setup
                   4916:       description  - text to display to operator that describes this config
                   4917:       CODElocation - if 0 or the string 'none'
                   4918:                           - no CODE exists for this config
                   4919:                      if -1 || the string 'letter'
                   4920:                           - a CODE exists for this config and is
                   4921:                             a string of letters
                   4922:                      Unsupported value (but planned for future support)
                   4923:                           if a positive integer
                   4924:                                - The CODE exists as the first n items from
                   4925:                                  the question section of the form
                   4926:                           if the string 'number'
                   4927:                                - The CODE exists for this config and is
                   4928:                                  a string of numbers
                   4929:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4930:                      the CODE starts
                   4931:       CODElength  - length of the CODE
                   4932:       IDstart     - column where the student ID number starts
                   4933:       IDlength    - length of the student ID info
                   4934:       Qstart      - column where the information from the bubbled
                   4935:                     'questions' start
                   4936:       Qlength     - number of columns comprising a single bubble line from
                   4937:                     the sheet. (usually either 1 or 10)
1.424     albertel 4938:       Qon         - either a single character representing the character used
1.423     albertel 4939:                     to signal a bubble was chosen in the positional setup, or
                   4940:                     the string 'letter' if the letter of the chosen bubble is
                   4941:                     in the final, or 'number' if a number representing the
                   4942:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4943:       Qoff        - the character used to represent that a bubble was
                   4944:                     left blank
1.423     albertel 4945:       PaperID     - if the scanning process generates a unique number for each
                   4946:                     sheet scanned the column that this ID number starts in
                   4947:       PaperIDlength - number of columns that comprise the unique ID number
                   4948:                       for the sheet of paper
1.424     albertel 4949:       FirstName   - column that the first name starts in
1.423     albertel 4950:       FirstNameLength - number of columns that the first name spans
                   4951:  
                   4952:       LastName    - column that the last name starts in
                   4953:       LastNameLength - number of columns that the last name spans
                   4954: 
                   4955: =cut
1.422     foxr     4956: 
1.82      albertel 4957: sub get_scantron_config {
                   4958:     my ($which) = @_;
                   4959:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4960:     my %config;
1.157     albertel 4961:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4962:     foreach my $line (<$fh>) {
                   4963: 	my ($name,$descrip)=split(/:/,$line);
                   4964: 	if ($name ne $which ) { next; }
                   4965: 	chomp($line);
                   4966: 	my @config=split(/:/,$line);
                   4967: 	$config{'name'}=$config[0];
                   4968: 	$config{'description'}=$config[1];
                   4969: 	$config{'CODElocation'}=$config[2];
                   4970: 	$config{'CODEstart'}=$config[3];
                   4971: 	$config{'CODElength'}=$config[4];
                   4972: 	$config{'IDstart'}=$config[5];
                   4973: 	$config{'IDlength'}=$config[6];
                   4974: 	$config{'Qstart'}=$config[7];
                   4975: 	$config{'Qlength'}=$config[8];
                   4976: 	$config{'Qoff'}=$config[9];
                   4977: 	$config{'Qon'}=$config[10];
1.157     albertel 4978: 	$config{'PaperID'}=$config[11];
                   4979: 	$config{'PaperIDlength'}=$config[12];
                   4980: 	$config{'FirstName'}=$config[13];
                   4981: 	$config{'FirstNamelength'}=$config[14];
                   4982: 	$config{'LastName'}=$config[15];
                   4983: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4984: 	last;
                   4985:     }
                   4986:     return %config;
                   4987: }
                   4988: 
1.423     albertel 4989: =pod 
                   4990: 
                   4991: =item username_to_idmap
                   4992: 
                   4993:     creates a hash keyed by student id with values of the corresponding
                   4994:     student username:domain.
                   4995: 
                   4996:   Arguments:
                   4997: 
                   4998:     $classlist - reference to the class list hash. This is a hash
                   4999:                  keyed by student name:domain  whose elements are references
1.424     albertel 5000:                  to arrays containing various chunks of information
1.423     albertel 5001:                  about the student. (See loncoursedata for more info).
                   5002: 
                   5003:   Returns
                   5004:     %idmap - the constructed hash
                   5005: 
                   5006: =cut
                   5007: 
1.82      albertel 5008: sub username_to_idmap {
                   5009:     my ($classlist)= @_;
                   5010:     my %idmap;
                   5011:     foreach my $student (keys(%$classlist)) {
                   5012: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5013: 	    $student;
                   5014:     }
                   5015:     return %idmap;
                   5016: }
1.423     albertel 5017: 
                   5018: =pod
                   5019: 
1.424     albertel 5020: =item scantron_fixup_scanline
1.423     albertel 5021: 
                   5022:    Process a requested correction to a scanline.
                   5023: 
                   5024:   Arguments:
                   5025:     $scantron_config   - hash from &get_scantron_config()
                   5026:     $scan_data         - hash of correction information 
                   5027:                           (see &scantron_getfile())
                   5028:     $line              - existing scanline
                   5029:     $whichline         - line number of the passed in scanline
                   5030:     $field             - type of change to process 
                   5031:                          (either 
                   5032:                           'ID'     -> correct the student ID number
                   5033:                           'CODE'   -> correct the CODE
                   5034:                           'answer' -> fixup the submitted answers)
                   5035:     
                   5036:    $args               - hash of additional info,
                   5037:                           - 'ID' 
                   5038:                                'newid' -> studentID to use in replacement
1.424     albertel 5039:                                           of existing one
1.423     albertel 5040:                           - 'CODE' 
                   5041:                                'CODE_ignore_dup' - set to true if duplicates
                   5042:                                                    should be ignored.
                   5043: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5044:                                         if the existing unfound code should
1.423     albertel 5045:                                         be used as is
                   5046:                           - 'answer'
                   5047:                                'response' - new answer or 'none' if blank
                   5048:                                'question' - the bubble line to change
                   5049: 
                   5050:   Returns:
                   5051:     $line - the modified scanline
                   5052: 
                   5053:   Side effects: 
                   5054:     $scan_data - may be updated
                   5055: 
                   5056: =cut
                   5057: 
1.82      albertel 5058: 
1.157     albertel 5059: sub scantron_fixup_scanline {
                   5060:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5061: 
1.157     albertel 5062:     if ($field eq 'ID') {
                   5063: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5064: 	    return ($line,1,'New value too large');
1.157     albertel 5065: 	}
                   5066: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5067: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5068: 				     $args->{'newid'});
                   5069: 	}
                   5070: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5071: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5072: 	if ($args->{'newid'}=~/^\s*$/) {
                   5073: 	    &scan_data($scan_data,"$whichline.user",
                   5074: 		       $args->{'username'}.':'.$args->{'domain'});
                   5075: 	}
1.186     albertel 5076:     } elsif ($field eq 'CODE') {
1.192     albertel 5077: 	if ($args->{'CODE_ignore_dup'}) {
                   5078: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5079: 	}
                   5080: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5081: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5082: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5083: 		return ($line,1,'New CODE value too large');
                   5084: 	    }
                   5085: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5086: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5087: 	    }
                   5088: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5089: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5090: 	}
1.157     albertel 5091:     } elsif ($field eq 'answer') {
                   5092: 	my $length=$scantron_config->{'Qlength'};
                   5093: 	my $off=$scantron_config->{'Qoff'};
                   5094: 	my $on=$scantron_config->{'Qon'};
                   5095: 	my $answer=${off}x$length;
                   5096: 	if ($args->{'response'} eq 'none') {
                   5097: 	    &scan_data($scan_data,
                   5098: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5099: 	} else {
1.274     albertel 5100: 	    if ($on eq 'letter') {
                   5101: 		my @alphabet=('A'..'Z');
                   5102: 		$answer=$alphabet[$args->{'response'}];
                   5103: 	    } elsif ($on eq 'number') {
                   5104: 		$answer=$args->{'response'}+1;
1.389     albertel 5105: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5106: 	    } else {
                   5107: 		substr($answer,$args->{'response'},1)=$on;
                   5108: 	    }
1.157     albertel 5109: 	    &scan_data($scan_data,
                   5110: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5111: 	}
                   5112: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5113: 	substr($line,$where-1,$length)=$answer;
                   5114:     }
                   5115:     return $line;
                   5116: }
1.423     albertel 5117: 
                   5118: =pod
                   5119: 
                   5120: =item scan_data
                   5121: 
                   5122:     Edit or look up  an item in the scan_data hash.
                   5123: 
                   5124:   Arguments:
                   5125:     $scan_data  - The hash (see scantron_getfile)
                   5126:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5127:                   scantronfilename_key).
1.423     albertel 5128:     $data        - New value of the hash entry.
                   5129:     $delete      - If true, the entry is removed from the hash.
                   5130: 
                   5131:   Returns:
                   5132:     The new value of the hash table field (undefined if deleted).
                   5133: 
                   5134: =cut
                   5135: 
                   5136: 
1.157     albertel 5137: sub scan_data {
                   5138:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5139:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5140:     if (defined($value)) {
                   5141: 	$scan_data->{$filename.'_'.$key} = $value;
                   5142:     }
                   5143:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5144:     return $scan_data->{$filename.'_'.$key};
                   5145: }
1.423     albertel 5146: 
                   5147: =pod 
                   5148: 
                   5149: =item scantron_parse_scanline
                   5150: 
                   5151:   Decodes a scanline from the selected scantron file
                   5152: 
                   5153:  Arguments:
                   5154:     line             - The text of the scantron file line to process
                   5155:     whichline        - Line number
                   5156:     scantron_config  - Hash describing the format of the scantron lines.
                   5157:     scan_data        - Hash of extra information about the scanline
                   5158:                        (see scantron_getfile for more information)
                   5159:     just_header      - True if should not process question answers but only
                   5160:                        the stuff to the left of the answers.
                   5161:  Returns:
                   5162:    Hash containing the result of parsing the scanline
                   5163: 
                   5164:    Keys are all proceeded by the string 'scantron.'
                   5165: 
                   5166:        CODE    - the CODE in use for this scanline
                   5167:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5168:                  by the operator
                   5169:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5170:                             CODEs were selected, but the usage has been
                   5171:                             forced by the operator
                   5172:        ID  - student ID
                   5173:        PaperID - if used, the ID number printed on the sheet when the 
                   5174:                  paper was scanned
                   5175:        FirstName - first name from the sheet
                   5176:        LastName  - last name from the sheet
                   5177: 
                   5178:      if just_header was not true these key may also exist
                   5179: 
1.447     foxr     5180:        missingerror - a list of bubble ranges that are considered to be answers
                   5181:                       to a single question that don't have any bubbles filled in.
                   5182:                       Of the form questionnumber:firstbubblenumber:count.
                   5183:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5184:                       to a single question that have more than one bubble filled in.
                   5185:                       Of the form questionnumber::firstbubblenumber:count
                   5186:    
                   5187:                 In the above, count is the number of bubble responses in the
                   5188:                 input line needed to represent the possible answers to the question.
                   5189:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5190:                 per line would have count = 2.
                   5191: 
1.423     albertel 5192:        maxquest     - the number of the last bubble line that was parsed
                   5193: 
                   5194:        (<number> starts at 1)
                   5195:        <number>.answer - zero or more letters representing the selected
                   5196:                          letters from the scanline for the bubble line 
                   5197:                          <number>.
                   5198:                          if blank there was either no bubble or there where
                   5199:                          multiple bubbles, (consult the keys missingerror and
                   5200:                          doubleerror if this is an error condition)
                   5201: 
                   5202: =cut
                   5203: 
1.82      albertel 5204: sub scantron_parse_scanline {
1.423     albertel 5205:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5206:     my %record;
1.422     foxr     5207:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5208:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5209:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5210: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5211: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5212: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5213: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5214: 	    $record{'scantron.CODE'}=substr($data,
                   5215: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5216: 					    $$scantron_config{'CODElength'});
1.191     albertel 5217: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5218: 		$record{'scantron.useCODE'}=1;
                   5219: 	    }
1.192     albertel 5220: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5221: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5222: 	    }
1.82      albertel 5223: 	} else {
                   5224: 	    #FIXME interpret first N questions
                   5225: 	}
                   5226:     }
1.83      albertel 5227:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5228: 				  $$scantron_config{'IDlength'});
1.157     albertel 5229:     $record{'scantron.PaperID'}=
                   5230: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5231: 	       $$scantron_config{'PaperIDlength'});
                   5232:     $record{'scantron.FirstName'}=
                   5233: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5234: 	       $$scantron_config{'FirstNamelength'});
                   5235:     $record{'scantron.LastName'}=
                   5236: 	substr($data,$$scantron_config{'LastName'}-1,
                   5237: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5238:     if ($just_header) { return \%record; }
1.194     albertel 5239: 
1.82      albertel 5240:     my @alphabet=('A'..'Z');
                   5241:     my $questnum=0;
1.447     foxr     5242:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5243: 
1.82      albertel 5244:     while ($questions) {
1.447     foxr     5245: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5246: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5247: 
                   5248: 
                   5249: 
1.82      albertel 5250: 	$questnum++;
1.447     foxr     5251: 	my $currentquest = substr($questions,0,$answer_length);
                   5252: 	$questions       = substr($questions,0,$answer_length)='';
                   5253: 	if (length($currentquest) < $answer_length) { next; }
                   5254: 
                   5255: 	# Qon letter implies for each slot in currentquest we have:
                   5256: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5257:         #    about anything else (esp. a value of Qoff for missing
                   5258: 	#    bubbles.
                   5259: 
                   5260: 
1.239     albertel 5261: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5262: 
                   5263: 	    if ($currentquest =~ /\?/
                   5264: 		|| $currentquest =~ /\*/
                   5265: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5266: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5267: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5268: 		    $record{"scantron.$ansnum.answer"}='';
                   5269: 		    $ansnum++;
                   5270: 		}
                   5271: 
1.389     albertel 5272: 	    } elsif (!defined($currentquest)
1.447     foxr     5273: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5274: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5275: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5276: 		    $record{"scantron.$ansnum.answer"}='';
                   5277: 		    $ansnum++;
                   5278: 
                   5279: 		}
1.239     albertel 5280: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5281: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5282: 		    $ansnum += $answers_needed;
1.239     albertel 5283: 		}
1.447     foxr     5284: 
1.239     albertel 5285: 	    } else {
1.447     foxr     5286: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5287: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5288: 		    $ansnum++;
                   5289: 		}
1.239     albertel 5290: 	    }
1.447     foxr     5291: 
                   5292: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5293: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5294:         #    and *? for double bubbles on a line.
                   5295: 	#    these answers are also stored as letters.
                   5296: 
1.239     albertel 5297: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5298: 	    if ($currentquest =~ /\?/
                   5299: 		|| $currentquest =~ /\*/
                   5300: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5301: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5302: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5303: 		    $record{"scantron.$ansnum.answer"}='';
                   5304: 		    $ansnum++;
                   5305: 		}
                   5306: 
1.389     albertel 5307: 	    } elsif (!defined($currentquest)
1.447     foxr     5308: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5309: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5310: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5311: 		    $record{"scantron.$ansnum.answer"}='';
                   5312: 		    $ansnum++;
                   5313: 
                   5314: 		}
1.239     albertel 5315: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5316: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5317: 		    $ansnum += $answers_needed;
1.239     albertel 5318: 		}
1.447     foxr     5319: 
1.239     albertel 5320: 	    } else {
1.447     foxr     5321: 		$currentquest = &digits_to_letters($currentquest);
                   5322: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5323: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5324: 		    $ansnum++;
1.371     albertel 5325: 		}
1.239     albertel 5326: 	    }
1.82      albertel 5327: 	} else {
1.447     foxr     5328: 
                   5329: 	    # Otherwise there's a positional notation;
                   5330: 	    # each bubble line requires Qlength items, and there are filled in
                   5331: 	    # bubbles for each case where there 'Qon' characters.
                   5332: 	    #
                   5333: 
1.239     albertel 5334: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5335: 
                   5336: 	    # If the split only  giveas us one element.. the full length of the
                   5337: 	    # answser string, no bubbles are filled in:
                   5338: 
                   5339: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5340: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5341: 		    $record{"scantron.$ansnum.answer"}='';
                   5342: 		    $ansnum++;
                   5343: 
                   5344: 		}
1.239     albertel 5345: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5346: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5347: 		}
1.447     foxr     5348: 	    } elsif (scalar(@array) lt 2) {
                   5349: 
                   5350: 		my $location      = [length($array[0])];
                   5351: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5352: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5353: 
                   5354: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5355: 		    if ($ans eq $line_num) {
                   5356: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5357: 		    } else {
                   5358: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5359: 		    }
                   5360: 		    $ansnum++;
                   5361: 		}
1.239     albertel 5362: 	    }
1.447     foxr     5363: 	    #  If there's more than one instance of a bubble character
                   5364: 	    #  That's a double bubble; with positional notation we can
                   5365: 	    #  record all the bubbles filled in as well as the 
                   5366: 	    #  fact this response consists of multiple bubbles.
                   5367: 	    #
                   5368: 	    else {
1.239     albertel 5369: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5370: 
                   5371: 		my $first_answer = $ansnum;
                   5372: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5373: 		    $record{"scantron.$ansnum.answer"} = '';
                   5374: 		    $ans++;
                   5375: 		}
                   5376: 
1.239     albertel 5377: 		my @ans=@array;
                   5378: 		my $i=length($ans[0]);shift(@ans);
                   5379: 		while ($#ans) {
                   5380: 		    $i+=length($ans[0])+1;
1.447     foxr     5381: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5382: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5383: 
                   5384: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5385: 		    shift(@ans);
                   5386: 		}
                   5387: 	    }
1.82      albertel 5388: 	}
                   5389:     }
1.83      albertel 5390:     $record{'scantron.maxquest'}=$questnum;
                   5391:     return \%record;
1.82      albertel 5392: }
                   5393: 
1.423     albertel 5394: =pod
                   5395: 
                   5396: =item scantron_add_delay
                   5397: 
                   5398:    Adds an error message that occurred during the grading phase to a
                   5399:    queue of messages to be shown after grading pass is complete
                   5400: 
                   5401:  Arguments:
1.424     albertel 5402:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5403:    $scanline    - the scanline that caused the error
                   5404:    $errormesage - the error message
                   5405:    $errorcode   - a numeric code for the error
                   5406: 
                   5407:  Side Effects:
1.424     albertel 5408:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5409: 
                   5410: =cut
                   5411: 
1.82      albertel 5412: sub scantron_add_delay {
1.140     albertel 5413:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5414:     push(@$delayqueue,
                   5415: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5416: 	  'ecode' => $errorcode }
                   5417: 	 );
1.82      albertel 5418: }
                   5419: 
1.423     albertel 5420: =pod
                   5421: 
                   5422: =item scantron_find_student
                   5423: 
1.424     albertel 5424:    Finds the username for the current scanline
                   5425: 
                   5426:   Arguments:
                   5427:    $scantron_record - hash result from scantron_parse_scanline
                   5428:    $scan_data       - hash of correction information 
                   5429:                       (see &scantron_getfile() form more information)
                   5430:    $idmap           - hash from &username_to_idmap()
                   5431:    $line            - number of current scanline
                   5432:  
                   5433:   Returns:
                   5434:    Either 'username:domain' or undef if unknown
                   5435: 
1.423     albertel 5436: =cut
                   5437: 
1.82      albertel 5438: sub scantron_find_student {
1.157     albertel 5439:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5440:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5441:     if ($scanID =~ /^\s*$/) {
                   5442:  	return &scan_data($scan_data,"$line.user");
                   5443:     }
1.83      albertel 5444:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5445:  	if (lc($id) eq lc($scanID)) {
                   5446:  	    return $$idmap{$id};
                   5447:  	}
1.83      albertel 5448:     }
                   5449:     return undef;
                   5450: }
                   5451: 
1.423     albertel 5452: =pod
                   5453: 
                   5454: =item scantron_filter
                   5455: 
1.424     albertel 5456:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5457:    hidden resources was selected
                   5458: 
1.423     albertel 5459: =cut
                   5460: 
1.83      albertel 5461: sub scantron_filter {
                   5462:     my ($curres)=@_;
1.331     albertel 5463: 
                   5464:     if (ref($curres) && $curres->is_problem()) {
                   5465: 	# if the user has asked to not have either hidden
                   5466: 	# or 'randomout' controlled resources to be graded
                   5467: 	# don't include them
                   5468: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5469: 	    && $curres->randomout) {
                   5470: 	    return 0;
                   5471: 	}
1.83      albertel 5472: 	return 1;
                   5473:     }
                   5474:     return 0;
1.82      albertel 5475: }
                   5476: 
1.423     albertel 5477: =pod
                   5478: 
                   5479: =item scantron_process_corrections
                   5480: 
1.424     albertel 5481:    Gets correction information out of submitted form data and corrects
                   5482:    the scanline
                   5483: 
1.423     albertel 5484: =cut
                   5485: 
1.157     albertel 5486: sub scantron_process_corrections {
                   5487:     my ($r) = @_;
1.257     albertel 5488:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5489:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5490:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5491:     my $which=$env{'form.scantron_line'};
1.200     albertel 5492:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5493:     my ($skip,$err,$errmsg);
1.257     albertel 5494:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5495: 	$skip=1;
1.257     albertel 5496:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5497: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5498: 	    $env{'form.scantron_domain'};
1.157     albertel 5499: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5500: 	($line,$err,$errmsg)=
                   5501: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5502: 				     'ID',{'newid'=>$newid,
1.257     albertel 5503: 				    'username'=>$env{'form.scantron_username'},
                   5504: 				    'domain'=>$env{'form.scantron_domain'}});
                   5505:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5506: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5507: 	my $newCODE;
1.192     albertel 5508: 	my %args;
1.190     albertel 5509: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5510: 	    $newCODE='use_unfound';
1.190     albertel 5511: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5512: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5513: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5514: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5515: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5516: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5517: 	}
1.257     albertel 5518: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5519: 	    $args{'CODE_ignore_dup'}=1;
                   5520: 	}
                   5521: 	$args{'CODE'}=$newCODE;
1.186     albertel 5522: 	($line,$err,$errmsg)=
                   5523: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5524: 				     'CODE',\%args);
1.257     albertel 5525:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5526: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5527: 	    ($line,$err,$errmsg)=
                   5528: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5529: 					 $which,'answer',
                   5530: 					 { 'question'=>$question,
1.257     albertel 5531: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5532: 	    if ($err) { last; }
                   5533: 	}
                   5534:     }
                   5535:     if ($err) {
1.398     albertel 5536: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5537:     } else {
1.200     albertel 5538: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5539: 	&scantron_putfile($scanlines,$scan_data);
                   5540:     }
                   5541: }
                   5542: 
1.423     albertel 5543: =pod
                   5544: 
                   5545: =item reset_skipping_status
                   5546: 
1.424     albertel 5547:    Forgets the current set of remember skipped scanlines (and thus
                   5548:    reverts back to considering all lines in the
                   5549:    scantron_skipped_<filename> file)
                   5550: 
1.423     albertel 5551: =cut
                   5552: 
1.200     albertel 5553: sub reset_skipping_status {
                   5554:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5555:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5556:     &scantron_putfile(undef,$scan_data);
                   5557: }
                   5558: 
1.423     albertel 5559: =pod
                   5560: 
                   5561: =item start_skipping
                   5562: 
1.424     albertel 5563:    Marks a scanline to be skipped. 
                   5564: 
1.423     albertel 5565: =cut
                   5566: 
1.376     albertel 5567: sub start_skipping {
1.200     albertel 5568:     my ($scan_data,$i)=@_;
                   5569:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5570:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5571: 	$remembered{$i}=2;
                   5572:     } else {
                   5573: 	$remembered{$i}=1;
                   5574:     }
1.200     albertel 5575:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5576: }
                   5577: 
1.423     albertel 5578: =pod
                   5579: 
                   5580: =item should_be_skipped
                   5581: 
1.424     albertel 5582:    Checks whether a scanline should be skipped.
                   5583: 
1.423     albertel 5584: =cut
                   5585: 
1.200     albertel 5586: sub should_be_skipped {
1.376     albertel 5587:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5588:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5589: 	# not redoing old skips
1.376     albertel 5590: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5591: 	return 0;
                   5592:     }
                   5593:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5594: 
                   5595:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5596: 	return 0;
                   5597:     }
1.200     albertel 5598:     return 1;
                   5599: }
                   5600: 
1.423     albertel 5601: =pod
                   5602: 
                   5603: =item remember_current_skipped
                   5604: 
1.424     albertel 5605:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5606:    file and remembers them into scan_data for later use.
                   5607: 
1.423     albertel 5608: =cut
                   5609: 
1.200     albertel 5610: sub remember_current_skipped {
                   5611:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5612:     my %to_remember;
                   5613:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5614: 	if ($scanlines->{'skipped'}[$i]) {
                   5615: 	    $to_remember{$i}=1;
                   5616: 	}
                   5617:     }
1.376     albertel 5618: 
1.200     albertel 5619:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5620:     &scantron_putfile(undef,$scan_data);
                   5621: }
                   5622: 
1.423     albertel 5623: =pod
                   5624: 
                   5625: =item check_for_error
                   5626: 
1.424     albertel 5627:     Checks if there was an error when attempting to remove a specific
                   5628:     scantron_.. bubble sheet data file. Prints out an error if
                   5629:     something went wrong.
                   5630: 
1.423     albertel 5631: =cut
                   5632: 
1.200     albertel 5633: sub check_for_error {
                   5634:     my ($r,$result)=@_;
                   5635:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5636: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5637:     }
                   5638: }
1.157     albertel 5639: 
1.423     albertel 5640: =pod
                   5641: 
                   5642: =item scantron_warning_screen
                   5643: 
1.424     albertel 5644:    Interstitial screen to make sure the operator has selected the
                   5645:    correct options before we start the validation phase.
                   5646: 
1.423     albertel 5647: =cut
                   5648: 
1.203     albertel 5649: sub scantron_warning_screen {
                   5650:     my ($button_text)=@_;
1.257     albertel 5651:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5652:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5653:     my $CODElist;
1.284     albertel 5654:     if ($scantron_config{'CODElocation'} &&
                   5655: 	$scantron_config{'CODEstart'} &&
                   5656: 	$scantron_config{'CODElength'}) {
                   5657: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5658: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5659: 	$CODElist=
                   5660: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5661: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5662:     }
1.203     albertel 5663:     return (<<STUFF);
                   5664: <p>
1.398     albertel 5665: <span class="LC_warning">Please double check the information
                   5666:                  below before clicking on '$button_text'</span>
1.203     albertel 5667: </p>
                   5668: <table>
1.284     albertel 5669: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5670: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5671: $CODElist
1.203     albertel 5672: </table>
                   5673: <br />
                   5674: <p> If this information is correct, please click on '$button_text'.</p>
                   5675: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5676: 
                   5677: <br />
                   5678: STUFF
                   5679: }
                   5680: 
1.423     albertel 5681: =pod
                   5682: 
                   5683: =item scantron_do_warning
                   5684: 
1.424     albertel 5685:    Check if the operator has picked something for all required
                   5686:    fields. Error out if something is missing.
                   5687: 
1.423     albertel 5688: =cut
                   5689: 
1.203     albertel 5690: sub scantron_do_warning {
                   5691:     my ($r)=@_;
1.324     albertel 5692:     my ($symb)=&get_symb($r);
1.203     albertel 5693:     if (!$symb) {return '';}
1.324     albertel 5694:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5695:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5696:     if ( $env{'form.selectpage'} eq '' ||
                   5697: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5698: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5699: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5700: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5701: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5702: 	} 
1.257     albertel 5703: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5704: 	    $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 5705: 	} 
1.257     albertel 5706: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5707: 	    $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 5708: 	} 
                   5709:     } else {
1.265     www      5710: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5711: 	$r->print(<<STUFF);
1.203     albertel 5712: $warning
1.265     www      5713: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5714: <input type="hidden" name="command" value="scantron_validate" />
                   5715: STUFF
1.237     albertel 5716:     }
1.352     albertel 5717:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5718:     return '';
                   5719: }
                   5720: 
1.423     albertel 5721: =pod
                   5722: 
                   5723: =item scantron_form_start
                   5724: 
1.424     albertel 5725:     html hidden input for remembering all selected grading options
                   5726: 
1.423     albertel 5727: =cut
                   5728: 
1.203     albertel 5729: sub scantron_form_start {
                   5730:     my ($max_bubble)=@_;
                   5731:     my $result= <<SCANTRONFORM;
                   5732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5733:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5734:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5735:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5736:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5737:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5738:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5739:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5740:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5741:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5742: SCANTRONFORM
1.447     foxr     5743: 
                   5744:   my $line = 0;
                   5745:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448     foxr     5746: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5747:        my $chunk =
                   5748: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5749:        $chunk .=
                   5750: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5751:        $result .= $chunk;
                   5752:        $line++;
                   5753:    }
1.203     albertel 5754:     return $result;
                   5755: }
                   5756: 
1.423     albertel 5757: =pod
                   5758: 
                   5759: =item scantron_validate_file
                   5760: 
1.424     albertel 5761:     Dispatch routine for doing validation of a bubble sheet data file.
                   5762: 
                   5763:     Also processes any necessary information resets that need to
                   5764:     occur before validation begins (ignore previous corrections,
                   5765:     restarting the skipped records processing)
                   5766: 
1.423     albertel 5767: =cut
                   5768: 
1.157     albertel 5769: sub scantron_validate_file {
                   5770:     my ($r) = @_;
1.324     albertel 5771:     my ($symb)=&get_symb($r);
1.157     albertel 5772:     if (!$symb) {return '';}
1.324     albertel 5773:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5774:     
                   5775:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5776:     # them when doing the corrections reset
1.257     albertel 5777:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5778: 	&reset_skipping_status();
                   5779:     }
1.257     albertel 5780:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5781: 	&remember_current_skipped();
1.257     albertel 5782: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5783:     }
                   5784: 
1.257     albertel 5785:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5786: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5787: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5788: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5789: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5790:     }
1.200     albertel 5791: 
1.257     albertel 5792:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5793: 	&scantron_process_corrections($r);
                   5794:     }
1.424     albertel 5795:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5796:     #get the student pick code ready
                   5797:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5798:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5799:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5800:     $r->print($result);
                   5801:     
1.334     albertel 5802:     my @validate_phases=( 'sequence',
                   5803: 			  'ID',
1.157     albertel 5804: 			  'CODE',
                   5805: 			  'doublebubble',
                   5806: 			  'missingbubbles');
1.257     albertel 5807:     if (!$env{'form.validatepass'}) {
                   5808: 	$env{'form.validatepass'} = 0;
1.157     albertel 5809:     }
1.257     albertel 5810:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5811: 
1.448     foxr     5812:     &Apache::lonnet::logthis("Phase: $currentphase");
                   5813: 
1.157     albertel 5814:     my $stop=0;
                   5815:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5816: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5817: 	$r->rflush();
                   5818: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5819: 	{
                   5820: 	    no strict 'refs';
                   5821: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5822: 	}
                   5823:     }
                   5824:     if (!$stop) {
1.203     albertel 5825: 	my $warning=&scantron_warning_screen('Start Grading');
                   5826: 	$r->print(<<STUFF);
                   5827: Validation process complete.<br />
                   5828: $warning
                   5829: <input type="submit" name="submit" value="Start Grading" />
                   5830: <input type="hidden" name="command" value="scantron_process" />
                   5831: STUFF
                   5832: 
1.157     albertel 5833:     } else {
                   5834: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5835: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5836:     }
                   5837:     if ($stop) {
1.334     albertel 5838: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5839: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5840: 	    $r->print(' this error <br />');
                   5841: 
                   5842: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5843: 	} else {
                   5844: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5845: 	    $r->print(' using corrected info <br />');
                   5846: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5847: 	    $r->print(" this scanline saving it for later.");
                   5848: 	}
1.157     albertel 5849:     }
1.352     albertel 5850:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5851:     return '';
                   5852: }
                   5853: 
1.423     albertel 5854: 
                   5855: =pod
                   5856: 
                   5857: =item scantron_remove_file
                   5858: 
1.424     albertel 5859:    Removes the requested bubble sheet data file, makes sure that
                   5860:    scantron_original_<filename> is never removed
                   5861: 
                   5862: 
1.423     albertel 5863: =cut
                   5864: 
1.200     albertel 5865: sub scantron_remove_file {
1.192     albertel 5866:     my ($which)=@_;
1.257     albertel 5867:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5869:     my $file='scantron_';
1.200     albertel 5870:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5871: 	$file.=$which.'_';
1.192     albertel 5872:     } else {
                   5873: 	return 'refused';
                   5874:     }
1.257     albertel 5875:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5876:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5877: }
                   5878: 
1.423     albertel 5879: 
                   5880: =pod
                   5881: 
                   5882: =item scantron_remove_scan_data
                   5883: 
1.424     albertel 5884:    Removes all scan_data correction for the requested bubble sheet
                   5885:    data file.  (In the case that both the are doing skipped records we need
                   5886:    to remember the old skipped lines for the time being so that element
                   5887:    persists for a while.)
                   5888: 
1.423     albertel 5889: =cut
                   5890: 
1.200     albertel 5891: sub scantron_remove_scan_data {
1.257     albertel 5892:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5893:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5894:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5895:     my @todelete;
1.257     albertel 5896:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5897:     foreach my $key (@keys) {
                   5898: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5899: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5900: 		$key=~/remember_skipping/) {
                   5901: 		next;
                   5902: 	    }
1.192     albertel 5903: 	    push(@todelete,$key);
                   5904: 	}
                   5905:     }
1.200     albertel 5906:     my $result;
1.192     albertel 5907:     if (@todelete) {
1.200     albertel 5908: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5909:     }
                   5910:     return $result;
                   5911: }
                   5912: 
1.423     albertel 5913: 
                   5914: =pod
                   5915: 
                   5916: =item scantron_getfile
                   5917: 
1.424     albertel 5918:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5919:     the scan_data hash
                   5920:   
                   5921:   Arguments:
                   5922:     None
                   5923: 
                   5924:   Returns:
                   5925:     2 hash references
                   5926: 
                   5927:      - first one has 
                   5928:          orig      -
                   5929:          corrected -
                   5930:          skipped   -  each of which points to an array ref of the specified
                   5931:                       file broken up into individual lines
                   5932:          count     - number of scanlines
                   5933:  
                   5934:      - second is the scan_data hash possible keys are
1.425     albertel 5935:        ($number refers to scanline numbered $number and thus the key affects
                   5936:         only that scanline
                   5937:         $bubline refers to the specific bubble line element and the aspects
                   5938:         refers to that specific bubble line element)
                   5939: 
                   5940:        $number.user - username:domain to use
                   5941:        $number.CODE_ignore_dup 
                   5942:                     - ignore the duplicate CODE error 
                   5943:        $number.useCODE
                   5944:                     - use the CODE in the scanline as is
                   5945:        $number.no_bubble.$bubline
                   5946:                     - it is valid that there is no bubbled in bubble
                   5947:                       at $number $bubline
                   5948:        remember_skipping
                   5949:                     - a frozen hash containing keys of $number and values
                   5950:                       of either 
                   5951:                         1 - we are on a 'do skipped records pass' and plan
                   5952:                             on processing this line
                   5953:                         2 - we are on a 'do skipped records pass' and this
                   5954:                             scanline has been marked to skip yet again
1.424     albertel 5955: 
1.423     albertel 5956: =cut
                   5957: 
1.157     albertel 5958: sub scantron_getfile {
1.200     albertel 5959:     #FIXME really would prefer a scantron directory
1.257     albertel 5960:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5961:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5962:     my $lines;
                   5963:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5964: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5965:     my %scanlines;
                   5966:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5967:     my $temp=$scanlines{'orig'};
                   5968:     $scanlines{'count'}=$#$temp;
                   5969: 
                   5970:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5971: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5972:     if ($lines eq '-1') {
                   5973: 	$scanlines{'corrected'}=[];
                   5974:     } else {
                   5975: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5976:     }
                   5977:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5978: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5979:     if ($lines eq '-1') {
                   5980: 	$scanlines{'skipped'}=[];
                   5981:     } else {
                   5982: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5983:     }
1.175     albertel 5984:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5985:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5986:     my %scan_data = @tmp;
                   5987:     return (\%scanlines,\%scan_data);
                   5988: }
                   5989: 
1.423     albertel 5990: =pod
                   5991: 
                   5992: =item lonnet_putfile
                   5993: 
1.424     albertel 5994:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5995: 
                   5996:  Arguments:
                   5997:    $contents - data to store
                   5998:    $filename - filename to store $contents into
                   5999: 
                   6000:  Returns:
                   6001:    result value from &Apache::lonnet::finishuserfileupload
                   6002: 
1.423     albertel 6003: =cut
                   6004: 
1.157     albertel 6005: sub lonnet_putfile {
                   6006:     my ($contents,$filename)=@_;
1.257     albertel 6007:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6008:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6009:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6010:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6011: 
                   6012: }
                   6013: 
1.423     albertel 6014: =pod
                   6015: 
                   6016: =item scantron_putfile
                   6017: 
1.424     albertel 6018:     Stores the current version of the bubble sheet data files, and the
                   6019:     scan_data hash. (Does not modify the original version only the
                   6020:     corrected and skipped versions.
                   6021: 
                   6022:  Arguments:
                   6023:     $scanlines - hash ref that looks like the first return value from
                   6024:                  &scantron_getfile()
                   6025:     $scan_data - hash ref that looks like the second return value from
                   6026:                  &scantron_getfile()
                   6027: 
1.423     albertel 6028: =cut
                   6029: 
1.157     albertel 6030: sub scantron_putfile {
                   6031:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6032:     #FIXME really would prefer a scantron directory
1.257     albertel 6033:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6034:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6035:     if ($scanlines) {
                   6036: 	my $prefix='scantron_';
1.157     albertel 6037: # no need to update orig, shouldn't change
                   6038: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6039: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6040: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6041: 			$prefix.'corrected_'.
1.257     albertel 6042: 			$env{'form.scantron_selectfile'});
1.200     albertel 6043: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6044: 			$prefix.'skipped_'.
1.257     albertel 6045: 			$env{'form.scantron_selectfile'});
1.200     albertel 6046:     }
1.175     albertel 6047:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6048: }
                   6049: 
1.423     albertel 6050: =pod
                   6051: 
                   6052: =item scantron_get_line
                   6053: 
1.424     albertel 6054:    Returns the correct version of the scanline
                   6055: 
                   6056:  Arguments:
                   6057:     $scanlines - hash ref that looks like the first return value from
                   6058:                  &scantron_getfile()
                   6059:     $scan_data - hash ref that looks like the second return value from
                   6060:                  &scantron_getfile()
                   6061:     $i         - number of the requested line (starts at 0)
                   6062: 
                   6063:  Returns:
                   6064:    A scanline, (either the original or the corrected one if it
                   6065:    exists), or undef if the requested scanline should be
                   6066:    skipped. (Either because it's an skipped scanline, or it's an
                   6067:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6068:    pass.
                   6069: 
1.423     albertel 6070: =cut
                   6071: 
1.157     albertel 6072: sub scantron_get_line {
1.200     albertel 6073:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6074:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6075:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6076:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6077:     return $scanlines->{'orig'}[$i]; 
                   6078: }
                   6079: 
1.423     albertel 6080: =pod
                   6081: 
                   6082: =item scantron_todo_count
                   6083: 
1.424     albertel 6084:     Counts the number of scanlines that need processing.
                   6085: 
                   6086:  Arguments:
                   6087:     $scanlines - hash ref that looks like the first return value from
                   6088:                  &scantron_getfile()
                   6089:     $scan_data - hash ref that looks like the second return value from
                   6090:                  &scantron_getfile()
                   6091: 
                   6092:  Returns:
                   6093:     $count - number of scanlines to process
                   6094: 
1.423     albertel 6095: =cut
                   6096: 
1.200     albertel 6097: sub get_todo_count {
                   6098:     my ($scanlines,$scan_data)=@_;
                   6099:     my $count=0;
                   6100:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6101: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6102: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6103: 	$count++;
                   6104:     }
                   6105:     return $count;
                   6106: }
                   6107: 
1.423     albertel 6108: =pod
                   6109: 
                   6110: =item scantron_put_line
                   6111: 
1.424     albertel 6112:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6113:     data file.
                   6114: 
                   6115:  Arguments:
                   6116:     $scanlines - hash ref that looks like the first return value from
                   6117:                  &scantron_getfile()
                   6118:     $scan_data - hash ref that looks like the second return value from
                   6119:                  &scantron_getfile()
                   6120:     $i         - line number to update
                   6121:     $newline   - contents of the updated scanline
                   6122:     $skip      - if true make the line for skipping and update the
                   6123:                  'skipped' file
                   6124: 
1.423     albertel 6125: =cut
                   6126: 
1.157     albertel 6127: sub scantron_put_line {
1.200     albertel 6128:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6129:     if ($skip) {
                   6130: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6131: 	&start_skipping($scan_data,$i);
1.157     albertel 6132: 	return;
                   6133:     }
                   6134:     $scanlines->{'corrected'}[$i]=$newline;
                   6135: }
                   6136: 
1.423     albertel 6137: =pod
                   6138: 
                   6139: =item scantron_clear_skip
                   6140: 
1.424     albertel 6141:    Remove a line from the 'skipped' file
                   6142: 
                   6143:  Arguments:
                   6144:     $scanlines - hash ref that looks like the first return value from
                   6145:                  &scantron_getfile()
                   6146:     $scan_data - hash ref that looks like the second return value from
                   6147:                  &scantron_getfile()
                   6148:     $i         - line number to update
                   6149: 
1.423     albertel 6150: =cut
                   6151: 
1.376     albertel 6152: sub scantron_clear_skip {
                   6153:     my ($scanlines,$scan_data,$i)=@_;
                   6154:     if (exists($scanlines->{'skipped'}[$i])) {
                   6155: 	undef($scanlines->{'skipped'}[$i]);
                   6156: 	return 1;
                   6157:     }
                   6158:     return 0;
                   6159: }
                   6160: 
1.423     albertel 6161: =pod
                   6162: 
                   6163: =item scantron_filter_not_exam
                   6164: 
1.424     albertel 6165:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6166:    filter out resources that are not marked as 'exam' mode
                   6167: 
1.423     albertel 6168: =cut
                   6169: 
1.334     albertel 6170: sub scantron_filter_not_exam {
                   6171:     my ($curres)=@_;
                   6172:     
                   6173:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6174: 	# if the user has asked to not have either hidden
                   6175: 	# or 'randomout' controlled resources to be graded
                   6176: 	# don't include them
                   6177: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6178: 	    && $curres->randomout) {
                   6179: 	    return 0;
                   6180: 	}
                   6181: 	return 1;
                   6182:     }
                   6183:     return 0;
                   6184: }
                   6185: 
1.423     albertel 6186: =pod
                   6187: 
                   6188: =item scantron_validate_sequence
                   6189: 
1.424     albertel 6190:     Validates the selected sequence, checking for resource that are
                   6191:     not set to exam mode.
                   6192: 
1.423     albertel 6193: =cut
                   6194: 
1.334     albertel 6195: sub scantron_validate_sequence {
                   6196:     my ($r,$currentphase) = @_;
                   6197: 
                   6198:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6199:     my (undef,undef,$sequence)=
                   6200: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6201: 
                   6202:     my $map=$navmap->getResourceByUrl($sequence);
                   6203: 
                   6204:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6205:                                     value="ignore" />');
                   6206:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6207: 	my @resources=
                   6208: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6209: 	if (@resources) {
1.357     banghart 6210: 	    $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 6211: 	    return (1,$currentphase);
                   6212: 	}
                   6213:     }
                   6214: 
                   6215:     return (0,$currentphase+1);
                   6216: }
                   6217: 
1.423     albertel 6218: =pod
                   6219: 
                   6220: =item scantron_validate_ID
                   6221: 
1.424     albertel 6222:    Validates all scanlines in the selected file to not have any
                   6223:    invalid or underspecified student IDs
                   6224: 
1.423     albertel 6225: =cut
                   6226: 
1.157     albertel 6227: sub scantron_validate_ID {
                   6228:     my ($r,$currentphase) = @_;
                   6229:     
                   6230:     #get student info
                   6231:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6232:     my %idmap=&username_to_idmap($classlist);
                   6233: 
                   6234:     #get scantron line setup
1.257     albertel 6235:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6236:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6237:     
                   6238:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6239: 
                   6240:     my %found=('ids'=>{},'usernames'=>{});
                   6241:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6242: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6243: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6244: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6245: 						 $scan_data);
                   6246: 	my $id=$$scan_record{'scantron.ID'};
                   6247: 	my $found;
                   6248: 	foreach my $checkid (keys(%idmap)) {
                   6249: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6250: 	}
                   6251: 	if ($found) {
                   6252: 	    my $username=$idmap{$found};
                   6253: 	    if ($found{'ids'}{$found}) {
                   6254: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6255: 					 $line,'duplicateID',$found);
1.194     albertel 6256: 		return(1,$currentphase);
1.157     albertel 6257: 	    } elsif ($found{'usernames'}{$username}) {
                   6258: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6259: 					 $line,'duplicateID',$username);
1.194     albertel 6260: 		return(1,$currentphase);
1.157     albertel 6261: 	    }
1.186     albertel 6262: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6263: 	    $found{'ids'}{$found}++;
                   6264: 	    $found{'usernames'}{$username}++;
                   6265: 	} else {
                   6266: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6267: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6268: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6269: 		    &scantron_get_correction($r,$i,$scan_record,
                   6270: 					     \%scantron_config,
                   6271: 					     $line,'duplicateID',$username);
1.194     albertel 6272: 		    return(1,$currentphase);
1.157     albertel 6273: 		} elsif (!defined($username)) {
                   6274: 		    &scantron_get_correction($r,$i,$scan_record,
                   6275: 					     \%scantron_config,
                   6276: 					     $line,'incorrectID');
1.194     albertel 6277: 		    return(1,$currentphase);
1.157     albertel 6278: 		}
                   6279: 		$found{'usernames'}{$username}++;
                   6280: 	    } else {
                   6281: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6282: 					 $line,'incorrectID');
1.194     albertel 6283: 		return(1,$currentphase);
1.157     albertel 6284: 	    }
                   6285: 	}
                   6286:     }
                   6287: 
                   6288:     return (0,$currentphase+1);
                   6289: }
                   6290: 
1.423     albertel 6291: =pod
                   6292: 
                   6293: =item scantron_get_correction
                   6294: 
1.424     albertel 6295:    Builds the interface screen to interact with the operator to fix a
                   6296:    specific error condition in a specific scanline
                   6297: 
                   6298:  Arguments:
                   6299:     $r           - Apache request object
                   6300:     $i           - number of the current scanline
                   6301:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6302:     $scan_config - hash ref as returned from &get_scantron_config()
                   6303:     $line        - full contents of the current scanline
                   6304:     $error       - error condition, valid values are
                   6305:                    'incorrectCODE', 'duplicateCODE',
                   6306:                    'doublebubble', 'missingbubble',
                   6307:                    'duplicateID', 'incorrectID'
                   6308:     $arg         - extra information needed
                   6309:        For errors:
                   6310:          - duplicateID   - paper number that this studentID was seen before on
                   6311:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6312:                            seen on before
                   6313:          - incorrectCODE - current incorrect CODE 
                   6314:          - doublebubble  - array ref of the bubble lines that have double
                   6315:                            bubble errors
                   6316:          - missingbubble - array ref of the bubble lines that have missing
                   6317:                            bubble errors
                   6318: 
1.423     albertel 6319: =cut
                   6320: 
1.157     albertel 6321: sub scantron_get_correction {
                   6322:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6323: 
                   6324: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6325: #to show both the current line and the previous one and allow skipping
                   6326: #the previous one or the current one
                   6327: 
1.161     albertel 6328:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6329:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6330: 	$r->print(" for PaperID <tt>".
                   6331: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6332:     } else {
                   6333: 	$r->print(" in scanline $i <pre>".
                   6334: 		  $line."</pre> \n");
                   6335:     }
1.242     albertel 6336:     my $message="<p>The ID on the form is  <tt>".
                   6337: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6338: 	"The name on the paper is ".
                   6339: 	$$scan_record{'scantron.LastName'}.",".
                   6340: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6341: 
1.157     albertel 6342:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6343:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6344:     if ($error =~ /ID$/) {
1.186     albertel 6345: 	if ($error eq 'incorrectID') {
1.157     albertel 6346: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6347: 	} elsif ($error eq 'duplicateID') {
                   6348: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6349: 	}
1.242     albertel 6350: 	$r->print($message);
1.157     albertel 6351: 	$r->print("<p>How should I handle this? <br /> \n");
                   6352: 	$r->print("\n<ul><li> ");
                   6353: 	#FIXME it would be nice if this sent back the user ID and
                   6354: 	#could do partial userID matches
                   6355: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6356: 				       'scantron_username','scantron_domain'));
                   6357: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6358: 	$r->print("\n@".
1.257     albertel 6359: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6360: 
                   6361: 	$r->print('</li>');
1.186     albertel 6362:     } elsif ($error =~ /CODE$/) {
                   6363: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6364: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6365: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6366: 	    $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 6367: 	}
1.224     albertel 6368: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6369: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6370: 	$r->print($message);
1.186     albertel 6371: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6372: 	$r->print("\n<br /> ");
1.194     albertel 6373: 	my $i=0;
1.273     albertel 6374: 	if ($error eq 'incorrectCODE' 
                   6375: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6376: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6377: 	    if ($closest > 0) {
                   6378: 		foreach my $testcode (@{$closest}) {
                   6379: 		    my $checked='';
1.401     albertel 6380: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6381: 		    $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' />");
                   6382: 		    $r->print("\n<br />");
                   6383: 		    $i++;
                   6384: 		}
1.194     albertel 6385: 	    }
                   6386: 	}
1.273     albertel 6387: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6388: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6389: 	    $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>");
                   6390: 	    $r->print("\n<br />");
                   6391: 	}
1.194     albertel 6392: 
1.188     albertel 6393: 	$r->print(<<ENDSCRIPT);
                   6394: <script type="text/javascript">
                   6395: function change_radio(field) {
1.190     albertel 6396:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6397:     var i;
                   6398:     for (i=0;i<slct.length;i++) {
                   6399:         if (slct[i].value==field) { slct[i].checked=true; }
                   6400:     }
                   6401: }
                   6402: </script>
                   6403: ENDSCRIPT
1.187     albertel 6404: 	my $href="/adm/pickcode?".
1.359     www      6405: 	   "form=".&escape("scantronupload").
                   6406: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6407: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6408: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6409: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6410: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6411: 	    $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')\" />");
                   6412: 	    $r->print("\n<br />");
                   6413: 	}
1.272     albertel 6414: 	$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 6415: 	$r->print("\n<br /><br />");
1.157     albertel 6416:     } elsif ($error eq 'doublebubble') {
                   6417: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6418: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6419: 		  join(',',@{$arg}).'" />');
1.242     albertel 6420: 	$r->print($message);
1.157     albertel 6421: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6422: 	foreach my $question (@{$arg}) {
1.447     foxr     6423: 
                   6424: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6425: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6426: 				      split('',$selected));
1.157     albertel 6427: 	}
                   6428:     } elsif ($error eq 'missingbubble') {
                   6429: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6430: 	$r->print($message);
1.157     albertel 6431: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6432: 	$r->print("Some questions have no scanned bubbles\n");
                   6433: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6434: 		  join(',',@{$arg}).'" />');
                   6435: 	foreach my $question (@{$arg}) {
1.448     foxr     6436: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6437: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6438: 	}
                   6439:     } else {
                   6440: 	$r->print("\n<ul>");
                   6441:     }
                   6442:     $r->print("\n</li></ul>");
                   6443: 
                   6444: }
1.423     albertel 6445: 
                   6446: =pod
                   6447: 
                   6448: =item scantron_bubble_selector
                   6449:   
                   6450:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6451:    possibly showing the existing the selected bubbles if known
1.423     albertel 6452: 
                   6453:  Arguments:
                   6454:     $r           - Apache request object
                   6455:     $scan_config - hash from &get_scantron_config()
                   6456:     $quest       - number of the bubble line to make a corrector for
                   6457:     $selected    - array of letters of previously selected bubbles
                   6458: 
                   6459: =cut
                   6460: 
1.157     albertel 6461: sub scantron_bubble_selector {
1.447     foxr     6462:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6463:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6464: 
                   6465:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6466: 
                   6467: 
1.274     albertel 6468:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6469: 
1.448     foxr     6470:     my $response = $quest-1;
                   6471:     my $lines = $bubble_lines_per_response{$response};
                   6472:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6473: 
1.422     foxr     6474:     my $total_lines = $lines*2;
1.157     albertel 6475:     my @alphabet=('A'..'Z');
1.422     foxr     6476:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6477: 
                   6478:     for (my $l = 0; $l < $lines; $l++) {
                   6479: 	if ($l != 0) {
                   6480: 	    $r->print('<tr>');
                   6481: 	}
                   6482: 
                   6483: 	# FIXME:  This loop probably has to be considerably more clever for
                   6484: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6485: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6486: 
                   6487: 	for (my $i=0;$i<$max;$i++) {
                   6488: 	    $r->print("\n".'<td align="center">');
                   6489: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6490: 		$r->print('X'); 
                   6491: 		shift(@selected) ;
                   6492: 	    } else { 
                   6493: 		$r->print('&nbsp;'); 
                   6494: 	    }
                   6495: 	    $r->print('</td>');
                   6496: 	    
                   6497: 	}
                   6498: 
                   6499: 	if ($l == 0) {
                   6500: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6501: 
                   6502: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6503: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6504: 	
                   6505: 	}
                   6506: 
                   6507: 	$r->print('</tr><tr>');
                   6508: 
                   6509: 	# FIXME: This may have to be a bit more clever for
                   6510: 	#        multiline questions (different values e.g..).
                   6511: 
                   6512: 	for (my $i=0;$i<$max;$i++) {
                   6513: 	    $r->print("\n".
                   6514: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6515: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6516: 	}
                   6517: 	$r->print('</tr>');
                   6518: 
                   6519: 	    
1.157     albertel 6520:     }
1.422     foxr     6521:     $r->print('</table>');
1.157     albertel 6522: }
                   6523: 
1.423     albertel 6524: =pod
                   6525: 
                   6526: =item num_matches
                   6527: 
1.424     albertel 6528:    Counts the number of characters that are the same between the two arguments.
                   6529: 
                   6530:  Arguments:
                   6531:    $orig - CODE from the scanline
                   6532:    $code - CODE to match against
                   6533: 
                   6534:  Returns:
                   6535:    $count - integer count of the number of same characters between the
                   6536:             two arguments
                   6537: 
1.423     albertel 6538: =cut
                   6539: 
1.194     albertel 6540: sub num_matches {
                   6541:     my ($orig,$code) = @_;
                   6542:     my @code=split(//,$code);
                   6543:     my @orig=split(//,$orig);
                   6544:     my $same=0;
                   6545:     for (my $i=0;$i<scalar(@code);$i++) {
                   6546: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6547:     }
                   6548:     return $same;
                   6549: }
                   6550: 
1.423     albertel 6551: =pod
                   6552: 
                   6553: =item scantron_get_closely_matching_CODEs
                   6554: 
1.424     albertel 6555:    Cycles through all CODEs and finds the set that has the greatest
                   6556:    number of same characters as the provided CODE
                   6557: 
                   6558:  Arguments:
                   6559:    $allcodes - hash ref returned by &get_codes()
                   6560:    $CODE     - CODE from the current scanline
                   6561: 
                   6562:  Returns:
                   6563:    2 element list
                   6564:     - first elements is number of how closely matching the best fit is 
                   6565:       (5 means best set has 5 matching characters)
                   6566:     - second element is an arrary ref containing the set of valid CODEs
                   6567:       that best fit the passed in CODE
                   6568: 
1.423     albertel 6569: =cut
                   6570: 
1.194     albertel 6571: sub scantron_get_closely_matching_CODEs {
                   6572:     my ($allcodes,$CODE)=@_;
                   6573:     my @CODEs;
                   6574:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6575: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6576:     }
                   6577: 
                   6578:     return ($#CODEs,$CODEs[-1]);
                   6579: }
                   6580: 
1.423     albertel 6581: =pod
                   6582: 
                   6583: =item get_codes
                   6584: 
1.424     albertel 6585:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6586:    set of remembered CODEs.
                   6587: 
                   6588:  Arguments:
                   6589:   $old_name - name of the set of remembered CODEs
                   6590:   $cdom     - domain of the course
                   6591:   $cnum     - internal course name
                   6592: 
                   6593:  Returns:
                   6594:   %allcodes - keys are the valid CODEs, values are all 1
                   6595: 
1.423     albertel 6596: =cut
                   6597: 
1.194     albertel 6598: sub get_codes {
1.280     foxr     6599:     my ($old_name, $cdom, $cnum) = @_;
                   6600:     if (!$old_name) {
                   6601: 	$old_name=$env{'form.scantron_CODElist'};
                   6602:     }
                   6603:     if (!$cdom) {
                   6604: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6605:     }
                   6606:     if (!$cnum) {
                   6607: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6608:     }
1.278     albertel 6609:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6610: 				    $cdom,$cnum);
                   6611:     my %allcodes;
                   6612:     if ($result{"type\0$old_name"} eq 'number') {
                   6613: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6614:     } else {
                   6615: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6616:     }
1.194     albertel 6617:     return %allcodes;
                   6618: }
                   6619: 
1.423     albertel 6620: =pod
                   6621: 
                   6622: =item scantron_validate_CODE
                   6623: 
1.424     albertel 6624:    Validates all scanlines in the selected file to not have any
                   6625:    invalid or underspecified CODEs and that none of the codes are
                   6626:    duplicated if this was requested.
                   6627: 
1.423     albertel 6628: =cut
                   6629: 
1.157     albertel 6630: sub scantron_validate_CODE {
                   6631:     my ($r,$currentphase) = @_;
1.257     albertel 6632:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6633:     if ($scantron_config{'CODElocation'} &&
                   6634: 	$scantron_config{'CODEstart'} &&
                   6635: 	$scantron_config{'CODElength'}) {
1.257     albertel 6636: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6637: 	    &FIXME_blow_up()
                   6638: 	}
                   6639:     } else {
                   6640: 	return (0,$currentphase+1);
                   6641:     }
                   6642:     
                   6643:     my %usedCODEs;
                   6644: 
1.194     albertel 6645:     my %allcodes=&get_codes();
1.186     albertel 6646: 
1.447     foxr     6647:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6648: 
1.186     albertel 6649:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6650:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6651: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6652: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6653: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6654: 						 $scan_data);
                   6655: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6656: 	my $error=0;
1.224     albertel 6657: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6658: 	    &scantron_get_correction($r,$i,$scan_record,
                   6659: 				     \%scantron_config,
                   6660: 				     $line,'incorrectCODE',\%allcodes);
                   6661: 	    return(1,$currentphase);
                   6662: 	}
1.221     albertel 6663: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6664: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6665: 	    &scantron_get_correction($r,$i,$scan_record,
                   6666: 				     \%scantron_config,
1.194     albertel 6667: 				     $line,'incorrectCODE',\%allcodes);
                   6668: 	    return(1,$currentphase);
1.186     albertel 6669: 	}
1.214     albertel 6670: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6671: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6672: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6673: 	    &scantron_get_correction($r,$i,$scan_record,
                   6674: 				     \%scantron_config,
1.194     albertel 6675: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6676: 	    return(1,$currentphase);
1.186     albertel 6677: 	}
1.194     albertel 6678: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6679:     }
1.157     albertel 6680:     return (0,$currentphase+1);
                   6681: }
                   6682: 
1.423     albertel 6683: =pod
                   6684: 
                   6685: =item scantron_validate_doublebubble
                   6686: 
1.424     albertel 6687:    Validates all scanlines in the selected file to not have any
                   6688:    bubble lines with multiple bubbles marked.
                   6689: 
1.423     albertel 6690: =cut
                   6691: 
1.157     albertel 6692: sub scantron_validate_doublebubble {
                   6693:     my ($r,$currentphase) = @_;
                   6694:     #get student info
                   6695:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6696:     my %idmap=&username_to_idmap($classlist);
                   6697: 
                   6698:     #get scantron line setup
1.257     albertel 6699:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6700:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6701: 
                   6702:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6703: 
1.157     albertel 6704:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6705: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6706: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6707: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6708: 						 $scan_data);
                   6709: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6710: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6711: 				 'doublebubble',
                   6712: 				 $$scan_record{'scantron.doubleerror'});
                   6713:     	return (1,$currentphase);
                   6714:     }
                   6715:     return (0,$currentphase+1);
                   6716: }
                   6717: 
1.423     albertel 6718: =pod
                   6719: 
                   6720: =item scantron_get_maxbubble
                   6721: 
1.424     albertel 6722:    Returns the maximum number of bubble lines that are expected to
                   6723:    occur. Does this by walking the selected sequence rendering the
                   6724:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6725:    for what the current value of the problem counter is.
                   6726: 
1.447     foxr     6727:    Caches the results to $env{'form.scantron_maxbubble'},
                   6728:    $env{'form.scantron.bubble_lines.n'} and 
                   6729:    $env{'form.scantron.first_bubble_line.n'}
                   6730:    which are the total number of bubble, lines, the number of bubble
                   6731:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6732: 
1.423     albertel 6733: =cut
                   6734: 
1.330     albertel 6735: sub scantron_get_maxbubble {    
1.448     foxr     6736:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6737:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6738: 	$env{'form.scantron_maxbubble'}) {
1.448     foxr     6739: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6740: 	&restore_bubble_lines();
1.257     albertel 6741: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6742:     }
1.448     foxr     6743:     &Apache::lonnet::logthis("computing");
1.330     albertel 6744: 
1.447     foxr     6745:     my (undef, undef, $sequence) =
1.257     albertel 6746: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6747: 
1.447     foxr     6748:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6749:     my $map=$navmap->getResourceByUrl($sequence);
                   6750:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6751: 
                   6752:     &Apache::lonxml::clear_problem_counter();
                   6753: 
1.435     foxr     6754:     my $uname       = $env{'form.student'};
                   6755:     my $udom        = $env{'form.userdom'};
                   6756:     my $cid         = $env{'request.course.id'};
                   6757:     my $total_lines = 0;
                   6758:     %bubble_lines_per_response = ();
1.447     foxr     6759:     %first_bubble_line         = ();
1.435     foxr     6760: 
1.447     foxr     6761:   
                   6762:     my $response_number = 0;
                   6763:     my $bubble_line     = 0;
1.191     albertel 6764:     foreach my $resource (@resources) {
1.435     foxr     6765: 	my $symb = $resource->symb();
1.447     foxr     6766: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6767: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6768: 					('symb' => $resource->symb()),
                   6769: 					('grade_target' => 'analyze'),
                   6770: 					('grade_courseid' => $cid),
                   6771: 					('grade_domain' => $udom),
                   6772: 					('grade_username' => $uname));
1.436     albertel 6773: 	my (undef, $an) =
1.435     foxr     6774: 	    split(/_HASH_REF__/,$result, 2);
                   6775: 
                   6776: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6777: 
                   6778: 
                   6779: 
                   6780: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6781: 	    my ($trash, $part) = split(/\./, $part_id);
                   6782: 
                   6783: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6784: 
                   6785: 	    # TODO - make this a persistent hash not an array.
                   6786: 
                   6787: 
                   6788: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6789: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6790: 	    $response_number++;
                   6791: 
                   6792: 	    $bubble_line +=  $lines;
                   6793: 	    $total_lines +=  $lines;
1.435     foxr     6794: 	}
                   6795: 
1.191     albertel 6796:     }
                   6797:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6798: 
                   6799:     &save_bubble_lines();
1.330     albertel 6800:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6801: 	$total_lines;
1.257     albertel 6802:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6803: }
                   6804: 
1.423     albertel 6805: =pod
                   6806: 
                   6807: =item scantron_validate_missingbubbles
                   6808: 
1.424     albertel 6809:    Validates all scanlines in the selected file to not have any
1.447     foxr     6810:     answers that don't have bubbles that have not been verified
                   6811:     to be bubble free.
1.424     albertel 6812: 
1.423     albertel 6813: =cut
                   6814: 
1.157     albertel 6815: sub scantron_validate_missingbubbles {
                   6816:     my ($r,$currentphase) = @_;
                   6817:     #get student info
                   6818:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6819:     my %idmap=&username_to_idmap($classlist);
                   6820: 
                   6821:     #get scantron line setup
1.257     albertel 6822:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6823:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6824:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6825:     if (!$max_bubble) { $max_bubble=2**31; }
                   6826:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6827: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6828: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6829: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6830: 						 $scan_data);
                   6831: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6832: 	my @to_correct;
                   6833: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6834: 	    if ($missing > $max_bubble) { next; }
                   6835: 	    push(@to_correct,$missing);
                   6836: 	}
                   6837: 	if (@to_correct) {
                   6838: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6839: 				     $line,'missingbubble',\@to_correct);
                   6840: 	    return (1,$currentphase);
                   6841: 	}
                   6842: 
                   6843:     }
                   6844:     return (0,$currentphase+1);
                   6845: }
                   6846: 
1.423     albertel 6847: =pod
                   6848: 
                   6849: =item scantron_process_students
                   6850: 
                   6851:    Routine that does the actual grading of the bubble sheet information.
                   6852: 
                   6853:    The parsed scanline hash is added to %env 
                   6854: 
                   6855:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6856:    foreach resource , with the form data of
                   6857: 
                   6858: 	'submitted'     =>'scantron' 
                   6859: 	'grade_target'  =>'grade',
                   6860: 	'grade_username'=> username of student
                   6861: 	'grade_domain'  => domain of student
                   6862: 	'grade_courseid'=> of course
                   6863: 	'grade_symb'    => symb of resource to grade
                   6864: 
                   6865:     This triggers a grading pass. The problem grading code takes care
                   6866:     of converting the bubbled letter information (now in %env) into a
                   6867:     valid submission.
                   6868: 
                   6869: =cut
                   6870: 
1.82      albertel 6871: sub scantron_process_students {
1.75      albertel 6872:     my ($r) = @_;
1.257     albertel 6873:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6874:     my ($symb)=&get_symb($r);
1.81      albertel 6875:     if (!$symb) {return '';}
1.324     albertel 6876:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6877: 
1.257     albertel 6878:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6879:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6880:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6881:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6882:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6883:     my $map=$navmap->getResourceByUrl($sequence);
                   6884:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6885: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6886:     my $result= <<SCANTRONFORM;
1.81      albertel 6887: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6888:   <input type="hidden" name="command" value="scantron_configphase" />
                   6889:   $default_form_data
                   6890: SCANTRONFORM
1.82      albertel 6891:     $r->print($result);
                   6892: 
                   6893:     my @delayqueue;
1.140     albertel 6894:     my %completedstudents;
                   6895:     
1.200     albertel 6896:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6897:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6898:  				    'Scantron Progress',$count,
1.195     albertel 6899: 				    'inline',undef,'scantronupload');
1.140     albertel 6900:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6901: 					  'Processing first student');
                   6902:     my $start=&Time::HiRes::time();
1.158     albertel 6903:     my $i=-1;
1.200     albertel 6904:     my ($uname,$udom,$started);
1.447     foxr     6905: 
                   6906:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6907: 
1.157     albertel 6908:     while ($i<$scanlines->{'count'}) {
                   6909:  	($uname,$udom)=('','');
                   6910:  	$i++;
1.200     albertel 6911:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6912:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6913: 	if ($started) {
                   6914: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6915: 						     'last student');
                   6916: 	}
                   6917: 	$started=1;
1.157     albertel 6918:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6919:  						 $scan_data);
                   6920:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6921:  					      \%idmap,$i)) {
                   6922:   	    &scantron_add_delay(\@delayqueue,$line,
                   6923:  				'Unable to find a student that matches',1);
                   6924:  	    next;
                   6925:   	}
                   6926:  	if (exists $completedstudents{$uname}) {
                   6927:  	    &scantron_add_delay(\@delayqueue,$line,
                   6928:  				'Student '.$uname.' has multiple sheets',2);
                   6929:  	    next;
                   6930:  	}
                   6931:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6932: 
                   6933: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6934:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6935: 
                   6936: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6937: 	    &scantron_putfile($scanlines,$scan_data);
                   6938: 	}
1.161     albertel 6939: 	
                   6940: 	my $i=0;
1.83      albertel 6941: 	foreach my $resource (@resources) {
1.85      albertel 6942: 	    $i++;
1.193     albertel 6943: 	    my %form=('submitted'     =>'scantron',
                   6944: 		      'grade_target'  =>'grade',
                   6945: 		      'grade_username'=>$uname,
                   6946: 		      'grade_domain'  =>$udom,
1.257     albertel 6947: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6948: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6949: 	    if (exists($scan_record->{'scantron.CODE'})
                   6950: 		&& 
                   6951: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6952: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6953: 	    } else {
                   6954: 		$form{'CODE'}='';
1.193     albertel 6955: 	    }
                   6956: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6957: 	    if ($result ne '') {
                   6958: 	    }
1.213     albertel 6959: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6960: 	}
1.140     albertel 6961: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6962: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6963:     } continue {
1.330     albertel 6964: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6965: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6966:     }
1.140     albertel 6967:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6968: #    my $lasttime = &Time::HiRes::time()-$start;
                   6969: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6970: 
1.200     albertel 6971:     $r->print("</form>");
1.324     albertel 6972:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6973:     return '';
1.75      albertel 6974: }
1.157     albertel 6975: 
1.423     albertel 6976: =pod
                   6977: 
                   6978: =item scantron_upload_scantron_data
                   6979: 
                   6980:     Creates the screen for adding a new bubble sheet data file to a course.
                   6981: 
                   6982: =cut
                   6983: 
1.157     albertel 6984: sub scantron_upload_scantron_data {
                   6985:     my ($r)=@_;
1.257     albertel 6986:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6987:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6988: 							  'domainid',
                   6989: 							  'coursename');
1.257     albertel 6990:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6991: 						   'domainid');
1.324     albertel 6992:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6993:     $r->print(<<UPLOAD);
                   6994: <script type="text/javascript" language="javascript">
                   6995:     function checkUpload(formname) {
                   6996: 	if (formname.upfile.value == "") {
                   6997: 	    alert("Please use the browse button to select a file from your local directory.");
                   6998: 	    return false;
                   6999: 	}
                   7000: 	formname.submit();
                   7001:     }
                   7002: </script>
                   7003: 
                   7004: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7005: $default_form_data
1.181     albertel 7006: <table>
                   7007: <tr><td>$select_link </td></tr>
                   7008: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7009: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7010: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7011: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7012: </table>
1.157     albertel 7013: <input name='command' value='scantronupload_save' type='hidden' />
                   7014: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7015: </form>
                   7016: UPLOAD
                   7017:     return '';
                   7018: }
                   7019: 
1.423     albertel 7020: =pod
                   7021: 
                   7022: =item scantron_upload_scantron_data_save
                   7023: 
                   7024:    Adds a provided bubble information data file to the course if user
                   7025:    has the correct privileges to do so.  
                   7026: 
                   7027: =cut
                   7028: 
1.157     albertel 7029: sub scantron_upload_scantron_data_save {
                   7030:     my($r)=@_;
1.324     albertel 7031:     my ($symb)=&get_symb($r,1);
1.182     albertel 7032:     my $doanotherupload=
                   7033: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7034: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7035: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7036: 	'</form>'."\n";
1.257     albertel 7037:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7038: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7039: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7040: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7041: 	if ($symb) {
1.324     albertel 7042: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7043: 	} else {
                   7044: 	    $r->print($doanotherupload);
                   7045: 	}
1.162     albertel 7046: 	return '';
                   7047:     }
1.257     albertel 7048:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7049:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7050:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7051:     #FIXME
                   7052:     #copied from lonnet::userfileupload()
                   7053:     #make that function able to target a specified course
                   7054:     # Replace Windows backslashes by forward slashes
                   7055:     $fname=~s/\\/\//g;
                   7056:     # Get rid of everything but the actual filename
                   7057:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7058:     # Replace spaces by underscores
                   7059:     $fname=~s/\s+/\_/g;
                   7060:     # Replace all other weird characters by nothing
                   7061:     $fname=~s/[^\w\.\-]//g;
                   7062:     # See if there is anything left
                   7063:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7064:     my $uploadedfile=$fname;
1.157     albertel 7065:     $fname='scantron_orig_'.$fname;
1.257     albertel 7066:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7067: 	$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 7068:     } else {
1.275     albertel 7069: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7070: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7071: 	    $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 7072: 	} else {
1.398     albertel 7073: 	    $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 7074: 	}
                   7075:     }
1.174     albertel 7076:     if ($symb) {
1.209     ng       7077: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7078:     } else {
1.182     albertel 7079: 	$r->print($doanotherupload);
1.174     albertel 7080:     }
1.157     albertel 7081:     return '';
                   7082: }
                   7083: 
1.423     albertel 7084: =pod
                   7085: 
                   7086: =item valid_file
                   7087: 
1.424     albertel 7088:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7089: 
                   7090: =cut
                   7091: 
1.202     albertel 7092: sub valid_file {
                   7093:     my ($requested_file)=@_;
                   7094:     foreach my $filename (sort(&scantron_filenames())) {
                   7095: 	if ($requested_file eq $filename) { return 1; }
                   7096:     }
                   7097:     return 0;
                   7098: }
                   7099: 
1.423     albertel 7100: =pod
                   7101: 
                   7102: =item scantron_download_scantron_data
                   7103: 
                   7104:    Shows a list of the three internal files (original, corrected,
                   7105:    skipped) for a specific bubble sheet data file that exists in the
                   7106:    course.
                   7107: 
                   7108: =cut
                   7109: 
1.202     albertel 7110: sub scantron_download_scantron_data {
                   7111:     my ($r)=@_;
1.324     albertel 7112:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7113:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7114:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7115:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7116:     if (! &valid_file($file)) {
                   7117: 	$r->print(<<ERROR);
                   7118: 	<p>
                   7119: 	    The requested file name was invalid.
                   7120:         </p>
                   7121: ERROR
1.324     albertel 7122: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7123: 	return;
                   7124:     }
                   7125:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7126:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7127:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7128:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7129:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7130:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7131:     $r->print(<<DOWNLOAD);
                   7132:     <p>
                   7133: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7134:     </p>
                   7135:     <p>
                   7136: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7137:     </p>
                   7138:     <p>
                   7139: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7140:     </p>
                   7141: DOWNLOAD
1.324     albertel 7142:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7143:     return '';
                   7144: }
1.157     albertel 7145: 
1.423     albertel 7146: =pod
                   7147: 
                   7148: =back
                   7149: 
                   7150: =cut
                   7151: 
1.75      albertel 7152: #-------- end of section for handling grading scantron forms -------
                   7153: #
                   7154: #-------------------------------------------------------------------
                   7155: 
1.72      ng       7156: #-------------------------- Menu interface -------------------------
                   7157: #
                   7158: #--- Show a Grading Menu button - Calls the next routine ---
                   7159: sub show_grading_menu_form {
1.324     albertel 7160:     my ($symb)=@_;
1.125     ng       7161:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7162: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7163: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7164: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7165: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7166: 	'</form>'."\n";
                   7167:     return $result;
                   7168: }
                   7169: 
1.77      ng       7170: # -- Retrieve choices for grading form
                   7171: sub savedState {
                   7172:     my %savedState = ();
1.257     albertel 7173:     if ($env{'form.saveState'}) {
                   7174: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7175: 	    my ($key,$value) = split(/=/,$_,2);
                   7176: 	    $savedState{$key} = $value;
                   7177: 	}
                   7178:     }
                   7179:     return \%savedState;
                   7180: }
1.76      ng       7181: 
1.443     banghart 7182: sub grading_menu {
                   7183:     my ($request) = @_;
                   7184:     my ($symb)=&get_symb($request);
                   7185:     if (!$symb) {return '';}
                   7186:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7187:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7188: 
                   7189:     #
                   7190:     # Define menu data
1.444     banghart 7191:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7192:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7193:     $request->print($table);
1.443     banghart 7194:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7195:                   'handgrade'=>$hdgrade,
                   7196:                   'probTitle'=>$probTitle,
                   7197:                   'command'=>'submit_options',
                   7198:                   'saveState'=>"",
                   7199:                   'gradingMenu'=>1,
                   7200:                   'showgrading'=>"yes");
                   7201:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7202:     my @menu = ({ url => $url,
                   7203:                      name => &mt('Manual Grading/View Submissions'),
                   7204:                      short_description => 
                   7205:     &mt('Start the process of hand grading submissions.'),
                   7206:                  });
                   7207:     $fields{'command'} = 'csvform';
                   7208:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7209:     push (@menu, { url => $url,
                   7210:                    name => &mt('Upload Scores'),
                   7211:                    short_description => 
                   7212:             &mt('Specify a file containing the class scores for current resource.')});
                   7213:     $fields{'command'} = 'processclicker';
                   7214:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7215:     push (@menu, { url => $url,
                   7216:                    name => &mt('Process Clicker'),
                   7217:                    short_description => 
                   7218:             &mt('Specify a file containing the clicker information for this resource.')});
                   7219:     $fields{'command'} = 'scantron_selectphase';
                   7220:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7221:     push (@menu, { url => $url,
                   7222:                    name => &mt('Grade Scantron Forms'),
                   7223:                    short_description => 
                   7224:             &mt('')});
                   7225:     $fields{'command'} = 'verify';
                   7226:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7227:     push (@menu, { url => "",
                   7228:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7229:                    name => &mt('Verify Receipt'),
                   7230:                    short_description => 
                   7231:             &mt('')});
                   7232:     $fields{'command'} = 'manage';
                   7233:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7234:     push (@menu, { url => $url,
                   7235:                    name => &mt('Manage Access Times'),
                   7236:                    short_description => 
                   7237:             &mt('')});
                   7238:     $fields{'command'} = 'view';
                   7239:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7240:     push (@menu, { url => $url,
                   7241:                    name => &mt('View Saved CODEs'),
                   7242:                    short_description => 
                   7243:             &mt('')});
                   7244: 
                   7245:     #
                   7246:     # Create the menu
                   7247:     my $Str;
1.444     banghart 7248:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7249:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7250:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7251:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7252: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7253: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7254: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7255: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7256: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7257: 
1.443     banghart 7258:     foreach my $menudata (@menu) {
1.445     banghart 7259:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7260:             $Str .='    <h3><a '.
                   7261:                 $menudata->{'jscript'}.
                   7262:                 ' href="'.
                   7263:                 $menudata->{'url'}.'" >'.
                   7264:                 $menudata->{'name'}."</a></h3>\n";
                   7265:         } else {
                   7266:             $Str .='    <h3><a '.
                   7267:                 $menudata->{'jscript'}.
1.446     banghart 7268:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7269:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7270:             $Str .= ('&nbsp;'x8).
                   7271:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7272:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7273:         }
1.443     banghart 7274:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7275:             "\n";
                   7276:     }
                   7277:     $Str .="</dl>\n";
1.444     banghart 7278:     $Str .="</form>\n";
1.443     banghart 7279:     $request->print(<<GRADINGMENUJS);
                   7280: <script type="text/javascript" language="javascript">
                   7281:     function checkChoice(formname,val,cmdx) {
                   7282: 	if (val <= 2) {
                   7283: 	    var cmd = radioSelection(formname.radioChoice);
                   7284: 	    var cmdsave = cmd;
                   7285: 	} else {
                   7286: 	    cmd = cmdx;
                   7287: 	    cmdsave = 'submission';
                   7288: 	}
                   7289: 	formname.command.value = cmd;
                   7290: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7291: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7292: 	if (val < 5) formname.submit();
                   7293: 	if (val == 5) {
                   7294: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7295: 	    formname.submit();
                   7296: 	}
                   7297: 	if (val < 7) formname.submit();
                   7298:     }
1.445     banghart 7299:     function checkChoice2(formname,val,cmdx) {
                   7300: 	if (val <= 2) {
                   7301: 	    var cmd = radioSelection(formname.radioChoice);
                   7302: 	    var cmdsave = cmd;
                   7303: 	} else {
                   7304: 	    cmd = cmdx;
                   7305: 	    cmdsave = 'submission';
                   7306: 	}
                   7307: 	formname.command.value = cmd;
                   7308: 	if (val < 5) formname.submit();
                   7309: 	if (val == 5) {
                   7310: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7311: 	    formname.submit();
                   7312: 	}
                   7313: 	if (val < 7) formname.submit();
                   7314:     }
1.443     banghart 7315: 
                   7316:     function checkReceiptNo(formname,nospace) {
                   7317: 	var receiptNo = formname.receipt.value;
                   7318: 	var checkOpt = false;
                   7319: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7320: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7321: 	if (checkOpt) {
                   7322: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7323: 	    formname.receipt.value = "";
                   7324: 	    formname.receipt.focus();
                   7325: 	    return false;
                   7326: 	}
                   7327: 	return true;
                   7328:     }
                   7329: </script>
                   7330: GRADINGMENUJS
                   7331:     &commonJSfunctions($request);
                   7332:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7333:     $result.=$table;
                   7334:     my (undef,$sections) = &getclasslist('all','0');
                   7335:     my $savedState = &savedState();
                   7336:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7337:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7338:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7339:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7340: 
                   7341:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7342: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7343: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7344: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7345: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7346: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7347: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7348: 
                   7349:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7350: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7351: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7352: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7353: 
                   7354:     $result.='<table width="100%" border="0">';
                   7355:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7356:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7357: #    $result.='<td>Groups</td>';
                   7358:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7359:     $result.='</tr>';
                   7360:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7361: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7362:     if (ref($sections)) {
                   7363: 	foreach (sort (@$sections)) {
                   7364: 	    $result.='<option value="'.$_.'" '.
                   7365: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7366: 	}
                   7367:     }
                   7368:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7369:     return $Str;    
                   7370: }
                   7371: 
                   7372: 
                   7373: #--- Displays the submissions first page -------
                   7374: sub submit_options {
1.72      ng       7375:     my ($request) = @_;
1.324     albertel 7376:     my ($symb)=&get_symb($request);
1.72      ng       7377:     if (!$symb) {return '';}
1.76      ng       7378:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7379: 
                   7380:     $request->print(<<GRADINGMENUJS);
                   7381: <script type="text/javascript" language="javascript">
1.116     ng       7382:     function checkChoice(formname,val,cmdx) {
                   7383: 	if (val <= 2) {
                   7384: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7385: 	    var cmdsave = cmd;
1.116     ng       7386: 	} else {
                   7387: 	    cmd = cmdx;
1.118     ng       7388: 	    cmdsave = 'submission';
1.116     ng       7389: 	}
                   7390: 	formname.command.value = cmd;
1.118     ng       7391: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7392: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7393: 	if (val < 5) formname.submit();
                   7394: 	if (val == 5) {
1.72      ng       7395: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7396: 	    formname.submit();
                   7397: 	}
1.238     albertel 7398: 	if (val < 7) formname.submit();
1.72      ng       7399:     }
                   7400: 
                   7401:     function checkReceiptNo(formname,nospace) {
                   7402: 	var receiptNo = formname.receipt.value;
                   7403: 	var checkOpt = false;
                   7404: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7405: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7406: 	if (checkOpt) {
                   7407: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7408: 	    formname.receipt.value = "";
                   7409: 	    formname.receipt.focus();
                   7410: 	    return false;
                   7411: 	}
                   7412: 	return true;
                   7413:     }
                   7414: </script>
                   7415: GRADINGMENUJS
1.118     ng       7416:     &commonJSfunctions($request);
1.398     albertel 7417:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7418:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7419:     $result.=$table;
1.76      ng       7420:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7421:     my $savedState = &savedState();
1.118     ng       7422:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7423:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7424:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7425:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7426: 
                   7427:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7428: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7429: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7430: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7431: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7432: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7433: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7434: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7435: 
1.446     banghart 7436:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7437: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7438: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7439: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7440: 
1.326     albertel 7441:     $result.='<table width="100%" border="0">';
1.442     banghart 7442:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7443:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7444:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7445:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7446:     $result.='</tr>';
1.116     ng       7447:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7448: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7449:     if (ref($sections)) {
1.155     albertel 7450: 	foreach (sort (@$sections)) {
                   7451: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7452: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7453: 	}
1.116     ng       7454:     }
1.401     albertel 7455:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7456:     $result.= '</td><td>'."\n";
                   7457:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7458:     $result.='</td><td>'."\n";
                   7459:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7460: 
1.116     ng       7461:     $result.='</td></tr>';
                   7462: 
1.442     banghart 7463:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7464: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7465: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7466: 	'</label> <select name="submitonly">'.
1.145     albertel 7467: 	'<option value="yes" '.
1.401     albertel 7468: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7469: 	'<option value="queued" '.
1.401     albertel 7470: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7471: 	'<option value="graded" '.
1.401     albertel 7472: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7473: 	'<option value="incorrect" '.
1.401     albertel 7474: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7475: 	'<option value="all" '.
1.401     albertel 7476: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7477: 
1.442     banghart 7478:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7479: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7480: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7481: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7482: 
1.442     banghart 7483:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7484: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7485: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7486: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7487: 
1.442     banghart 7488:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7489: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7490: 	'</td></tr></table>'."\n";
                   7491: 
1.446     banghart 7492:     $result.='</td>'; #<td valign="top">';
1.116     ng       7493: 
1.446     banghart 7494: #    $result.='<table width="100%" border="0">';
                   7495: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7496: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7497: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7498: #
                   7499: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7500: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7501: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7502: #
                   7503: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7504: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7505: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7506: #
                   7507: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7508: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7509: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7510: #	    ' '.&mt('receipt').': '.
                   7511: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7512: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7513: #	    '</td></tr>'."\n";
                   7514: #    } 
                   7515: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7516: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7517: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7518: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7519: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7520: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7521: #
                   7522: #    $result.='</table>'."\n".'</td>';
                   7523:     $result.= '</tr></table>'."\n".
1.401     albertel 7524: 	'</td></tr></table></form>'."\n";
1.44      ng       7525:     return $result;
1.2       albertel 7526: }
                   7527: 
1.285     albertel 7528: sub reset_perm {
                   7529:     undef(%perm);
                   7530: }
                   7531: 
                   7532: sub init_perm {
                   7533:     &reset_perm();
1.300     albertel 7534:     foreach my $test_perm ('vgr','mgr','opa') {
                   7535: 
                   7536: 	my $scope = $env{'request.course.id'};
                   7537: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7538: 
                   7539: 	    $scope .= '/'.$env{'request.course.sec'};
                   7540: 	    if ( $perm{$test_perm}=
                   7541: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7542: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7543: 	    } else {
                   7544: 		delete($perm{$test_perm});
                   7545: 	    }
1.285     albertel 7546: 	}
                   7547:     }
                   7548: }
                   7549: 
1.400     www      7550: sub gather_clicker_ids {
1.408     albertel 7551:     my %clicker_ids;
1.400     www      7552: 
                   7553:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7554: 
                   7555:     # Set up a couple variables.
1.407     albertel 7556:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7557:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7558:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7559: 
1.407     albertel 7560:     foreach my $student (keys(%$classlist)) {
1.438     www      7561:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7562:         my $username = $classlist->{$student}->[$username_idx];
                   7563:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7564:         my $clickers =
1.408     albertel 7565: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7566:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7567:             $id=~s/^[\#0]+//;
1.421     www      7568:             $id=~s/[\-\:]//g;
1.407     albertel 7569:             if (exists($clicker_ids{$id})) {
1.408     albertel 7570: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7571:             } else {
1.408     albertel 7572: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7573:             }
                   7574:         }
                   7575:     }
1.407     albertel 7576:     return %clicker_ids;
1.400     www      7577: }
                   7578: 
1.402     www      7579: sub gather_adv_clicker_ids {
1.408     albertel 7580:     my %clicker_ids;
1.402     www      7581:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7582:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7583:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7584:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7585:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7586:             my ($puname,$pudom)=split(/\:/,$person);
                   7587:             my $clickers =
1.408     albertel 7588: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7589:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7590: 		$id=~s/^[\#0]+//;
1.421     www      7591:                 $id=~s/[\-\:]//g;
1.408     albertel 7592: 		if (exists($clicker_ids{$id})) {
                   7593: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7594: 		} else {
                   7595: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7596: 		}
1.405     www      7597:             }
1.402     www      7598:         }
                   7599:     }
1.407     albertel 7600:     return %clicker_ids;
1.402     www      7601: }
                   7602: 
1.413     www      7603: sub clicker_grading_parameters {
                   7604:     return ('gradingmechanism' => 'scalar',
                   7605:             'upfiletype' => 'scalar',
                   7606:             'specificid' => 'scalar',
                   7607:             'pcorrect' => 'scalar',
                   7608:             'pincorrect' => 'scalar');
                   7609: }
                   7610: 
1.400     www      7611: sub process_clicker {
                   7612:     my ($r)=@_;
                   7613:     my ($symb)=&get_symb($r);
                   7614:     if (!$symb) {return '';}
                   7615:     my $result=&checkforfile_js();
                   7616:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7617:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7618:     $result.=$table;
                   7619:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7620:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7621:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7622:         '.</b></td></tr>'."\n";
                   7623:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7624: # Attempt to restore parameters from last session, set defaults if not present
                   7625:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7626:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7627:                                                  \%Saveable_Parameters);
                   7628:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7629:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7630:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7631:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7632: 
                   7633:     my %checked;
                   7634:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7635:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7636:           $checked{$gradingmechanism}="checked='checked'";
                   7637:        }
                   7638:     }
                   7639: 
1.400     www      7640:     my $upload=&mt("Upload File");
                   7641:     my $type=&mt("Type");
1.402     www      7642:     my $attendance=&mt("Award points just for participation");
                   7643:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7644:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7645:     my $pcorrect=&mt("Percentage points for correct solution");
                   7646:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7647:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7648: 						   ('iclicker' => 'i>clicker',
                   7649:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7650:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7651:     $result.=<<ENDUPFORM;
1.402     www      7652: <script type="text/javascript">
                   7653: function sanitycheck() {
                   7654: // Accept only integer percentages
                   7655:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7656:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7657: // Find out grading choice
                   7658:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7659:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7660:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7661:       }
                   7662:    }
                   7663: // By default, new choice equals user selection
                   7664:    newgradingchoice=gradingchoice;
                   7665: // Not good to give more points for false answers than correct ones
                   7666:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7667:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7668:    }
                   7669: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7670:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7671:       document.forms.gradesupload.pcorrect.value=100;
                   7672:       document.forms.gradesupload.pincorrect.value=100;
                   7673:    }
                   7674: // If the values are different, cannot be attendance only
                   7675:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7676:        (gradingchoice=='attendance')) {
                   7677:        newgradingchoice='personnel';
                   7678:    }
                   7679: // Change grading choice to new one
                   7680:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7681:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7682:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7683:       } else {
                   7684:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7685:       }
                   7686:    }
                   7687: // Remember the old state
                   7688:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7689: }
                   7690: </script>
1.400     www      7691: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7692: <input type="hidden" name="symb" value="$symb" />
                   7693: <input type="hidden" name="command" value="processclickerfile" />
                   7694: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7695: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7696: <input type="file" name="upfile" size="50" />
                   7697: <br /><label>$type: $selectform</label>
1.451     albertel 7698: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7699: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7700: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7701: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7702: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7703: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7704: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7705: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7706: </form>
                   7707: ENDUPFORM
                   7708:     $result.='</td></tr></table>'."\n".
                   7709:              '</td></tr></table><br /><br />'."\n";
                   7710:     $result.=&show_grading_menu_form($symb);
                   7711:     return $result;
                   7712: }
                   7713: 
                   7714: sub process_clicker_file {
                   7715:     my ($r)=@_;
                   7716:     my ($symb)=&get_symb($r);
                   7717:     if (!$symb) {return '';}
1.413     www      7718: 
                   7719:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7720:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7721:                                               \%Saveable_Parameters);
                   7722: 
1.400     www      7723:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7724:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7725: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7726: 	return $result.&show_grading_menu_form($symb);
1.404     www      7727:     }
1.407     albertel 7728:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7729:     my %correct_ids;
1.404     www      7730:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7731: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7732:     }
                   7733:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7734: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7735: 	   $correct_id=~tr/a-z/A-Z/;
                   7736: 	   $correct_id=~s/\s//gs;
                   7737: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7738:            $correct_id=~s/[\-\:]//g;
1.414     www      7739:            if ($correct_id) {
                   7740: 	      $correct_ids{$correct_id}='specified';
                   7741:            }
                   7742:         }
1.400     www      7743:     }
1.404     www      7744:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7745: 	$result.=&mt('Score based on attendance only');
1.404     www      7746:     } else {
1.408     albertel 7747: 	my $number=0;
1.411     www      7748: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7749: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7750: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7751: 	    if ($correct_ids{$id} eq 'specified') {
                   7752: 		$result.=&mt('specified');
                   7753: 	    } else {
                   7754: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7755: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7756: 	    }
                   7757: 	    $number++;
                   7758: 	}
1.411     www      7759:         $result.="</p>\n";
1.408     albertel 7760: 	if ($number==0) {
                   7761: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7762: 	    return $result.&show_grading_menu_form($symb);
                   7763: 	}
1.404     www      7764:     }
1.405     www      7765:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7766:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7767: 		     '<span class="LC_error">',
                   7768: 		     '</span>',
                   7769: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7770:         return $result.&show_grading_menu_form($symb);
                   7771:     }
1.410     www      7772: 
                   7773: # Were able to get all the info needed, now analyze the file
                   7774: 
1.411     www      7775:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7776:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7777:     my $heading=&mt('Scanning clicker file');
                   7778:     $result.=(<<ENDHEADER);
                   7779: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7780: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7781: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7782: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7783: <input type="hidden" name="symb" value="$symb" />
                   7784: <input type="hidden" name="command" value="assignclickergrades" />
                   7785: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7786: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7787: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7788: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7789: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7790: ENDHEADER
1.408     albertel 7791:     my %responses;
                   7792:     my @questiontitles;
1.405     www      7793:     my $errormsg='';
                   7794:     my $number=0;
                   7795:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7796: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7797:     }
1.419     www      7798:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7799:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7800:     }
1.411     www      7801:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7802:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7803:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7804:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7805:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7806:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7807:              '<br />';
1.414     www      7808: # Remember Question Titles
                   7809: # FIXME: Possibly need delimiter other than ":"
                   7810:     for (my $i=0;$i<$number;$i++) {
                   7811:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7812:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7813:     }
1.411     www      7814:     my $correct_count=0;
                   7815:     my $student_count=0;
                   7816:     my $unknown_count=0;
1.414     www      7817: # Match answers with usernames
                   7818: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7819:     foreach my $id (keys(%responses)) {
1.410     www      7820:        if ($correct_ids{$id}) {
1.414     www      7821:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7822:           $correct_count++;
1.410     www      7823:        } elsif ($clicker_ids{$id}) {
1.437     www      7824:           if ($clicker_ids{$id}=~/\,/) {
                   7825: # More than one user with the same clicker!
                   7826:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7827:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7828:                            "<select name='multi".$id."'>";
                   7829:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7830:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7831:              }
                   7832:              $result.='</select>';
                   7833:              $unknown_count++;
                   7834:           } else {
                   7835: # Good: found one and only one user with the right clicker
                   7836:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7837:              $student_count++;
                   7838:           }
1.410     www      7839:        } else {
1.411     www      7840:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7841:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7842:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7843:                    "\n".&mt("Domain").": ".
                   7844:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7845:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7846:           $unknown_count++;
1.410     www      7847:        }
1.405     www      7848:     }
1.412     www      7849:     $result.='<hr />'.
                   7850:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7851:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7852:        if ($correct_count==0) {
                   7853:           $errormsg.="Found no correct answers answers for grading!";
                   7854:        } elsif ($correct_count>1) {
1.414     www      7855:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7856:        }
                   7857:     }
1.428     www      7858:     if ($number<1) {
                   7859:        $errormsg.="Found no questions.";
                   7860:     }
1.412     www      7861:     if ($errormsg) {
                   7862:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7863:     } else {
                   7864:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7865:     }
                   7866:     $result.='</form></td></tr></table>'."\n".
1.410     www      7867:              '</td></tr></table><br /><br />'."\n";
1.404     www      7868:     return $result.&show_grading_menu_form($symb);
1.400     www      7869: }
                   7870: 
1.405     www      7871: sub iclicker_eval {
1.406     www      7872:     my ($questiontitles,$responses)=@_;
1.405     www      7873:     my $number=0;
                   7874:     my $errormsg='';
                   7875:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7876:         my %components=&Apache::loncommon::record_sep($line);
                   7877:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7878: 	if ($entries[0] eq 'Question') {
                   7879: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7880: 		$$questiontitles[$number]=$entries[$i];
                   7881: 		$number++;
                   7882: 	    }
                   7883: 	}
                   7884: 	if ($entries[0]=~/^\#/) {
                   7885: 	    my $id=$entries[0];
                   7886: 	    my @idresponses;
                   7887: 	    $id=~s/^[\#0]+//;
                   7888: 	    for (my $i=0;$i<$number;$i++) {
                   7889: 		my $idx=3+$i*6;
                   7890: 		push(@idresponses,$entries[$idx]);
                   7891: 	    }
                   7892: 	    $$responses{$id}=join(',',@idresponses);
                   7893: 	}
1.405     www      7894:     }
                   7895:     return ($errormsg,$number);
                   7896: }
                   7897: 
1.419     www      7898: sub interwrite_eval {
                   7899:     my ($questiontitles,$responses)=@_;
                   7900:     my $number=0;
                   7901:     my $errormsg='';
1.420     www      7902:     my $skipline=1;
                   7903:     my $questionnumber=0;
                   7904:     my %idresponses=();
1.419     www      7905:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7906:         my %components=&Apache::loncommon::record_sep($line);
                   7907:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7908:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7909:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7910:         next if $skipline;
                   7911:         if ($entries[0]!=$questionnumber) {
                   7912:            $questionnumber=$entries[0];
                   7913:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7914:            $number++;
1.419     www      7915:         }
1.420     www      7916:         my $id=$entries[4];
                   7917:         $id=~s/^[\#0]+//;
1.421     www      7918:         $id=~s/^v\d*\://i;
                   7919:         $id=~s/[\-\:]//g;
1.420     www      7920:         $idresponses{$id}[$number]=$entries[6];
                   7921:     }
                   7922:     foreach my $id (keys %idresponses) {
                   7923:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7924:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7925:     }
                   7926:     return ($errormsg,$number);
                   7927: }
                   7928: 
1.414     www      7929: sub assign_clicker_grades {
                   7930:     my ($r)=@_;
                   7931:     my ($symb)=&get_symb($r);
                   7932:     if (!$symb) {return '';}
1.416     www      7933: # See which part we are saving to
                   7934:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7935: # FIXME: This should probably look for the first handgradeable part
                   7936:     my $part=$$partlist[0];
                   7937: # Start screen output
1.414     www      7938:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7939: 
1.414     www      7940:     my $heading=&mt('Assigning grades based on clicker file');
                   7941:     $result.=(<<ENDHEADER);
                   7942: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7943: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7944: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7945: ENDHEADER
                   7946: # Get correct result
                   7947: # FIXME: Possibly need delimiter other than ":"
                   7948:     my @correct=();
1.415     www      7949:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7950:     my $number=$env{'form.number'};
                   7951:     if ($gradingmechanism ne 'attendance') {
1.414     www      7952:        foreach my $key (keys(%env)) {
                   7953:           if ($key=~/^form\.correct\:/) {
                   7954:              my @input=split(/\,/,$env{$key});
                   7955:              for (my $i=0;$i<=$#input;$i++) {
                   7956:                  if (($correct[$i]) && ($input[$i]) &&
                   7957:                      ($correct[$i] ne $input[$i])) {
                   7958:                     $result.='<br /><span class="LC_warning">'.
                   7959:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7960:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7961:                  } elsif ($input[$i]) {
                   7962:                     $correct[$i]=$input[$i];
                   7963:                  }
                   7964:              }
                   7965:           }
                   7966:        }
1.415     www      7967:        for (my $i=0;$i<$number;$i++) {
1.414     www      7968:           if (!$correct[$i]) {
                   7969:              $result.='<br /><span class="LC_error">'.
                   7970:                       &mt('No correct result given for question "[_1]"!',
                   7971:                           $env{'form.question:'.$i}).'</span>';
                   7972:           }
                   7973:        }
                   7974:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7975:     }
                   7976: # Start grading
1.415     www      7977:     my $pcorrect=$env{'form.pcorrect'};
                   7978:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7979:     my $storecount=0;
1.415     www      7980:     foreach my $key (keys(%env)) {
1.420     www      7981:        my $user='';
1.415     www      7982:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7983:           $user=$1;
                   7984:        }
                   7985:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7986:           my $id=$1;
                   7987:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7988:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7989:           } elsif ($env{'form.multi'.$id}) {
                   7990:              $user=$env{'form.multi'.$id};
1.420     www      7991:           }
                   7992:        }
                   7993:        if ($user) { 
1.415     www      7994:           my @answer=split(/\,/,$env{$key});
                   7995:           my $sum=0;
                   7996:           for (my $i=0;$i<$number;$i++) {
                   7997:              if ($answer[$i]) {
                   7998:                 if ($gradingmechanism eq 'attendance') {
                   7999:                    $sum+=$pcorrect;
                   8000:                 } else {
                   8001:                    if ($answer[$i] eq $correct[$i]) {
                   8002:                       $sum+=$pcorrect;
                   8003:                    } else {
                   8004:                       $sum+=$pincorrect;
                   8005:                    }
                   8006:                 }
                   8007:              }
                   8008:           }
1.416     www      8009:           my $ave=$sum/(100*$number);
                   8010: # Store
                   8011:           my ($username,$domain)=split(/\:/,$user);
                   8012:           my %grades=();
                   8013:           $grades{"resource.$part.solved"}='correct_by_override';
                   8014:           $grades{"resource.$part.awarded"}=$ave;
                   8015:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8016:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8017:                                                  $env{'request.course.id'},
                   8018:                                                  $domain,$username);
                   8019:           if ($returncode ne 'ok') {
                   8020:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8021:           } else {
                   8022:              $storecount++;
                   8023:           }
1.415     www      8024:        }
                   8025:     }
                   8026: # We are done
1.416     www      8027:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8028:              '</td></tr></table>'."\n".
1.414     www      8029:              '</td></tr></table><br /><br />'."\n";
                   8030:     return $result.&show_grading_menu_form($symb);
                   8031: }
                   8032: 
1.1       albertel 8033: sub handler {
1.41      ng       8034:     my $request=$_[0];
1.447     foxr     8035: 
1.434     albertel 8036:     &reset_caches();
1.257     albertel 8037:     if ($env{'browser.mathml'}) {
1.141     www      8038: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8039:     } else {
1.141     www      8040: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8041:     }
                   8042:     $request->send_http_header;
1.44      ng       8043:     return '' if $request->header_only;
1.41      ng       8044:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8045:     my $symb=&get_symb($request,1);
1.160     albertel 8046:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8047:     my $command=$commands[0];
1.447     foxr     8048: 
1.160     albertel 8049:     if ($#commands > 0) {
                   8050: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8051:     }
1.447     foxr     8052: 
                   8053: 
1.353     albertel 8054:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8055:     if ($symb eq '' && $command eq '') {
1.257     albertel 8056: 	if ($env{'user.adv'}) {
                   8057: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8058: 		($env{'form.codethree'})) {
                   8059: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8060: 		    $env{'form.codethree'};
1.41      ng       8061: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8062: 		    &Apache::lonnet::checkin($token);
                   8063: 		if ($tsymb) {
1.137     albertel 8064: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8065: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8066: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8067: 					  ('grade_username' => $tuname,
                   8068: 					   'grade_domain' => $tudom,
                   8069: 					   'grade_courseid' => $tcrsid,
                   8070: 					   'grade_symb' => $tsymb)));
1.41      ng       8071: 		    } else {
1.45      ng       8072: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8073: 		    }
1.41      ng       8074: 		} else {
1.45      ng       8075: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8076: 		}
1.14      www      8077: 	    } else {
1.41      ng       8078: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8079: 	    }
                   8080: 	}
                   8081:     } else {
1.285     albertel 8082: 	&init_perm();
1.104     albertel 8083: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8084: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8085: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8086: 	    &pickStudentPage($request);
1.103     albertel 8087: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8088: 	    &displayPage($request);
1.104     albertel 8089: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8090: 	    &updateGradeByPage($request);
1.104     albertel 8091: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8092: 	    &processGroup($request);
1.104     albertel 8093: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8094: 	    $request->print(&grading_menu($request));
                   8095: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8096: 	    $request->print(&submit_options($request));
1.104     albertel 8097: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8098: 	    $request->print(&viewgrades($request));
1.104     albertel 8099: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8100: 	    $request->print(&processHandGrade($request));
1.106     albertel 8101: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8102: 	    $request->print(&editgrades($request));
1.106     albertel 8103: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8104: 	    $request->print(&verifyreceipt($request));
1.400     www      8105:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8106:             $request->print(&process_clicker($request));
                   8107:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8108:             $request->print(&process_clicker_file($request));
1.414     www      8109:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8110:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8111: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8112: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8113: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8114: 	    $request->print(&csvupload($request));
1.106     albertel 8115: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8116: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8117: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8118: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8119: 		$request->print(&csvuploadoptions($request));
1.41      ng       8120: 	    } else {
1.257     albertel 8121: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8122: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8123: 		} else {
1.257     albertel 8124: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8125: 		}
                   8126: 		$request->print(&csvuploadmap($request));
                   8127: 	    }
1.246     albertel 8128: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8129: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8130: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8131: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8132: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8133:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8134:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8135: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8136: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8137: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8138: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8139:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8140:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8141: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8142:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8143:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8144:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8145: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8146:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8147:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8148: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8149:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8150: 	} elsif ($command) {
1.157     albertel 8151: 	    $request->print("Access Denied ($command)");
1.26      albertel 8152: 	}
1.2       albertel 8153:     }
1.353     albertel 8154:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8155:     &reset_caches();
1.44      ng       8156:     return '';
                   8157: }
                   8158: 
1.1       albertel 8159: 1;
                   8160: 
1.13      albertel 8161: __END__;

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