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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.468   ! albertel    4: # $Id: grades.pm,v 1.464 2007/10/25 20:05:52 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.456     banghart   38: use Apache::lonpickcode;
1.55      matthew    39: use Apache::loncoursedata;
1.362     albertel   40: use Apache::lonmsg();
1.1       albertel   41: use Apache::Constants qw(:common);
1.167     sakharuk   42: use Apache::lonlocal;
1.386     raeburn    43: use Apache::lonenc;
1.170     albertel   44: use String::Similarity;
1.359     www        45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
1.435     foxr       49: 
                     50: my %perm=();
1.447     foxr       51: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       52:                                    # index is "symb.part_id"
                     53: 
1.447     foxr       54: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     55: 
                     56: # Save and restore the bubble lines array to the form env.
                     57: 
                     58: 
                     59: sub save_bubble_lines {
                     60:     foreach my $line (keys(%bubble_lines_per_response)) {
                     61: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     62: 	$env{"form.scantron.first_bubble_line.$line"} =
                     63: 	    $first_bubble_line{$line};
                     64:     }
                     65: }
                     66: 
                     67: 
                     68: sub restore_bubble_lines {
                     69:     my $line = 0;
                     70:     %bubble_lines_per_response = ();
                     71:     while ($env{"form.scantron.bubblelines.$line"}) {
                     72: 	my $value = $env{"form.scantron.bubblelines.$line"};
                     73: 	$bubble_lines_per_response{$line} = $value;
                     74: 	$first_bubble_line{$line}  =
                     75: 	    $env{"form.scantron.first_bubble_line.$line"};
                     76: 	$line++;
                     77:     }
                     78: 
                     79: }
                     80: 
                     81: #  Given the parsed scanline, get the response for 
                     82: #  'answer' number n:
                     83: 
                     84: sub get_response_bubbles {
                     85:     my ($parsed_line, $response)  = @_;
                     86: 
1.460     foxr       87: 
                     88:     my $bubble_line = $first_bubble_line{$response-1} +1;
                     89:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                     90:     
1.447     foxr       91:     my $selected = "";
                     92: 
                     93:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
1.461     foxr       94: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
1.447     foxr       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">'.
1.466     albertel  335: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    336: 	    '<tr valign="top"><td>'.$grayFont.&mt('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.466     albertel  355: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    356: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  357: 	    $middlerow.'</tr>'.
1.466     albertel  358: 	    '<tr valign="top"><td>'.$grayFont.&mt('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.466     albertel  368: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  369: 		} else {
1.466     albertel  370: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  371: 		}
                    372: 	    } else {
1.466     albertel  373: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  374: 	    }
1.398     albertel  375: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  376: 	}
                    377: 	return '<blockquote><table border="1">'.
1.466     albertel  378: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    379: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  380: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    381:     } elsif ($response eq 'essay') {
1.257     albertel  382: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        383: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  384: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    385: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        386: 
1.257     albertel  387: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    388: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    389: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    390: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    391: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    392: 	    $env{'form.'.$symb} = 1; # so that we don't have to read it from disk for multiple sub of the same prob.
1.122     ng        393: 	}
1.166     albertel  394: 	$answer =~ s-\n-<br />-g;
                    395: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  396:     } elsif ( $response eq 'organic') {
                    397: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    398: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    399: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    400: 	return $result;
1.335     albertel  401:     } elsif ( $response eq 'Task') {
                    402: 	if ( $answer eq 'SUBMITTED') {
                    403: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  404: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  405: 	    return $result;
                    406: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    407: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    408: 			       keys(%{$record}));
                    409: 	    return join('<br />',($version,@matches));
                    410: 			       
                    411: 			       
                    412: 	} else {
                    413: 	    my $result =
                    414: 		'<p>'
                    415: 		.&mt('Overall result: [_1]',
                    416: 		     $record->{$version."resource.$respid.$partid.status"})
                    417: 		.'</p>';
                    418: 	    
                    419: 	    $result .= '<ul>';
                    420: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    421: 			     keys(%{$record}));
                    422: 	    foreach my $grade (sort(@grade)) {
                    423: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    424: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    425: 				     $dim, $record->{$grade}).
                    426: 			  '</li>';
                    427: 	    }
                    428: 	    $result.='</ul>';
                    429: 	    return $result;
                    430: 	}
1.440     albertel  431:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    432: 	$answer = 
                    433: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    434: 							      $answer);
1.122     ng        435:     }
1.118     ng        436:     return $answer;
                    437: }
                    438: 
                    439: #-- A couple of common js functions
                    440: sub commonJSfunctions {
                    441:     my $request = shift;
                    442:     $request->print(<<COMMONJSFUNCTIONS);
                    443: <script type="text/javascript" language="javascript">
                    444:     function radioSelection(radioButton) {
                    445: 	var selection=null;
                    446: 	if (radioButton.length > 1) {
                    447: 	    for (var i=0; i<radioButton.length; i++) {
                    448: 		if (radioButton[i].checked) {
                    449: 		    return radioButton[i].value;
                    450: 		}
                    451: 	    }
                    452: 	} else {
                    453: 	    if (radioButton.checked) return radioButton.value;
                    454: 	}
                    455: 	return selection;
                    456:     }
                    457: 
                    458:     function pullDownSelection(selectOne) {
                    459: 	var selection="";
                    460: 	if (selectOne.length > 1) {
                    461: 	    for (var i=0; i<selectOne.length; i++) {
                    462: 		if (selectOne[i].selected) {
                    463: 		    return selectOne[i].value;
                    464: 		}
                    465: 	    }
                    466: 	} else {
1.138     albertel  467:             // only one value it must be the selected one
                    468: 	    return selectOne.value;
1.118     ng        469: 	}
                    470:     }
                    471: </script>
                    472: COMMONJSFUNCTIONS
                    473: }
                    474: 
1.44      ng        475: #--- Dumps the class list with usernames,list of sections,
                    476: #--- section, ids and fullnames for each user.
                    477: sub getclasslist {
1.449     banghart  478:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  479:     my @getsec;
1.450     banghart  480:     my @getgroup;
1.442     banghart  481:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  482:     if (!ref($getsec)) {
                    483: 	if ($getsec ne '' && $getsec ne 'all') {
                    484: 	    @getsec=($getsec);
                    485: 	}
                    486:     } else {
                    487: 	@getsec=@{$getsec};
                    488:     }
                    489:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  490:     if (!ref($getgroup)) {
                    491: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    492: 	    @getgroup=($getgroup);
                    493: 	}
                    494:     } else {
                    495: 	@getgroup=@{$getgroup};
                    496:     }
                    497:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  498: 
1.449     banghart  499:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  500:     # Bail out if we were unable to get the classlist
1.56      matthew   501:     return if (! defined($classlist));
1.449     banghart  502:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   503:     #
                    504:     my %sections;
                    505:     my %fullnames;
1.205     matthew   506:     foreach my $student (keys(%$classlist)) {
                    507:         my $end      = 
                    508:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    509:         my $start    = 
                    510:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    511:         my $id       = 
                    512:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    513:         my $section  = 
                    514:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    515:         my $fullname = 
                    516:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    517:         my $status   = 
                    518:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  519:         my $group   = 
                    520:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        521: 	# filter students according to status selected
1.442     banghart  522: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    523: 	    if (!($stu_status =~ $status)) {
1.450     banghart  524: 		delete($classlist->{$student});
1.76      ng        525: 		next;
                    526: 	    }
                    527: 	}
1.450     banghart  528: 	# filter students according to groups selected
1.453     banghart  529: 	my @stu_groups = split(/,/,$group);
1.450     banghart  530: 	if (@getgroup) {
                    531: 	    my $exclude = 1;
1.454     banghart  532: 	    foreach my $grp (@getgroup) {
                    533: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  534: 	            if ($stu_group eq $grp) {
                    535: 	                $exclude = 0;
                    536:     	            } 
1.450     banghart  537: 	        }
1.453     banghart  538:     	        if (($grp eq 'none') && !$group) {
                    539:         	        $exclude = 0;
                    540:         	}
1.450     banghart  541: 	    }
                    542: 	    if ($exclude) {
                    543: 	        delete($classlist->{$student});
                    544: 	    }
                    545: 	}
1.205     matthew   546: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  547: 	if (&canview($section)) {
1.291     albertel  548: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  549: 		$sections{$section}++;
1.450     banghart  550: 		if ($classlist->{$student}) {
                    551: 		    $fullnames{$student}=$fullname;
                    552: 		}
1.103     albertel  553: 	    } else {
1.205     matthew   554: 		delete($classlist->{$student});
1.103     albertel  555: 	    }
                    556: 	} else {
1.205     matthew   557: 	    delete($classlist->{$student});
1.103     albertel  558: 	}
1.44      ng        559:     }
                    560:     my %seen = ();
1.56      matthew   561:     my @sections = sort(keys(%sections));
                    562:     return ($classlist,\@sections,\%fullnames);
1.44      ng        563: }
                    564: 
1.103     albertel  565: sub canmodify {
                    566:     my ($sec)=@_;
                    567:     if ($perm{'mgr'}) {
                    568: 	if (!defined($perm{'mgr_section'})) {
                    569: 	    # can modify whole class
                    570: 	    return 1;
                    571: 	} else {
                    572: 	    if ($sec eq $perm{'mgr_section'}) {
                    573: 		#can modify the requested section
                    574: 		return 1;
                    575: 	    } else {
                    576: 		# can't modify the request section
                    577: 		return 0;
                    578: 	    }
                    579: 	}
                    580:     }
                    581:     #can't modify
                    582:     return 0;
                    583: }
                    584: 
                    585: sub canview {
                    586:     my ($sec)=@_;
                    587:     if ($perm{'vgr'}) {
                    588: 	if (!defined($perm{'vgr_section'})) {
                    589: 	    # can modify whole class
                    590: 	    return 1;
                    591: 	} else {
                    592: 	    if ($sec eq $perm{'vgr_section'}) {
                    593: 		#can modify the requested section
                    594: 		return 1;
                    595: 	    } else {
                    596: 		# can't modify the request section
                    597: 		return 0;
                    598: 	    }
                    599: 	}
                    600:     }
                    601:     #can't modify
                    602:     return 0;
                    603: }
                    604: 
1.44      ng        605: #--- Retrieve the grade status of a student for all the parts
                    606: sub student_gradeStatus {
1.324     albertel  607:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  608:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        609:     my %partstatus = ();
                    610:     foreach (@$partlist) {
1.128     ng        611: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        612: 	$status              = 'nothing' if ($status eq '');
                    613: 	$partstatus{$_}      = $status;
                    614: 	my $subkey           = "resource.$_.submitted_by";
                    615: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    616:     }
                    617:     return %partstatus;
                    618: }
                    619: 
1.45      ng        620: # hidden form and javascript that calls the form
                    621: # Use by verifyscript and viewgrades
                    622: # Shows a student's view of problem and submission
                    623: sub jscriptNform {
1.324     albertel  624:     my ($symb) = @_;
1.442     banghart  625:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        626:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    627: 	'    function viewOneStudent(user,domain) {'."\n".
                    628: 	'	document.onestudent.student.value = user;'."\n".
                    629: 	'	document.onestudent.userdom.value = domain;'."\n".
                    630: 	'	document.onestudent.submit();'."\n".
                    631: 	'    }'."\n".
                    632: 	'</script>'."\n";
                    633:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  634: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  635: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    636: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  637: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        638: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    639: 	'<input type="hidden" name="student" value="" />'."\n".
                    640: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    641: 	'</form>'."\n";
                    642:     return $jscript;
                    643: }
1.39      ng        644: 
1.447     foxr      645: 
                    646: 
1.315     bowersj2  647: # Given the score (as a number [0-1] and the weight) what is the final
                    648: # point value? This function will round to the nearest tenth, third,
                    649: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  650: sub compute_points {
1.315     bowersj2  651:     my ($score, $weight) = @_;
                    652:     
                    653:     my $tolerance = .00001;
                    654:     my $points = $score * $weight;
                    655: 
                    656:     # Check for nearness to 1/x.
                    657:     my $check_for_nearness = sub {
                    658:         my ($factor) = @_;
                    659:         my $num = ($points * $factor) + $tolerance;
                    660:         my $floored_num = floor($num);
1.316     albertel  661:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  662:             return $floored_num / $factor;
                    663:         }
                    664:         return $points;
                    665:     };
                    666: 
                    667:     $points = $check_for_nearness->(10);
                    668:     $points = $check_for_nearness->(3);
                    669:     $points = $check_for_nearness->(4);
                    670:     
                    671:     return $points;
                    672: }
                    673: 
1.44      ng        674: #------------------ End of general use routines --------------------
1.87      www       675: 
                    676: #
                    677: # Find most similar essay
                    678: #
                    679: 
                    680: sub most_similar {
1.426     albertel  681:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       682: 
                    683: # ignore spaces and punctuation
                    684: 
                    685:     $uessay=~s/\W+/ /gs;
                    686: 
1.282     www       687: # ignore empty submissions (occuring when only files are sent)
                    688: 
                    689:     unless ($uessay=~/\w+/) { return ''; }
                    690: 
1.87      www       691: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       692:     my $limit=0.6;
1.87      www       693:     my $sname='';
                    694:     my $sdom='';
                    695:     my $scrsid='';
                    696:     my $sessay='';
                    697: # go through all essays ...
1.426     albertel  698:     foreach my $tkey (keys(%$old_essays)) {
                    699: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       700: # ... except the same student
1.426     albertel  701:         next if (($tname eq $uname) && ($tdom eq $udom));
                    702: 	my $tessay=$old_essays->{$tkey};
                    703: 	$tessay=~s/\W+/ /gs;
1.87      www       704: # String similarity gives up if not even limit
1.426     albertel  705: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       706: # Found one
1.426     albertel  707: 	if ($tsimilar>$limit) {
                    708: 	    $limit=$tsimilar;
                    709: 	    $sname=$tname;
                    710: 	    $sdom=$tdom;
                    711: 	    $scrsid=$tcrsid;
                    712: 	    $sessay=$old_essays->{$tkey};
                    713: 	}
1.87      www       714:     }
1.88      www       715:     if ($limit>0.6) {
1.87      www       716:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    717:     } else {
                    718:        return ('','','','',0);
                    719:     }
                    720: }
                    721: 
1.44      ng        722: #-------------------------------------------------------------------
                    723: 
                    724: #------------------------------------ Receipt Verification Routines
1.45      ng        725: #
1.44      ng        726: #--- Check whether a receipt number is valid.---
                    727: sub verifyreceipt {
                    728:     my $request  = shift;
                    729: 
1.257     albertel  730:     my $courseid = $env{'request.course.id'};
1.184     www       731:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  732: 	$env{'form.receipt'};
1.44      ng        733:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  734:     my ($symb)   = &get_symb($request);
1.44      ng        735: 
1.398     albertel  736:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    737: 	$receipt.'</h3></span>'."\n".
                    738: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        739: 
                    740:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   741:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  742:     
                    743:     my $receiptparts=0;
1.390     albertel  744:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    745: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  746:     my $parts=['0'];
1.324     albertel  747:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  748:     foreach (sort 
                    749: 	     {
                    750: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    751: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    752: 		 }
                    753: 		 return $a cmp $b;
                    754: 	     } (keys(%$fullname))) {
1.44      ng        755: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  756: 	foreach my $part (@$parts) {
                    757: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    758: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    759: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  760: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  761: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    762: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    763: 		if ($receiptparts) {
                    764: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    765: 		}
                    766: 		$contents.='</tr>'."\n";
                    767: 		
                    768: 		$matches++;
                    769: 	    }
1.44      ng        770: 	}
                    771:     }
                    772:     if ($matches == 0) {
                    773: 	$string = $title.'No match found for the above receipt.';
                    774:     } else {
1.324     albertel  775: 	$string = &jscriptNform($symb).$title.
1.44      ng        776: 	    'The above receipt matches the following student'.
                    777: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    778: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    779: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    780: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    781: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  782: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    783: 	if ($receiptparts) {
                    784: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    785: 	}
                    786: 	$string.='</tr>'."\n".$contents.
1.44      ng        787: 	    '</table></td></tr></table>'."\n";
                    788:     }
1.324     albertel  789:     return $string.&show_grading_menu_form($symb);
1.44      ng        790: }
                    791: 
                    792: #--- This is called by a number of programs.
                    793: #--- Called from the Grading Menu - View/Grade an individual student
                    794: #--- Also called directly when one clicks on the subm button 
                    795: #    on the problem page.
1.30      ng        796: sub listStudents {
1.41      ng        797:     my ($request) = shift;
1.49      albertel  798: 
1.324     albertel  799:     my ($symb) = &get_symb($request);
1.257     albertel  800:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    801:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    802:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  803:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  804:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    805:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    806:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    807: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  808: 
1.398     albertel  809:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    810: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        811: 
1.324     albertel  812:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  813: 
1.45      ng        814:     $request->print(<<LISTJAVASCRIPT);
                    815: <script type="text/javascript" language="javascript">
1.110     ng        816:     function checkSelect(checkBox) {
                    817: 	var ctr=0;
                    818: 	var sense="";
                    819: 	if (checkBox.length > 1) {
                    820: 	    for (var i=0; i<checkBox.length; i++) {
                    821: 		if (checkBox[i].checked) {
                    822: 		    ctr++;
                    823: 		}
                    824: 	    }
                    825: 	    sense = "a student or group of students";
                    826: 	} else {
                    827: 	    if (checkBox.checked) {
                    828: 		ctr = 1;
                    829: 	    }
                    830: 	    sense = "the student";
                    831: 	}
                    832: 	if (ctr == 0) {
1.126     ng        833: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        834: 	    return false;
                    835: 	}
                    836: 	document.gradesub.submit();
                    837:     }
                    838: 
                    839:     function reLoadList(formname) {
1.112     ng        840: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        841: 	formname.command.value = 'submission';
                    842: 	formname.submit();
                    843:     }
1.45      ng        844: </script>
                    845: LISTJAVASCRIPT
                    846: 
1.118     ng        847:     &commonJSfunctions($request);
1.41      ng        848:     $request->print($result);
1.39      ng        849: 
1.401     albertel  850:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    851:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  852:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    853: 	"\n".$table.
1.401     albertel  854: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  855: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    856: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    857: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    858: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  859: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  860: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  861:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  862: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  863:     }
1.442     banghart  864:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    865:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  866:     $env{'form.Status'} = $saveStatus;
1.267     albertel  867:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    868: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    869: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  870: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    871:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    872:         '<option value="1">Whole Points</option>'.
                    873:         '<option value=".5">Half Points</option>'.
1.349     albertel  874:         '<option value=".25">Quarter Points</option>'.
                    875:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  876:         '</select>'.
1.432     banghart  877:         &build_section_inputs().
1.45      ng        878: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  879: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    880: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    881: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    882: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  883: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        884: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    885: 
1.257     albertel  886:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  887: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        888:     } else {
                    889: 	$gradeTable.='<b>Student Status:</b> '.
                    890: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    891:     }
1.112     ng        892: 
1.126     ng        893:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    894: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        895: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  896: 
                    897: # checkall buttons
                    898:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        899:     $gradeTable.='<input type="button" '."\n".
1.45      ng        900: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  901: 	'value="Next->" /> <br />'."\n";
                    902:     $gradeTable.=&check_buttons();
1.401     albertel  903:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.450     banghart  904:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.45      ng        905:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        906: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    907:     my $loop = 0;
                    908:     while ($loop < 2) {
1.126     ng        909: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  910: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  911: 	if ($env{'form.showgrading'} eq 'yes' 
                    912: 	    && $submitonly ne 'queued'
                    913: 	    && $submitonly ne 'all') {
1.110     ng        914: 	    foreach (sort(@$partlist)) {
1.324     albertel  915: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  916: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    917: 		    ' Status&nbsp;</b></td>';
1.110     ng        918: 	    }
1.301     albertel  919: 	} elsif ($submitonly eq 'queued') {
                    920: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        921: 	}
                    922: 	$loop++;
1.126     ng        923: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        924:     }
1.45      ng        925:     $gradeTable.='</tr>'."\n";
1.41      ng        926: 
1.45      ng        927:     my $ctr = 0;
1.294     albertel  928:     foreach my $student (sort 
                    929: 			 {
                    930: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    931: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    932: 			     }
                    933: 			     return $a cmp $b;
                    934: 			 }
                    935: 			 (keys(%$fullname))) {
1.41      ng        936: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  937: 
1.110     ng        938: 	my %status = ();
1.301     albertel  939: 
                    940: 	if ($submitonly eq 'queued') {
                    941: 	    my %queue_status = 
                    942: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    943: 							$udom,$uname);
                    944: 	    next if (!defined($queue_status{'gradingqueue'}));
                    945: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    946: 	}
                    947: 
                    948: 	if ($env{'form.showgrading'} eq 'yes' 
                    949: 	    && $submitonly ne 'queued'
                    950: 	    && $submitonly ne 'all') {
1.324     albertel  951: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  952: 	    my $submitted = 0;
1.164     albertel  953: 	    my $graded = 0;
1.248     albertel  954: 	    my $incorrect = 0;
1.110     ng        955: 	    foreach (keys(%status)) {
1.145     albertel  956: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  957: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    958: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    959: 		
1.110     ng        960: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    961: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  962: 		    $submitted = 0;
1.150     albertel  963: 		    my ($part)=split(/\./,$partid);
1.110     ng        964: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  965: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        966: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    967: 		}
1.41      ng        968: 	    }
1.248     albertel  969: 	    
1.156     albertel  970: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    971: 				     $submitonly eq 'incorrect' ||
                    972: 				     $submitonly eq 'graded'));
1.248     albertel  973: 	    next if (!$graded && ($submitonly eq 'graded'));
                    974: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        975: 	}
1.34      ng        976: 
1.45      ng        977: 	$ctr++;
1.249     albertel  978: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart  979:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel  980: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        981: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        982: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  983:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    984:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    985: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    986: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.452     banghart  987: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
1.110     ng        988: 
1.257     albertel  989: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        990: 		foreach (sort keys(%status)) {
                    991: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  992: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        993: 		}
1.41      ng        994: 	    }
1.126     ng        995: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        996: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        997: 	}
                    998:     }
1.110     ng        999:     if ($ctr%2 ==1) {
1.126     ng       1000: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1001: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1002: 		&& $submitonly ne 'queued'
                   1003: 		&& $submitonly ne 'all') {
1.110     ng       1004: 		foreach (@$partlist) {
                   1005: 		    $gradeTable.='<td>&nbsp;</td>';
                   1006: 		}
1.301     albertel 1007: 	    } elsif ($submitonly eq 'queued') {
                   1008: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1009: 	    }
                   1010: 	$gradeTable.='</tr>';
                   1011:     }
                   1012: 
1.249     albertel 1013:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng       1014: 	'<input type="button" '.
                   1015: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1016: 	'value="Next->" /></form>'."\n";
1.45      ng       1017:     if ($ctr == 0) {
1.96      albertel 1018: 	my $num_students=(scalar(keys(%$fullname)));
                   1019: 	if ($num_students eq 0) {
1.398     albertel 1020: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1021: 	} else {
1.171     albertel 1022: 	    my $submissions='submissions';
                   1023: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1024: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1025: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1026: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1027: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1028: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1029: 	}
1.46      ng       1030:     } elsif ($ctr == 1) {
                   1031: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1032:     }
1.324     albertel 1033:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1034:     $request->print($gradeTable);
1.44      ng       1035:     return '';
1.10      ng       1036: }
                   1037: 
1.44      ng       1038: #---- Called from the listStudents routine
1.249     albertel 1039: 
                   1040: sub check_script {
                   1041:     my ($form, $type)=@_;
                   1042:     my $chkallscript='<script type="text/javascript">
                   1043:     function checkall() {
                   1044:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1045:             ele = document.forms.'.$form.'.elements[i];
                   1046:             if (ele.name == "'.$type.'") {
                   1047:             document.forms.'.$form.'.elements[i].checked=true;
                   1048:                                        }
                   1049:         }
                   1050:     }
                   1051: 
                   1052:     function checksec() {
                   1053:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1054:             ele = document.forms.'.$form.'.elements[i];
                   1055:            string = document.forms.'.$form.'.chksec.value;
                   1056:            if
                   1057:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1058:               document.forms.'.$form.'.elements[i].checked=true;
                   1059:             }
                   1060:         }
                   1061:     }
                   1062: 
                   1063: 
                   1064:     function uncheckall() {
                   1065:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1066:             ele = document.forms.'.$form.'.elements[i];
                   1067:             if (ele.name == "'.$type.'") {
                   1068:             document.forms.'.$form.'.elements[i].checked=false;
                   1069:                                        }
                   1070:         }
                   1071:     }
                   1072: 
                   1073: </script>'."\n";
                   1074:     return $chkallscript;
                   1075: }
                   1076: 
                   1077: sub check_buttons {
                   1078:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1079:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1080:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1081:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1082:     return $buttons;
                   1083: }
                   1084: 
1.44      ng       1085: #     Displays the submissions for one student or a group of students
1.34      ng       1086: sub processGroup {
1.41      ng       1087:     my ($request)  = shift;
                   1088:     my $ctr        = 0;
1.155     albertel 1089:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1090:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1091: 
1.396     banghart 1092:     foreach my $student (@stuchecked) {
                   1093: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1094: 	$env{'form.student'}        = $uname;
                   1095: 	$env{'form.userdom'}        = $udom;
                   1096: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1097: 	&submission($request,$ctr,$total);
                   1098: 	$ctr++;
                   1099:     }
                   1100:     return '';
1.35      ng       1101: }
1.34      ng       1102: 
1.44      ng       1103: #------------------------------------------------------------------------------------
                   1104: #
                   1105: #-------------------------- Next few routines handles grading by student, essentially
                   1106: #                           handles essay response type problem/part
                   1107: #
                   1108: #--- Javascript to handle the submission page functionality ---
                   1109: sub sub_page_js {
                   1110:     my $request = shift;
                   1111:     $request->print(<<SUBJAVASCRIPT);
                   1112: <script type="text/javascript" language="javascript">
1.71      ng       1113:     function updateRadio(formname,id,weight) {
1.125     ng       1114: 	var gradeBox = formname["GD_BOX"+id];
                   1115: 	var radioButton = formname["RADVAL"+id];
                   1116: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1117: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1118: 	gradeBox.value = pts;
                   1119: 	var resetbox = false;
                   1120: 	if (isNaN(pts) || pts < 0) {
                   1121: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1122: 	    for (var i=0; i<radioButton.length; i++) {
                   1123: 		if (radioButton[i].checked) {
                   1124: 		    gradeBox.value = i;
                   1125: 		    resetbox = true;
                   1126: 		}
                   1127: 	    }
                   1128: 	    if (!resetbox) {
                   1129: 		formtextbox.value = "";
                   1130: 	    }
                   1131: 	    return;
1.44      ng       1132: 	}
1.71      ng       1133: 
                   1134: 	if (pts > weight) {
                   1135: 	    var resp = confirm("You entered a value ("+pts+
                   1136: 			       ") greater than the weight for the part. Accept?");
                   1137: 	    if (resp == false) {
1.125     ng       1138: 		gradeBox.value = oldpts;
1.71      ng       1139: 		return;
                   1140: 	    }
1.44      ng       1141: 	}
1.13      albertel 1142: 
1.71      ng       1143: 	for (var i=0; i<radioButton.length; i++) {
                   1144: 	    radioButton[i].checked=false;
                   1145: 	    if (pts == i && pts != "") {
                   1146: 		radioButton[i].checked=true;
                   1147: 	    }
                   1148: 	}
                   1149: 	updateSelect(formname,id);
1.125     ng       1150: 	formname["stores"+id].value = "0";
1.41      ng       1151:     }
1.5       albertel 1152: 
1.72      ng       1153:     function writeBox(formname,id,pts) {
1.125     ng       1154: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1155: 	if (checkSolved(formname,id) == 'update') {
                   1156: 	    gradeBox.value = pts;
                   1157: 	} else {
1.125     ng       1158: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1159: 	    gradeBox.value = oldpts;
1.125     ng       1160: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1161: 	    for (var i=0; i<radioButton.length; i++) {
                   1162: 		radioButton[i].checked=false;
1.72      ng       1163: 		if (i == oldpts) {
1.71      ng       1164: 		    radioButton[i].checked=true;
                   1165: 		}
                   1166: 	    }
1.41      ng       1167: 	}
1.125     ng       1168: 	formname["stores"+id].value = "0";
1.71      ng       1169: 	updateSelect(formname,id);
                   1170: 	return;
1.41      ng       1171:     }
1.44      ng       1172: 
1.71      ng       1173:     function clearRadBox(formname,id) {
                   1174: 	if (checkSolved(formname,id) == 'noupdate') {
                   1175: 	    updateSelect(formname,id);
                   1176: 	    return;
                   1177: 	}
1.125     ng       1178: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1179: 	for (var i=0; i<gradeSelect.length; i++) {
                   1180: 	    if (gradeSelect[i].selected) {
                   1181: 		var selectx=i;
                   1182: 	    }
                   1183: 	}
1.125     ng       1184: 	var stores = formname["stores"+id];
1.71      ng       1185: 	if (selectx == stores.value) { return };
1.125     ng       1186: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1187: 	gradeBox.value = "";
1.125     ng       1188: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1189: 	for (var i=0; i<radioButton.length; i++) {
                   1190: 	    radioButton[i].checked=false;
                   1191: 	}
                   1192: 	stores.value = selectx;
                   1193:     }
1.5       albertel 1194: 
1.71      ng       1195:     function checkSolved(formname,id) {
1.125     ng       1196: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1197: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1198: 	    if (!reply) {return "noupdate";}
1.120     ng       1199: 	    formname.overRideScore.value = 'yes';
1.41      ng       1200: 	}
1.71      ng       1201: 	return "update";
1.13      albertel 1202:     }
1.71      ng       1203: 
                   1204:     function updateSelect(formname,id) {
1.125     ng       1205: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1206: 	return;
1.41      ng       1207:     }
1.33      ng       1208: 
1.121     ng       1209: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1210:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1211: 	formname.gradeOpt.value = val;
1.71      ng       1212: 	if (val == "Save & Next") {
                   1213: 	    for (i=0;i<=total;i++) {
                   1214: 		for (j=0;j<parttot;j++) {
1.125     ng       1215: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1216: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1217: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1218: 			if (points == "") {
1.125     ng       1219: 			    var name = formname["name"+i].value;
1.129     ng       1220: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1221: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1222: 					       ", part "+partid+". Continue?");
1.71      ng       1223: 			    if (resp == false) {
1.125     ng       1224: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1225: 				return false;
                   1226: 			    }
                   1227: 			}
                   1228: 		    }
                   1229: 		    
                   1230: 		}
                   1231: 	    }
                   1232: 	    
                   1233: 	}
1.121     ng       1234: 	if (val == "Grade Student") {
                   1235: 	    formname.showgrading.value = "yes";
                   1236: 	    if (formname.Status.value == "") {
                   1237: 		formname.Status.value = "Active";
                   1238: 	    }
                   1239: 	    formname.studentNo.value = total;
                   1240: 	}
1.120     ng       1241: 	formname.submit();
                   1242:     }
                   1243: 
1.71      ng       1244: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1245:     function checkSubmitPage(formname,total) {
                   1246: 	noscore = new Array(100);
                   1247: 	var ptr = 0;
                   1248: 	for (i=1;i<total;i++) {
1.125     ng       1249: 	    var partid = formname["q_"+i].value;
1.127     ng       1250: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1251: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1252: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1253: 		if (points == "" && status != "correct_by_student") {
                   1254: 		    noscore[ptr] = i;
                   1255: 		    ptr++;
                   1256: 		}
                   1257: 	    }
                   1258: 	}
                   1259: 	if (ptr != 0) {
                   1260: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1261: 	    var prolist = "";
                   1262: 	    if (ptr == 1) {
                   1263: 		prolist = noscore[0];
                   1264: 	    } else {
                   1265: 		var i = 0;
                   1266: 		while (i < ptr-1) {
                   1267: 		    prolist += noscore[i]+", ";
                   1268: 		    i++;
                   1269: 		}
                   1270: 		prolist += "and "+noscore[i];
                   1271: 	    }
                   1272: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1273: 	    if (resp == false) {
                   1274: 		return false;
                   1275: 	    }
                   1276: 	}
1.45      ng       1277: 
1.71      ng       1278: 	formname.submit();
                   1279:     }
                   1280: </script>
                   1281: SUBJAVASCRIPT
                   1282: }
1.45      ng       1283: 
1.71      ng       1284: #--- javascript for essay type problem --
                   1285: sub sub_page_kw_js {
                   1286:     my $request = shift;
1.80      ng       1287:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1288:     &commonJSfunctions($request);
1.350     albertel 1289: 
1.351     albertel 1290:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1291:     <script text="text/javascript">
                   1292:     function checkInput() {
                   1293:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1294:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1295:       var usrctr = document.msgcenter.usrctr.value;
                   1296:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1297:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1298: 
                   1299:       var msgchk = "";
                   1300:       if (document.msgcenter.subchk.checked) {
                   1301:          msgchk = "msgsub,";
                   1302:       }
                   1303:       var includemsg = 0;
                   1304:       for (var i=1; i<=nmsg; i++) {
                   1305:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1306:           var frmmsg = document.msgcenter["msg"+i];
                   1307:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1308:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1309:           showflg.value = "1";
                   1310:           var chkbox = document.msgcenter["msgn"+i];
                   1311:           if (chkbox.checked) {
                   1312:              msgchk += "savemsg"+i+",";
                   1313:              includemsg = 1;
                   1314:           }
                   1315:       }
                   1316:       if (document.msgcenter.newmsgchk.checked) {
                   1317:          msgchk += "newmsg"+usrctr;
                   1318:          includemsg = 1;
                   1319:       }
                   1320:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1321:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1322:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1323:       includemsg.value = msgchk;
                   1324: 
                   1325:       self.close()
                   1326: 
                   1327:     }
                   1328:     </script>
                   1329: INNERJS
                   1330: 
1.351     albertel 1331:     my $inner_js_highlight_central=<<INNERJS;
                   1332:  <script type="text/javascript">
                   1333:     function updateChoice(flag) {
                   1334:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1335:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1336:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1337:       opener.document.SCORE.refresh.value = "on";
                   1338:       if (opener.document.SCORE.keywords.value!=""){
                   1339:          opener.document.SCORE.submit();
                   1340:       }
                   1341:       self.close()
                   1342:     }
                   1343: </script>
                   1344: INNERJS
                   1345: 
                   1346:     my $start_page_msg_central = 
                   1347:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1348: 				       {'js_ready'  => 1,
                   1349: 					'only_body' => 1,
                   1350: 					'bgcolor'   =>'#FFFFFF',});
                   1351:     my $end_page_msg_central = 
                   1352: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1353: 
                   1354: 
                   1355:     my $start_page_highlight_central = 
                   1356:         &Apache::loncommon::start_page('Highlight Central',
                   1357: 				       $inner_js_highlight_central,
1.350     albertel 1358: 				       {'js_ready'  => 1,
                   1359: 					'only_body' => 1,
                   1360: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1361:     my $end_page_highlight_central = 
1.350     albertel 1362: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1363: 
1.219     www      1364:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1365:     $docopen=~s/^document\.//;
1.71      ng       1366:     $request->print(<<SUBJAVASCRIPT);
                   1367: <script type="text/javascript" language="javascript">
1.45      ng       1368: 
1.44      ng       1369: //===================== Show list of keywords ====================
1.122     ng       1370:   function keywords(formname) {
                   1371:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1372:     if (nret==null) return;
1.122     ng       1373:     formname.keywords.value = nret;
1.44      ng       1374: 
1.122     ng       1375:     if (formname.keywords.value != "") {
1.128     ng       1376: 	formname.refresh.value = "on";
1.122     ng       1377: 	formname.submit();
1.44      ng       1378:     }
                   1379:     return;
                   1380:   }
                   1381: 
                   1382: //===================== Script to view submitted by ==================
                   1383:   function viewSubmitter(submitter) {
                   1384:     document.SCORE.refresh.value = "on";
                   1385:     document.SCORE.NCT.value = "1";
                   1386:     document.SCORE.unamedom0.value = submitter;
                   1387:     document.SCORE.submit();
                   1388:     return;
                   1389:   }
                   1390: 
                   1391: //===================== Script to add keyword(s) ==================
                   1392:   function getSel() {
                   1393:     if (document.getSelection) txt = document.getSelection();
                   1394:     else if (document.selection) txt = document.selection.createRange().text;
                   1395:     else return;
                   1396:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1397:     if (cleantxt=="") {
1.46      ng       1398: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1399: 	return;
                   1400:     }
                   1401:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1402:     if (nret==null) return;
1.127     ng       1403:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1404:     if (document.SCORE.keywords.value != "") {
1.127     ng       1405: 	document.SCORE.refresh.value = "on";
1.44      ng       1406: 	document.SCORE.submit();
                   1407:     }
                   1408:     return;
                   1409:   }
                   1410: 
                   1411: //====================== Script for composing message ==============
1.80      ng       1412:    // preload images
                   1413:    img1 = new Image();
                   1414:    img1.src = "$iconpath/mailbkgrd.gif";
                   1415:    img2 = new Image();
                   1416:    img2.src = "$iconpath/mailto.gif";
                   1417: 
1.44      ng       1418:   function msgCenter(msgform,usrctr,fullname) {
                   1419:     var Nmsg  = msgform.savemsgN.value;
                   1420:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1421:     var subject = msgform.msgsub.value;
1.127     ng       1422:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1423:     re = /msgsub/;
                   1424:     var shwsel = "";
                   1425:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1426:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1427:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1428:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1429: 	var testmsg = "savemsg"+i+",";
                   1430: 	re = new RegExp(testmsg,"g");
1.44      ng       1431: 	shwsel = "";
                   1432: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1433: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1434: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1435: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1436: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1437:     }
1.125     ng       1438:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1439:     shwsel = "";
                   1440:     re = /newmsg/;
                   1441:     if (re.test(msgchk)) { shwsel = "checked" }
                   1442:     newMsg(newmsg,shwsel);
                   1443:     msgTail(); 
                   1444:     return;
                   1445:   }
                   1446: 
1.123     ng       1447:   function checkEntities(strx) {
                   1448:     if (strx.length == 0) return strx;
                   1449:     var orgStr = ["&", "<", ">", '"']; 
                   1450:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1451:     var counter = 0;
                   1452:     while (counter < 4) {
                   1453: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1454: 	counter++;
                   1455:     }
                   1456:     return strx;
                   1457:   }
                   1458: 
                   1459:   function strReplace(strx, orgStr, newStr) {
                   1460:     return strx.split(orgStr).join(newStr);
                   1461:   }
                   1462: 
1.44      ng       1463:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1464:     var height = 70*Nmsg+250;
1.44      ng       1465:     var scrollbar = "no";
                   1466:     if (height > 600) {
                   1467: 	height = 600;
                   1468: 	scrollbar = "yes";
                   1469:     }
1.118     ng       1470:     var xpos = (screen.width-600)/2;
                   1471:     xpos = (xpos < 0) ? '0' : xpos;
                   1472:     var ypos = (screen.height-height)/2-30;
                   1473:     ypos = (ypos < 0) ? '0' : ypos;
                   1474: 
1.206     albertel 1475:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1476:     pWin.focus();
                   1477:     pDoc = pWin.document;
1.219     www      1478:     pDoc.$docopen;
1.351     albertel 1479:     pDoc.write('$start_page_msg_central');
1.76      ng       1480: 
                   1481:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1482:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1483:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1484: 
                   1485:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1486:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1487:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1488: }
                   1489:     function displaySubject(msg,shwsel) {
1.76      ng       1490:     pDoc = pWin.document;
                   1491:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1492:     pDoc.write("<td>Subject<\\/td>");
                   1493:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1494:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1495: }
                   1496: 
1.72      ng       1497:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1498:     pDoc = pWin.document;
                   1499:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1500:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1501:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1502:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1503: }
                   1504: 
                   1505:   function newMsg(newmsg,shwsel) {
1.76      ng       1506:     pDoc = pWin.document;
                   1507:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1508:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1509:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1510:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1511: }
                   1512: 
                   1513:   function msgTail() {
1.76      ng       1514:     pDoc = pWin.document;
1.465     albertel 1515:     pDoc.write("<\\/table>");
                   1516:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1517:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1518:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1519:     pDoc.write("<\\/form>");
1.351     albertel 1520:     pDoc.write('$end_page_msg_central');
1.128     ng       1521:     pDoc.close();
1.44      ng       1522: }
                   1523: 
                   1524: //====================== Script for keyword highlight options ==============
                   1525:   function kwhighlight() {
                   1526:     var kwclr    = document.SCORE.kwclr.value;
                   1527:     var kwsize   = document.SCORE.kwsize.value;
                   1528:     var kwstyle  = document.SCORE.kwstyle.value;
                   1529:     var redsel = "";
                   1530:     var grnsel = "";
                   1531:     var blusel = "";
                   1532:     if (kwclr=="red")   {var redsel="checked"};
                   1533:     if (kwclr=="green") {var grnsel="checked"};
                   1534:     if (kwclr=="blue")  {var blusel="checked"};
                   1535:     var sznsel = "";
                   1536:     var sz1sel = "";
                   1537:     var sz2sel = "";
                   1538:     if (kwsize=="0")  {var sznsel="checked"};
                   1539:     if (kwsize=="+1") {var sz1sel="checked"};
                   1540:     if (kwsize=="+2") {var sz2sel="checked"};
                   1541:     var synsel = "";
                   1542:     var syisel = "";
                   1543:     var sybsel = "";
                   1544:     if (kwstyle=="")    {var synsel="checked"};
                   1545:     if (kwstyle=="<i>") {var syisel="checked"};
                   1546:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1547:     highlightCentral();
                   1548:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1549:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1550:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1551:     highlightend();
                   1552:     return;
                   1553:   }
                   1554: 
                   1555:   function highlightCentral() {
1.76      ng       1556: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1557:     var xpos = (screen.width-400)/2;
                   1558:     xpos = (xpos < 0) ? '0' : xpos;
                   1559:     var ypos = (screen.height-330)/2-30;
                   1560:     ypos = (ypos < 0) ? '0' : ypos;
                   1561: 
1.206     albertel 1562:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1563:     hwdWin.focus();
                   1564:     var hDoc = hwdWin.document;
1.219     www      1565:     hDoc.$docopen;
1.351     albertel 1566:     hDoc.write('$start_page_highlight_central');
1.76      ng       1567:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1568:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1569: 
                   1570:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1571:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1572:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1573:   }
                   1574: 
                   1575:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1576:     var hDoc = hwdWin.document;
                   1577:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1578:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1579:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1580:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1581:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1582:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1583:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1584:     hDoc.write("<\\/tr>");
1.44      ng       1585:   }
                   1586: 
                   1587:   function highlightend() { 
1.76      ng       1588:     var hDoc = hwdWin.document;
1.465     albertel 1589:     hDoc.write("<\\/table>");
                   1590:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1591:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1592:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1593:     hDoc.write("<\\/form>");
1.351     albertel 1594:     hDoc.write('$end_page_highlight_central');
1.128     ng       1595:     hDoc.close();
1.44      ng       1596:   }
                   1597: 
                   1598: </script>
                   1599: SUBJAVASCRIPT
                   1600: }
                   1601: 
1.349     albertel 1602: sub get_increment {
1.348     bowersj2 1603:     my $increment = $env{'form.increment'};
                   1604:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1605:         $increment != .1) {
                   1606:         $increment = 1;
                   1607:     }
                   1608:     return $increment;
                   1609: }
                   1610: 
1.71      ng       1611: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1612: sub gradeBox {
1.322     albertel 1613:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1614:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1615: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1616: 	'/check.gif" height="16" border="0" />';
                   1617:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1618:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1619:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1620:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1621:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1622: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1623:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1624:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1625:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1626: 				       [$partid]);
                   1627:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1628:     if ($last_resets{$partid}) {
                   1629:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1630:     }
1.71      ng       1631:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1632: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1633:     my $ctr = 0;
1.348     bowersj2 1634:     my $thisweight = 0;
1.349     albertel 1635:     my $increment = &get_increment();
1.71      ng       1636:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1637:     while ($thisweight<=$wgt) {
1.381     albertel 1638: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1639: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1640: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1641: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1642: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1643:         $thisweight += $increment;
1.71      ng       1644: 	$ctr++;
                   1645:     }
                   1646:     $result.='</tr></table>';
                   1647:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1648:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1649: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1650: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1651: 	$wgt.')" /></td>'."\n";
                   1652:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1653: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1654: 	' </td><td>'."\n";
                   1655:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1656: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1657:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1658: 	$result.='<option></option>'.
1.401     albertel 1659: 	    '<option selected="selected">excused</option>';
1.71      ng       1660:     } else {
1.401     albertel 1661: 	$result.='<option selected="selected"></option>'.
1.125     ng       1662: 	    '<option>excused</option>';
1.71      ng       1663:     }
1.125     ng       1664:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1665:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1666:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1667: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1668: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1669: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1670:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1671:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1672:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1673:         $aggtries.'" />'."\n";
1.71      ng       1674:     $result.='</td></tr></table>'."\n";
1.323     banghart 1675:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1676:     return $result;
                   1677: }
1.322     albertel 1678: 
                   1679: sub handback_box {
1.323     banghart 1680:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1681:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1682:     my (@respids);
1.375     albertel 1683:      my @part_response_id = &flatten_responseType($responseType);
                   1684:     foreach my $part_response_id (@part_response_id) {
                   1685:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1686:         if ($part eq $partid) {
1.375     albertel 1687:             push(@respids,$resp);
1.323     banghart 1688:         }
                   1689:     }
1.318     banghart 1690:     my $result;
1.323     banghart 1691:     foreach my $respid (@respids) {
1.322     albertel 1692: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1693: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1694: 	next if (!@$files);
                   1695: 	my $file_counter = 1;
1.313     banghart 1696: 	foreach my $file (@$files) {
1.368     banghart 1697: 	    if ($file =~ /\/portfolio\//) {
                   1698:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1699:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1700:     	        $file_disp = "$name.$ext";
                   1701:     	        $file = $file_path.$file_disp;
                   1702:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1703:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1704:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1705:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.466     albertel 1706:     	        $result.='(File will be uploaded when you click on Save &amp; Next below.)<br />';
1.368     banghart 1707:     	        $file_counter++;
                   1708: 	    }
1.322     albertel 1709: 	}
1.313     banghart 1710:     }
1.318     banghart 1711:     return $result;    
1.71      ng       1712: }
1.44      ng       1713: 
1.58      albertel 1714: sub show_problem {
1.382     albertel 1715:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1716:     my $rendered;
1.382     albertel 1717:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1718:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1719:     if ($mode eq 'both' or $mode eq 'text') {
                   1720: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1721: 						       $env{'request.course.id'},
                   1722: 						       undef,\%form);
1.144     albertel 1723:     }
1.58      albertel 1724:     if ($removeform) {
                   1725: 	$rendered=~s|<form(.*?)>||g;
                   1726: 	$rendered=~s|</form>||g;
1.374     albertel 1727: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1728:     }
1.144     albertel 1729:     my $companswer;
                   1730:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1731: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1732: 	$companswer=
                   1733: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1734: 						    $env{'request.course.id'},
                   1735: 						    %form);
1.144     albertel 1736:     }
1.58      albertel 1737:     if ($removeform) {
                   1738: 	$companswer=~s|<form(.*?)>||g;
                   1739: 	$companswer=~s|</form>||g;
1.144     albertel 1740: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1741:     }
1.468   ! albertel 1742:     $rendered=
        !          1743: 	'<div class="LC_grade_show_problem_header">'.
        !          1744: 	&mt('View of the problem').
        !          1745: 	'</div><div class="LC_grade_show_problem_problem">'.
        !          1746: 	$rendered.
        !          1747: 	'</div>';
        !          1748:     $companswer=
        !          1749: 	'<div class="LC_grade_show_problem_header">'.
        !          1750: 	&mt('Correct answer').
        !          1751: 	'</div><div class="LC_grade_show_problem_problem">'.
        !          1752: 	$companswer.
        !          1753: 	'</div>';
        !          1754:     my $result;
1.144     albertel 1755:     if ($mode eq 'both') {
1.468   ! albertel 1756: 	$result=$rendered.$companswer;
1.144     albertel 1757:     } elsif ($mode eq 'text') {
1.468   ! albertel 1758: 	$result=$rendered;
1.144     albertel 1759:     } elsif ($mode eq 'answer') {
1.468   ! albertel 1760: 	$result=$companswer;
1.144     albertel 1761:     }
1.468   ! albertel 1762:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1763:     return $result;
1.58      albertel 1764: }
1.397     albertel 1765: 
1.396     banghart 1766: sub files_exist {
                   1767:     my ($r, $symb) = @_;
                   1768:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1769: 
1.396     banghart 1770:     foreach my $student (@students) {
                   1771:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1772:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1773: 					      $udom,$uname);
1.396     banghart 1774:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1775:         foreach my $submission (@$string) {
                   1776:             my ($partid,$respid) =
                   1777: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1778:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1779: 					   \%record);
                   1780:             return 1 if (@$files);
1.396     banghart 1781:         }
                   1782:     }
1.397     albertel 1783:     return 0;
1.396     banghart 1784: }
1.397     albertel 1785: 
1.394     banghart 1786: sub download_all_link {
                   1787:     my ($r,$symb) = @_;
1.395     albertel 1788:     my $all_students = 
                   1789: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1790: 
                   1791:     my $parts =
                   1792: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1793: 
1.394     banghart 1794:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1795:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1796:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1797:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1798:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1799: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1800:     return
                   1801: }
1.395     albertel 1802: 
1.432     banghart 1803: sub build_section_inputs {
                   1804:     my $section_inputs;
                   1805:     if ($env{'form.section'} eq '') {
                   1806:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1807:     } else {
                   1808:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1809:         foreach my $section (@sections) {
1.432     banghart 1810:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1811:         }
                   1812:     }
                   1813:     return $section_inputs;
                   1814: }
                   1815: 
1.44      ng       1816: # --------------------------- show submissions of a student, option to grade 
                   1817: sub submission {
                   1818:     my ($request,$counter,$total) = @_;
1.257     albertel 1819:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1820:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1821:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1822:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1823:     my $symb = &get_symb($request); 
                   1824:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1825: 
                   1826:     if (!&canview($usec)) {
1.398     albertel 1827: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1828: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1829: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1830: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1831: 	return;
                   1832:     }
                   1833: 
1.257     albertel 1834:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1835:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1836:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1837:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1838:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1839: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1840: 	'/check.gif" height="16" border="0" />';
1.41      ng       1841: 
1.426     albertel 1842:     my %old_essays;
1.41      ng       1843:     # header info
                   1844:     if ($counter == 0) {
                   1845: 	&sub_page_js($request);
1.257     albertel 1846: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1847: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1848: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1849: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1850: 	    &download_all_link($request, $symb);
                   1851: 	}
1.398     albertel 1852: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1853: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1854: 
1.257     albertel 1855: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1856: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1857: 		$checkIcon.' symbol.'."\n";
                   1858: 	    $request->print($checkMark);
                   1859: 	}
1.41      ng       1860: 
1.44      ng       1861: 	# option to display problem, only once else it cause problems 
                   1862:         # with the form later since the problem has a form.
1.257     albertel 1863: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1864: 	    my $mode;
1.257     albertel 1865: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1866: 		$mode='both';
1.257     albertel 1867: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1868: 		$mode='text';
1.257     albertel 1869: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1870: 		$mode='answer';
                   1871: 	    }
1.329     albertel 1872: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1873: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1874: 	}
1.441     www      1875: 
1.44      ng       1876: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1877:         # if this subroutine has been called once.
1.41      ng       1878: 	my %keyhash = ();
1.257     albertel 1879: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1880: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1881: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1882: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1883: 
1.257     albertel 1884: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1885: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1886: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1887: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1888: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1889: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1890: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1891: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1892: 	}
1.257     albertel 1893: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1894: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1895: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1896: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1897: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1898: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1899: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1900: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1901: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1902: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1903: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1904: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1905: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1906: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1907: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1908: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1909: 			&build_section_inputs().
1.326     albertel 1910: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1911: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1912: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1913: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1914: 	if ($env{'form.handgrade'} eq 'yes') {
                   1915: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1916: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1917: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1918: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1919: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1920: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1921: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1922: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1923: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1924: 	    }
1.123     ng       1925: 	}
1.41      ng       1926: 	
                   1927: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1928: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1929: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1930: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1931: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1932: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1933: 		'" />'."\n".
                   1934: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1935: 	    $cts++;
                   1936: 	}
                   1937: 	$request->print($prnmsg);
1.32      ng       1938: 
1.257     albertel 1939: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1940: #
                   1941: # Print out the keyword options line
                   1942: #
1.41      ng       1943: 	    $request->print(<<KEYWORDS);
1.38      ng       1944: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1945: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1946: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1947:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1948: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1949: KEYWORDS
1.88      www      1950: #
                   1951: # Load the other essays for similarity check
                   1952: #
1.324     albertel 1953:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1954: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1955: 	    $apath=&escape($apath);
1.88      www      1956: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1957: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1958:         }
                   1959:     }
1.44      ng       1960: 
1.441     www      1961: # This is where output for one specific student would start
1.468   ! albertel 1962:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      1963:     $request->print("\n\n".
1.468   ! albertel 1964:                     '<div class="LC_grade_show_user '.$add_class.'">'.
        !          1965: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
        !          1966: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      1967: 
1.257     albertel 1968:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1969: 	my $mode;
1.257     albertel 1970: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1971: 	    $mode='both';
1.257     albertel 1972: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1973: 	    $mode='text';
1.257     albertel 1974: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1975: 	    $mode='answer';
                   1976: 	}
1.329     albertel 1977: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1978: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1979:     }
1.144     albertel 1980: 
1.257     albertel 1981:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1982:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1983: 
1.44      ng       1984:     # Display student info
1.41      ng       1985:     $request->print(($counter == 0 ? '' : '<br />'));
1.468   ! albertel 1986:     my $result='<div class="LC_grade_submissions">';
        !          1987:     
        !          1988:     $result.='<div class="LC_grade_submissions_header">';
        !          1989:     $result.= &mt('Submissions');
1.45      ng       1990:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1991: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1992: 
1.118     ng       1993:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 1994:     my $fullname;
                   1995:     my $col_fullnames = [];
1.257     albertel 1996:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 1997: 	(my $sub_result,$fullname,$col_fullnames)=
                   1998: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   1999: 				 $counter);
                   2000: 	$result.=$sub_result;
1.41      ng       2001:     }
1.44      ng       2002:     $request->print($result."\n");
1.468   ! albertel 2003:     $request->print('</div>'."\n");
1.44      ng       2004:     # print student answer/submission
                   2005:     # Options are (1) Handgaded submission only
                   2006:     #             (2) Last submission, includes submission that is not handgraded 
                   2007:     #                  (for multi-response type part)
                   2008:     #             (3) Last submission plus the parts info
                   2009:     #             (4) The whole record for this student
1.257     albertel 2010:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2011: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468   ! albertel 2012: 	
        !          2013: 	my $lastsubonly;
        !          2014: 
1.151     albertel 2015: 	if ($$timestamp eq '') {
1.468   ! albertel 2016: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2017: 	} else {
1.468   ! albertel 2018: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
        !          2019: 
1.151     albertel 2020: 	    my %seenparts;
1.375     albertel 2021: 	    my @part_response_id = &flatten_responseType($responseType);
                   2022: 	    foreach my $part (@part_response_id) {
1.393     albertel 2023: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2024: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2025: 
1.375     albertel 2026: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2027: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2028: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2029: 		    if (exists($seenparts{$partid})) { next; }
                   2030: 		    $seenparts{$partid}=1;
1.207     albertel 2031: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2032: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2033: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2034: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2035: 			'\');" target="_self">'.
1.257     albertel 2036: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2037: 		    $request->print($submitby);
                   2038: 		    next;
                   2039: 		}
                   2040: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2041: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468   ! albertel 2042: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2043: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2044: 			' )</span>&nbsp; &nbsp;'.
1.468   ! albertel 2045: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2046: 		    next;
                   2047: 		}
1.468   ! albertel 2048: 		foreach my $submission (@$string) {
        !          2049: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2050: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468   ! albertel 2051: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2052: 		    # Similarity check
                   2053: 		    my $similar='';
1.257     albertel 2054: 		    if($env{'form.checkPlag'}){
1.151     albertel 2055: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2056: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2057: 			if ($osim) {
                   2058: 			    $osim=int($osim*100.0);
1.426     albertel 2059: 			    my %old_course_desc = 
                   2060: 				&Apache::lonnet::coursedescription($ocrsid,
                   2061: 								   {'one_time' => 1});
                   2062: 
                   2063: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2064: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2065: 				    $osim,
                   2066: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2067: 				    $oname,$odom,
1.426     albertel 2068: 				    $old_course_desc{'description'},
1.427     albertel 2069: 				    $old_course_desc{'num'},
1.426     albertel 2070: 				    $old_course_desc{'domain'}).
1.398     albertel 2071: 				'</span></h3><blockquote><i>'.
1.151     albertel 2072: 				&keywords_highlight($oessay).
                   2073: 				'</i></blockquote><hr />';
                   2074: 			}
1.150     albertel 2075: 		    }
1.151     albertel 2076: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2077: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2078: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2079: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2080: 			my $display_part=&get_display_part($partid,$symb);
1.468   ! albertel 2081: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2082: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2083: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2084: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2085: 			if (@$files) {
1.468   ! albertel 2086: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2087: 			    my $file_counter = 0;
1.313     banghart 2088: 			    foreach my $file (@$files) {
1.468   ! albertel 2089: 			        $file_counter++;
1.232     albertel 2090: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2091: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2092: 			    }
1.236     albertel 2093: 			    $lastsubonly.='<br />';
1.41      ng       2094: 			}
1.468   ! albertel 2095: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2096: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2097: 					 $respid,\%record,$order);
                   2098: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468   ! albertel 2099: 			$lastsubonly.='</div>';
1.41      ng       2100: 		    }
                   2101: 		}
                   2102: 	    }
1.468   ! albertel 2103: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2104: 	}
                   2105: 	$request->print($lastsubonly);
1.468   ! albertel 2106:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2107: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2108: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2109:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2110: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2111: 								 $env{'request.course.id'},
1.44      ng       2112: 								 $last,'.submission',
                   2113: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2114:     }
1.120     ng       2115: 
1.121     ng       2116:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2117: 	.$udom.'" />'."\n");
1.44      ng       2118:     # return if view submission with no grading option
1.257     albertel 2119:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2120: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2121: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2122: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468   ! albertel 2123: 	$toGrade.='</div>'."\n";
1.257     albertel 2124: 	if (($env{'form.command'} eq 'submission') || 
                   2125: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2126: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2127: 	}
1.180     albertel 2128: 	$request->print($toGrade);
1.41      ng       2129: 	return;
1.180     albertel 2130:     } else {
1.468   ! albertel 2131: 	$request->print('</div>'."\n");
1.41      ng       2132:     }
1.33      ng       2133: 
1.121     ng       2134:     # essay grading message center
1.257     albertel 2135:     if ($env{'form.handgrade'} eq 'yes') {
1.468   ! albertel 2136: 	my $result='<div class="LC_grade_message_center">';
        !          2137:     
        !          2138: 	$result.='<div class="LC_grade_message_center_header">'.
        !          2139: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2140: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2141: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2142: 	if (scalar(@$col_fullnames) > 0) {
                   2143: 	    my $lastone = pop(@$col_fullnames);
                   2144: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2145: 	}
                   2146: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468   ! albertel 2147: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2148: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2149: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2150: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2151: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2152: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2153: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2154: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2155: 	    '<br />&nbsp;('.
1.468   ! albertel 2156: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
        !          2157: 	$result.='</div></div>';
1.121     ng       2158: 	$request->print($result);
1.118     ng       2159:     }
1.41      ng       2160: 
                   2161:     my %seen = ();
                   2162:     my @partlist;
1.129     ng       2163:     my @gradePartRespid;
1.375     albertel 2164:     my @part_response_id = &flatten_responseType($responseType);
1.468   ! albertel 2165:     $request->print('<div class="LC_grade_assign">'.
        !          2166: 		    
        !          2167: 		    '<div class="LC_grade_assign_header">'.
        !          2168: 		    &mt('Assign Grades').'</div>'.
        !          2169: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2170:     foreach my $part_response_id (@part_response_id) {
                   2171:     	my ($partid,$respid) = @{ $part_response_id };
                   2172: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2173: 	next if ($seen{$partid} > 0);
1.41      ng       2174: 	$seen{$partid}++;
1.393     albertel 2175: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2176: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2177: 	push @partlist,$partid;
1.129     ng       2178: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2179: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2180:     }
1.468   ! albertel 2181:     $request->print('</div></div>');
        !          2182: 
        !          2183:     $request->print('<div class="LC_grade_info_links">');
        !          2184:     if ($perm{'vgr'}) {
        !          2185: 	$request->print(
        !          2186: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
        !          2187: 						   $uname,$udom,'check'));
        !          2188:     }
        !          2189:     if ($perm{'opa'}) {
        !          2190: 	$request->print(
        !          2191: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
        !          2192: 					 $uname,$udom,$symb,'check'));
        !          2193:     }
        !          2194:     $request->print('</div>');
        !          2195: 
1.45      ng       2196:     $result='<input type="hidden" name="partlist'.$counter.
                   2197: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2198:     $result.='<input type="hidden" name="gradePartRespid'.
                   2199: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2200:     my $ctr = 0;
                   2201:     while ($ctr < scalar(@partlist)) {
                   2202: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2203: 	    $partlist[$ctr].'" />'."\n";
                   2204: 	$ctr++;
                   2205:     }
1.468   ! albertel 2206:     $request->print($result.''."\n");
1.41      ng       2207: 
1.441     www      2208: # Done with printing info for one student
                   2209: 
1.468   ! albertel 2210:     $request->print('</div>');#LC_grade_show_user_body
        !          2211:     $request->print('</div>');#LC_grade_show_user
1.441     www      2212: 
                   2213: 
1.41      ng       2214:     # print end of form
                   2215:     if ($counter == $total) {
1.297     www      2216: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2217: 	$endform.='<input type="button" value="Save & Next" '.
                   2218: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2219: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2220: 	my $ntstu ='<select name="NTSTU">'.
                   2221: 	    '<option>1</option><option>2</option>'.
                   2222: 	    '<option>3</option><option>5</option>'.
                   2223: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2224: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2225: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2226: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2227: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2228: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2229: 	    '<input type="button" value="Next" '.
1.417     albertel 2230: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2231: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2232:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2233:             "' name='increment' />";
1.45      ng       2234: 	$endform.='</td><tr></table></form>';
1.324     albertel 2235: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2236: 	$request->print($endform);
                   2237:     }
                   2238:     return '';
1.38      ng       2239: }
                   2240: 
1.464     albertel 2241: sub check_collaborators {
                   2242:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2243:     my ($result,@col_fullnames);
                   2244:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2245:     foreach my $part (keys(%$handgrade)) {
                   2246: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2247: 					'.maxcollaborators',
                   2248: 					$symb,$udom,$uname);
                   2249: 	next if ($ncol <= 0);
                   2250: 	$part =~ s/\_/\./g;
                   2251: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2252: 	my (@good_collaborators, @bad_collaborators);
                   2253: 	foreach my $possible_collaborator
                   2254: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2255: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2256: 	    next if ($possible_collaborator eq '');
                   2257: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2258: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2259: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2260: 	    # Doing this grep allows 'fuzzy' specification
                   2261: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2262: 			       keys(%$classlist));
                   2263: 	    if (! scalar(@matches)) {
                   2264: 		push(@bad_collaborators, $possible_collaborator);
                   2265: 	    } else {
                   2266: 		push(@good_collaborators, @matches);
                   2267: 	    }
                   2268: 	}
                   2269: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2270: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2271: 	    foreach my $name (@good_collaborators) {
                   2272: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2273: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2274: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2275: 	    }
                   2276: 	    $result.='<br />'."\n";
1.466     albertel 2277: 	    my ($part)=split(/\./,$part);
1.464     albertel 2278: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2279: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2280: 		"\n";
                   2281: 	}
                   2282: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2283: 	    $result.='<div class="LC_warning">';
1.464     albertel 2284: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2285: 	    $result .= '</div>';
                   2286: 	}         
                   2287: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2288: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2289: 	    $result .= &mt('This student has submitted too many '.
                   2290: 		'collaborators.  Maximum is [_1].',$ncol);
                   2291: 	    $result .= '</div>';
                   2292: 	}
                   2293:     }
                   2294:     return ($result,$fullname,\@col_fullnames);
                   2295: }
                   2296: 
1.44      ng       2297: #--- Retrieve the last submission for all the parts
1.38      ng       2298: sub get_last_submission {
1.119     ng       2299:     my ($returnhash)=@_;
1.46      ng       2300:     my (@string,$timestamp);
1.119     ng       2301:     if ($$returnhash{'version'}) {
1.46      ng       2302: 	my %lasthash=();
                   2303: 	my ($version);
1.119     ng       2304: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2305: 	    foreach my $key (sort(split(/\:/,
                   2306: 					$$returnhash{$version.':keys'}))) {
                   2307: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2308: 		$timestamp = 
                   2309: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2310: 	    }
                   2311: 	}
1.397     albertel 2312: 	foreach my $key (keys(%lasthash)) {
                   2313: 	    next if ($key !~ /\.submission$/);
                   2314: 
                   2315: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2316: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2317: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2318: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2319: 	}
                   2320:     }
1.397     albertel 2321:     if (!@string) {
                   2322: 	$string[0] =
1.398     albertel 2323: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2324:     }
                   2325:     return (\@string,\$timestamp);
1.38      ng       2326: }
1.35      ng       2327: 
1.44      ng       2328: #--- High light keywords, with style choosen by user.
1.38      ng       2329: sub keywords_highlight {
1.44      ng       2330:     my $string    = shift;
1.257     albertel 2331:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2332:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2333:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2334:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2335:     foreach my $keyword (@keylist) {
                   2336: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2337:     }
                   2338:     return $string;
1.38      ng       2339: }
1.36      ng       2340: 
1.44      ng       2341: #--- Called from submission routine
1.38      ng       2342: sub processHandGrade {
1.41      ng       2343:     my ($request) = shift;
1.324     albertel 2344:     my $symb   = &get_symb($request);
                   2345:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2346:     my $button = $env{'form.gradeOpt'};
                   2347:     my $ngrade = $env{'form.NCT'};
                   2348:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2349:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2350:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2351: 
1.44      ng       2352:     if ($button eq 'Save & Next') {
                   2353: 	my $ctr = 0;
                   2354: 	while ($ctr < $ngrade) {
1.257     albertel 2355: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2356: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2357: 	    if ($errorflag eq 'no_score') {
                   2358: 		$ctr++;
                   2359: 		next;
                   2360: 	    }
1.104     albertel 2361: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2362: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2363: 		$ctr++;
                   2364: 		next;
                   2365: 	    }
1.257     albertel 2366: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2367: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2368: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2369:             my ($feedurl,$showsymb) =
                   2370: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2371: 	    my $messagetail;
1.62      albertel 2372: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2373: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2374: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2375: 		$subject.=' ['.$restitle.']';
1.44      ng       2376: 		my (@msgnum) = split(/,/,$includemsg);
                   2377: 		foreach (@msgnum) {
1.257     albertel 2378: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2379: 		}
1.80      ng       2380: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2381: 		if ($env{'form.withgrades'.$ctr}) {
                   2382: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2383: 		    $messagetail = " for <a href=\"".
1.418     albertel 2384: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2385: 		}
                   2386: 		$msgstatus = 
                   2387:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2388: 						     $message.$messagetail,
1.418     albertel 2389:                                                      undef,$feedurl,undef,
1.386     raeburn  2390:                                                      undef,undef,$showsymb,
                   2391:                                                      $restitle);
                   2392: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2393: 				$msgstatus);
1.44      ng       2394: 	    }
1.257     albertel 2395: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2396: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2397: 		foreach my $collabstr (@collabstrs) {
                   2398: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2399: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2400: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2401: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2402: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2403: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2404: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2405: 			    next;
1.418     albertel 2406: 			} elsif ($message ne '') {
                   2407: 			    my ($baseurl,$showsymb) = 
                   2408: 				&get_feedurl_and_symb($symb,$collaborator,
                   2409: 						      $udom);
                   2410: 			    if ($env{'form.withgrades'.$ctr}) {
                   2411: 				$messagetail = " for <a href=\"".
1.386     raeburn  2412:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2413: 			    }
1.418     albertel 2414: 			    $msgstatus = 
                   2415: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2416: 			}
1.44      ng       2417: 		    }
                   2418: 		}
                   2419: 	    }
                   2420: 	    $ctr++;
                   2421: 	}
                   2422:     }
                   2423: 
1.257     albertel 2424:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2425: 	# Keywords sorted in alphabatical order
1.257     albertel 2426: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2427: 	my %keyhash = ();
1.257     albertel 2428: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2429: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2430: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2431: 	$env{'form.keywords'} = join(' ',@keywords);
                   2432: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2433: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2434: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2435: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2436: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2437: 
                   2438: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2439: 	# New messages are saved in env for the next student.
1.119     ng       2440: 	# All messages are saved in nohist_handgrade.db
                   2441: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2442: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2443: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2444: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2445: 		$idx++;
                   2446: 	    }
                   2447: 	    $ctr++;
1.41      ng       2448: 	}
1.119     ng       2449: 	$ctr = 0;
                   2450: 	while ($ctr < $ngrade) {
1.257     albertel 2451: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2452: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2453: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2454: 		$idx++;
                   2455: 	    }
                   2456: 	    $ctr++;
1.41      ng       2457: 	}
1.257     albertel 2458: 	$env{'form.savemsgN'} = --$idx;
                   2459: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2460: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2461: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2462:     }
1.44      ng       2463:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2464:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2465:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2466: 	my ($ctr,$total) = (0,0);
                   2467: 	while ($ctr < $ngrade) {
1.257     albertel 2468: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2469: 	    $ctr++;
                   2470: 	}
1.257     albertel 2471: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2472: 	$ctr = 0;
                   2473: 	while ($ctr < $total) {
1.257     albertel 2474: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2475: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2476: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2477: 	    &submission($request,$ctr,$total-1);
1.41      ng       2478: 	    $ctr++;
                   2479: 	}
                   2480: 	return '';
                   2481:     }
1.36      ng       2482: 
1.121     ng       2483: # Go directly to grade student - from submission or link from chart page
1.120     ng       2484:     if ($button eq 'Grade Student') {
1.324     albertel 2485: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2486: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2487: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2488: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2489: 	&submission($request,0,0);
                   2490: 	return '';
                   2491:     }
                   2492: 
1.44      ng       2493:     # Get the next/previous one or group of students
1.257     albertel 2494:     my $firststu = $env{'form.unamedom0'};
                   2495:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2496:     my $ctr = 2;
1.41      ng       2497:     while ($laststu eq '') {
1.257     albertel 2498: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2499: 	$ctr++;
                   2500: 	$laststu = $firststu if ($ctr > $ngrade);
                   2501:     }
1.44      ng       2502: 
1.41      ng       2503:     my (@parsedlist,@nextlist);
                   2504:     my ($nextflg) = 0;
1.294     albertel 2505:     foreach (sort 
                   2506: 	     {
                   2507: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2508: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2509: 		 }
                   2510: 		 return $a cmp $b;
                   2511: 	     } (keys(%$fullname))) {
1.41      ng       2512: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2513: 	    push @parsedlist,$_;
                   2514: 	}
                   2515: 	$nextflg = 1 if ($_ eq $laststu);
                   2516: 	if ($button eq 'Previous') {
                   2517: 	    last if ($_ eq $firststu);
                   2518: 	    push @parsedlist,$_;
                   2519: 	}
                   2520:     }
                   2521:     $ctr = 0;
                   2522:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2523:     my ($partlist) = &response_type($symb);
1.41      ng       2524:     foreach my $student (@parsedlist) {
1.257     albertel 2525: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2526: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2527: 	
                   2528: 	if ($submitonly eq 'queued') {
                   2529: 	    my %queue_status = 
                   2530: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2531: 							$udom,$uname);
                   2532: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2533: 	}
                   2534: 
1.156     albertel 2535: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2536: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2537: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2538: 	    my $submitted = 0;
1.248     albertel 2539: 	    my $ungraded = 0;
                   2540: 	    my $incorrect = 0;
1.145     albertel 2541: 	    foreach (keys(%status)) {
                   2542: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2543: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2544: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2545: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2546: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2547: 		    $submitted = 0;
                   2548: 		}
1.41      ng       2549: 	    }
1.156     albertel 2550: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2551: 				     $submitonly eq 'incorrect' ||
                   2552: 				     $submitonly eq 'graded'));
1.248     albertel 2553: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2554: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2555: 	}
                   2556: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2557: 	last if ($ctr == $ntstu);
1.41      ng       2558: 	$ctr++;
                   2559:     }
1.36      ng       2560: 
1.41      ng       2561:     $ctr = 0;
                   2562:     my $total = scalar(@nextlist)-1;
1.39      ng       2563: 
1.41      ng       2564:     foreach (sort @nextlist) {
                   2565: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2566: 	$env{'form.student'}  = $uname;
                   2567: 	$env{'form.userdom'}  = $udom;
                   2568: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2569: 	&submission($request,$ctr,$total);
                   2570: 	$ctr++;
                   2571:     }
                   2572:     if ($total < 0) {
1.398     albertel 2573: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2574: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2575: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2576: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2577: 	$request->print($the_end);
                   2578:     }
                   2579:     return '';
1.38      ng       2580: }
1.36      ng       2581: 
1.44      ng       2582: #---- Save the score and award for each student, if changed
1.38      ng       2583: sub saveHandGrade {
1.324     albertel 2584:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2585:     my @version_parts;
1.104     albertel 2586:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2587: 					   $env{'request.course.id'});
1.104     albertel 2588:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2589:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2590:     my @parts_graded;
1.77      ng       2591:     my %newrecord  = ();
                   2592:     my ($pts,$wgt) = ('','');
1.269     raeburn  2593:     my %aggregate = ();
                   2594:     my $aggregateflag = 0;
1.301     albertel 2595:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2596:     foreach my $new_part (@parts) {
1.337     banghart 2597: 	#collaborator ($submi may vary for different parts
1.259     banghart 2598: 	if ($submitter && $new_part ne $part) { next; }
                   2599: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2600: 	if ($dropMenu eq 'excused') {
1.259     banghart 2601: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2602: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2603: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2604: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2605: 		}
1.364     banghart 2606: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2607: 	    }
1.125     ng       2608: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2609: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2610: 	    foreach my $key (keys (%record)) {
1.259     banghart 2611: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2612: 	    }
1.259     banghart 2613: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2614: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2615:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2616: 
                   2617:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2618: 					       [$new_part]);
                   2619:             my $aggtries =$totaltries;
1.269     raeburn  2620:             if ($last_resets{$new_part}) {
1.270     albertel 2621:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2622: 					   $new_part);
1.269     raeburn  2623:             }
1.270     albertel 2624: 
                   2625:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2626:             if ($aggtries > 0) {
1.327     albertel 2627:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2628:                 $aggregateflag = 1;
                   2629:             }
1.125     ng       2630: 	} elsif ($dropMenu eq '') {
1.259     banghart 2631: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2632: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2633: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2634: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2635: 		next;
                   2636: 	    }
1.259     banghart 2637: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2638: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2639: 	    my $partial= $pts/$wgt;
1.259     banghart 2640: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2641: 		#do not update score for part if not changed.
1.346     banghart 2642:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2643: 		next;
1.251     banghart 2644: 	    } else {
1.259     banghart 2645: 	        push @parts_graded, $new_part;
1.153     albertel 2646: 	    }
1.259     banghart 2647: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2648: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2649: 	    }
1.259     banghart 2650: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2651: 	    if ($partial == 0) {
1.153     albertel 2652: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2653: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2654: 		}
1.41      ng       2655: 	    } else {
1.153     albertel 2656: 		if ($record{$reckey} ne 'correct_by_override') {
                   2657: 		    $newrecord{$reckey} = 'correct_by_override';
                   2658: 		}
                   2659: 	    }	    
                   2660: 	    if ($submitter && 
1.259     banghart 2661: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2662: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2663: 	    }
1.259     banghart 2664: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2665: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2666: 	}
1.259     banghart 2667: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2668: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2669: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2670: 	        $dropMenu eq 'reset status')
                   2671: 	   {
1.342     banghart 2672: 	    push (@version_parts,$new_part);
1.259     banghart 2673: 	}
1.41      ng       2674:     }
1.301     albertel 2675:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2676:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2677: 
1.344     albertel 2678:     if (%newrecord) {
                   2679:         if (@version_parts) {
1.364     banghart 2680:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2681:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2682: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2683: 	    foreach my $new_part (@version_parts) {
                   2684: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2685: 				$new_part,\%newrecord);
                   2686: 	    }
1.259     banghart 2687:         }
1.44      ng       2688: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2689: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2690: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2691: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2692:     }
1.269     raeburn  2693:     if ($aggregateflag) {
                   2694:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2695: 			      $cdom,$cnum);
1.269     raeburn  2696:     }
1.301     albertel 2697:     return ('',$pts,$wgt);
1.36      ng       2698: }
1.322     albertel 2699: 
1.380     albertel 2700: sub check_and_remove_from_queue {
                   2701:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2702:     my @ungraded_parts;
                   2703:     foreach my $part (@{$parts}) {
                   2704: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2705: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2706: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2707: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2708: 		) {
                   2709: 	    push(@ungraded_parts, $part);
                   2710: 	}
                   2711:     }
                   2712:     if ( !@ungraded_parts ) {
                   2713: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2714: 					       $cnum,$domain,$stuname);
                   2715:     }
                   2716: }
                   2717: 
1.337     banghart 2718: sub handback_files {
                   2719:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2720:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2721:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2722: 
                   2723:     my @part_response_id = &flatten_responseType($responseType);
                   2724:     foreach my $part_response_id (@part_response_id) {
                   2725:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2726: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2727:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2728:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2729:                 my $file_counter = 1;
1.367     albertel 2730: 		my $file_msg;
1.337     banghart 2731:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2732:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2733:                     my ($directory,$answer_file) = 
                   2734:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2735:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2736: 		        &file_name_version_ext($answer_file);
1.355     banghart 2737: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2738: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2739: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2740:                     # fix file name
                   2741:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2742:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2743:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2744:             	                                $save_file_name);
1.337     banghart 2745:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2746:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2747:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2748:                     } else {
1.360     banghart 2749:                         # mark the file as read only
                   2750:                         my @files = ($save_file_name);
1.372     albertel 2751:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2752:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2753: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2754: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2755: 			}
                   2756:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2757: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2758: 
1.337     banghart 2759:                     }
                   2760:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2761:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2762:                     $file_counter++;
                   2763:                 }
1.367     albertel 2764: 		my $subject = "File Handed Back by Instructor ";
                   2765: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2766: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2767: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2768: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2769: 		my ($feedurl,$showsymb) = 
                   2770: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2771:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2772: 		my $msgstatus = 
                   2773:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2774: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2775:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2776:             }
                   2777:         }
1.338     banghart 2778:     return;
1.337     banghart 2779: }
                   2780: 
1.418     albertel 2781: sub get_feedurl_and_symb {
                   2782:     my ($symb,$uname,$udom) = @_;
                   2783:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2784:     $url = &Apache::lonnet::clutter($url);
                   2785:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2786: 					$symb,$udom,$uname);
                   2787:     if ($encrypturl =~ /^yes$/i) {
                   2788: 	&Apache::lonenc::encrypted(\$url,1);
                   2789: 	&Apache::lonenc::encrypted(\$symb,1);
                   2790:     }
                   2791:     return ($url,$symb);
                   2792: }
                   2793: 
1.313     banghart 2794: sub get_submitted_files {
                   2795:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2796:     my @files;
                   2797:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2798:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2799:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2800:     	    push(@files,$file_url.$file);
                   2801:         }
                   2802:     }
                   2803:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2804:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2805:     }
                   2806:     return (\@files);
                   2807: }
1.322     albertel 2808: 
1.269     raeburn  2809: # ----------- Provides number of tries since last reset.
                   2810: sub get_num_tries {
                   2811:     my ($record,$last_reset,$part) = @_;
                   2812:     my $timestamp = '';
                   2813:     my $num_tries = 0;
                   2814:     if ($$record{'version'}) {
                   2815:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2816:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2817:                 $timestamp = $$record{$version.':timestamp'};
                   2818:                 if ($timestamp > $last_reset) {
                   2819:                     $num_tries ++;
                   2820:                 } else {
                   2821:                     last;
                   2822:                 }
                   2823:             }
                   2824:         }
                   2825:     }
                   2826:     return $num_tries;
                   2827: }
                   2828: 
                   2829: # ----------- Determine decrements required in aggregate totals 
                   2830: sub decrement_aggs {
                   2831:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2832:     my %decrement = (
                   2833:                         attempts => 0,
                   2834:                         users => 0,
                   2835:                         correct => 0
                   2836:                     );
                   2837:     $decrement{'attempts'} = $aggtries;
                   2838:     if ($solvedstatus =~ /^correct/) {
                   2839:         $decrement{'correct'} = 1;
                   2840:     }
                   2841:     if ($aggtries == $totaltries) {
                   2842:         $decrement{'users'} = 1;
                   2843:     }
                   2844:     foreach my $type (keys (%decrement)) {
                   2845:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2846:     }
                   2847:     return;
                   2848: }
                   2849: 
                   2850: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2851: sub get_last_resets {
1.270     albertel 2852:     my ($symb,$courseid,$partids) =@_;
                   2853:     my %last_resets;
1.269     raeburn  2854:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2855:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2856:     my @keys;
                   2857:     foreach my $part (@{$partids}) {
                   2858: 	push(@keys,"$symb\0$part\0resettime");
                   2859:     }
                   2860:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2861: 				     $cdom,$cname);
                   2862:     foreach my $part (@{$partids}) {
                   2863: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2864:     }
1.270     albertel 2865:     return %last_resets;
1.269     raeburn  2866: }
                   2867: 
1.251     banghart 2868: # ----------- Handles creating versions for portfolio files as answers
                   2869: sub version_portfiles {
1.343     banghart 2870:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2871:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2872:     my @returned_keys;
1.255     banghart 2873:     my $parts = join('|', @$parts_graded);
1.359     www      2874:     my $portfolio_root = &propath($domain,$stu_name).
                   2875: 	'/userfiles/portfolio';
1.277     albertel 2876:     foreach my $key (keys(%$record)) {
1.259     banghart 2877:         my $new_portfiles;
1.263     banghart 2878:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2879:             my @versioned_portfiles;
1.367     albertel 2880:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2881:             foreach my $file (@portfiles) {
1.306     banghart 2882:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2883:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2884: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2885: 		    &file_name_version_ext($answer_file);
1.306     banghart 2886:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2887:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2888:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2889:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2890:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2891:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2892:                         [$directory.$new_answer],
1.306     banghart 2893:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2894:                 }
1.252     banghart 2895:             }
1.343     banghart 2896:             $$record{$key} = join(',',@versioned_portfiles);
                   2897:             push(@returned_keys,$key);
1.251     banghart 2898:         }
                   2899:     } 
1.343     banghart 2900:     return (@returned_keys);   
1.305     banghart 2901: }
                   2902: 
1.307     banghart 2903: sub get_next_version {
1.341     banghart 2904:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2905:     my $version;
                   2906:     foreach my $row (@$dir_list) {
                   2907:         my ($file) = split(/\&/,$row,2);
                   2908:         my ($file_name,$file_version,$file_ext) =
                   2909: 	    &file_name_version_ext($file);
                   2910:         if (($file_name eq $answer_name) && 
                   2911: 	    ($file_ext eq $answer_ext)) {
                   2912:                 # gets here if filename and extension match, regardless of version
                   2913:                 if ($file_version ne '') {
                   2914:                 # a versioned file is found  so save it for later
                   2915:                 if ($file_version > $version) {
                   2916: 		    $version = $file_version;
                   2917: 	        }
                   2918:             }
                   2919:         }
                   2920:     } 
                   2921:     $version ++;
                   2922:     return($version);
                   2923: }
                   2924: 
1.305     banghart 2925: sub version_selected_portfile {
1.306     banghart 2926:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2927:     my ($answer_name,$answer_ver,$answer_ext) =
                   2928:         &file_name_version_ext($file_name);
                   2929:     my $new_answer;
                   2930:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2931:     if($env{'form.copy'} eq '-1') {
                   2932:         $new_answer = 'problem getting file';
                   2933:     } else {
                   2934:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2935:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2936:                             $stu_name,$domain,'copy',
                   2937: 		        '/portfolio'.$directory.$new_answer);
                   2938:     }    
                   2939:     return ($new_answer);
1.251     banghart 2940: }
                   2941: 
1.304     albertel 2942: sub file_name_version_ext {
                   2943:     my ($file)=@_;
                   2944:     my @file_parts = split(/\./, $file);
                   2945:     my ($name,$version,$ext);
                   2946:     if (@file_parts > 1) {
                   2947: 	$ext=pop(@file_parts);
                   2948: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2949: 	    $version=pop(@file_parts);
                   2950: 	}
                   2951: 	$name=join('.',@file_parts);
                   2952:     } else {
                   2953: 	$name=join('.',@file_parts);
                   2954:     }
                   2955:     return($name,$version,$ext);
                   2956: }
                   2957: 
1.44      ng       2958: #--------------------------------------------------------------------------------------
                   2959: #
                   2960: #-------------------------- Next few routines handles grading by section or whole class
                   2961: #
                   2962: #--- Javascript to handle grading by section or whole class
1.42      ng       2963: sub viewgrades_js {
                   2964:     my ($request) = shift;
                   2965: 
1.41      ng       2966:     $request->print(<<VIEWJAVASCRIPT);
                   2967: <script type="text/javascript" language="javascript">
1.45      ng       2968:    function writePoint(partid,weight,point) {
1.125     ng       2969: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2970: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2971: 	if (point == "textval") {
1.125     ng       2972: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2973: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2974: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2975: 		var resetbox = false;
                   2976: 		for (var i=0; i<radioButton.length; i++) {
                   2977: 		    if (radioButton[i].checked) {
                   2978: 			textbox.value = i;
                   2979: 			resetbox = true;
                   2980: 		    }
                   2981: 		}
                   2982: 		if (!resetbox) {
                   2983: 		    textbox.value = "";
                   2984: 		}
                   2985: 		return;
                   2986: 	    }
1.109     matthew  2987: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2988: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2989: 				   ") greater than the weight for the part. Accept?");
                   2990: 		if (resp == false) {
                   2991: 		    textbox.value = "";
                   2992: 		    return;
                   2993: 		}
                   2994: 	    }
1.42      ng       2995: 	    for (var i=0; i<radioButton.length; i++) {
                   2996: 		radioButton[i].checked=false;
1.109     matthew  2997: 		if (parseFloat(point) == i) {
1.42      ng       2998: 		    radioButton[i].checked=true;
                   2999: 		}
                   3000: 	    }
1.41      ng       3001: 
1.42      ng       3002: 	} else {
1.125     ng       3003: 	    textbox.value = parseFloat(point);
1.42      ng       3004: 	}
1.41      ng       3005: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3006: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3007: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3008: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3009: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3010: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3011: 	    if (saveval != "correct") {
                   3012: 		scorename.value = point;
1.43      ng       3013: 		if (selname[0].selected != true) {
                   3014: 		    selname[0].selected = true;
                   3015: 		}
1.42      ng       3016: 	    }
                   3017: 	}
1.125     ng       3018: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3019:     }
                   3020: 
                   3021:     function writeRadText(partid,weight) {
1.125     ng       3022: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3023: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3024:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3025: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3026: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3027: 	    for (var i=0; i<radioButton.length; i++) {
                   3028: 		radioButton[i].checked=false;
                   3029: 
                   3030: 	    }
                   3031: 	    textbox.value = "";
                   3032: 
                   3033: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3034: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3035: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3036: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3037: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3038: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3039: 		if ((saveval != "correct") || override) {
1.42      ng       3040: 		    scorename.value = "";
1.125     ng       3041: 		    if (selval[1].selected) {
                   3042: 			selname[1].selected = true;
                   3043: 		    } else {
                   3044: 			selname[2].selected = true;
                   3045: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3046: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3047: 		    }
1.42      ng       3048: 		}
                   3049: 	    }
1.43      ng       3050: 	} else {
                   3051: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3052: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3053: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3054: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3055: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3056: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3057: 		if ((saveval != "correct") || override) {
1.125     ng       3058: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3059: 		    selname[0].selected = true;
                   3060: 		}
                   3061: 	    }
                   3062: 	}	    
1.42      ng       3063:     }
                   3064: 
                   3065:     function changeSelect(partid,user) {
1.125     ng       3066: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3067: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3068: 	var point  = textbox.value;
1.125     ng       3069: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3070: 
1.109     matthew  3071: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3072: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3073: 	    textbox.value = "";
                   3074: 	    return;
                   3075: 	}
1.109     matthew  3076: 	if (parseFloat(point) > parseFloat(weight)) {
                   3077: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3078: 			       ") greater than the weight of the part. Accept?");
                   3079: 	    if (resp == false) {
                   3080: 		textbox.value = "";
                   3081: 		return;
                   3082: 	    }
                   3083: 	}
1.42      ng       3084: 	selval[0].selected = true;
                   3085:     }
                   3086: 
                   3087:     function changeOneScore(partid,user) {
1.125     ng       3088: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3089: 	if (selval[1].selected || selval[2].selected) {
                   3090: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3091: 	    if (selval[2].selected) {
                   3092: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3093: 	    }
1.269     raeburn  3094:         }
1.42      ng       3095:     }
                   3096: 
                   3097:     function resetEntry(numpart) {
                   3098: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3099: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3100: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3101: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3102: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3103: 	    for (var i=0; i<radioButton.length; i++) {
                   3104: 		radioButton[i].checked=false;
                   3105: 
                   3106: 	    }
                   3107: 	    textbox.value = "";
                   3108: 	    selval[0].selected = true;
                   3109: 
                   3110: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3111: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3112: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3113: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3114: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3115: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3116: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3117: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3118: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3119: 		if (saveselval == "excused") {
1.43      ng       3120: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3121: 		} else {
1.43      ng       3122: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3123: 		}
                   3124: 	    }
1.41      ng       3125: 	}
1.42      ng       3126:     }
                   3127: 
1.41      ng       3128: </script>
                   3129: VIEWJAVASCRIPT
1.42      ng       3130: }
                   3131: 
1.44      ng       3132: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3133: sub viewgrades {
                   3134:     my ($request) = shift;
                   3135:     &viewgrades_js($request);
1.41      ng       3136: 
1.324     albertel 3137:     my ($symb) = &get_symb($request);
1.168     albertel 3138:     #need to make sure we have the correct data for later EXT calls, 
                   3139:     #thus invalidate the cache
                   3140:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3141:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3142:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3143:     &Apache::lonnet::clear_EXT_cache_status();
                   3144: 
1.398     albertel 3145:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3146:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3147: 
                   3148:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3149:     $result.=&jscriptNform($symb);
1.41      ng       3150: 
1.44      ng       3151:     #beginning of class grading form
1.442     banghart 3152:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3153:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3154: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3155: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3156: 	&build_section_inputs().
1.257     albertel 3157: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3158: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3159: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3160: 
1.126     ng       3161:     my $sectionClass;
1.430     banghart 3162:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3163:     if ($env{'form.section'} eq 'all') {
1.126     ng       3164: 	$sectionClass='Class </h3>';
1.257     albertel 3165:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3166: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3167:     } else {
1.431     banghart 3168: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3169:     }
1.431     banghart 3170:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3171:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3172: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3173:     #radio buttons/text box for assigning points for a section or class.
                   3174:     #handles different parts of a problem
1.375     albertel 3175:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3176:     my %weight = ();
                   3177:     my $ctsparts = 0;
1.41      ng       3178:     $result.='<table border="0">';
1.45      ng       3179:     my %seen = ();
1.375     albertel 3180:     my @part_response_id = &flatten_responseType($responseType);
                   3181:     foreach my $part_response_id (@part_response_id) {
                   3182:     	my ($partid,$respid) = @{ $part_response_id };
                   3183: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3184: 	next if $seen{$partid};
                   3185: 	$seen{$partid}++;
1.375     albertel 3186: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3187: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3188: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3189: 
1.44      ng       3190: 	$result.='<input type="hidden" name="partid_'.
                   3191: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3192: 	$result.='<input type="hidden" name="weight_'.
                   3193: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3194: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3195: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3196: 	$result.='<table border="0"><tr>';  
1.41      ng       3197: 	my $ctr = 0;
1.42      ng       3198: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3199: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3200: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3201: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3202: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3203: 	    $ctr++;
                   3204: 	}
                   3205: 	$result.='</tr></table>';
1.44      ng       3206: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3207: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3208: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3209: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3210: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3211: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3212: 		$weight{$partid}.')"> '.
1.401     albertel 3213: 	    '<option selected="selected"> </option>'.
1.125     ng       3214: 	    '<option>excused</option>'.
1.265     www      3215: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3216:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3217: 	$ctsparts++;
1.41      ng       3218:     }
1.52      albertel 3219:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3220: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3221:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3222: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3223: 
1.44      ng       3224:     #table listing all the students in a section/class
                   3225:     #header of table
1.126     ng       3226:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3227:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3228: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3229: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3230:     my (@parts) = sort(&getpartlist($symb));
                   3231:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3232:     my @partids = ();
1.41      ng       3233:     foreach my $part (@parts) {
                   3234: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3235: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3236: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3237: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3238:         push(@partids, $partid);
1.324     albertel 3239: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3240: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3241: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3242: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3243: 	    next;
1.207     albertel 3244: 	} else {
                   3245: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3246: 	}
1.53      albertel 3247: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3248: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3249:     }
                   3250:     $result.='</tr>';
1.44      ng       3251: 
1.270     albertel 3252:     my %last_resets = 
                   3253: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3254: 
1.41      ng       3255:     #get info for each student
1.44      ng       3256:     #list all the students - with points and grade status
1.257     albertel 3257:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3258:     my $ctr = 0;
1.294     albertel 3259:     foreach (sort 
                   3260: 	     {
                   3261: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3262: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3263: 		 }
                   3264: 		 return $a cmp $b;
                   3265: 	     } (keys(%$fullname))) {
1.126     ng       3266: 	$ctr++;
1.324     albertel 3267: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3268: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3269:     }
                   3270:     $result.='</table></td></tr></table>';
                   3271:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3272:     $result.='<input type="button" value="Save" '.
1.417     albertel 3273: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3274:     if (scalar(%$fullname) eq 0) {
                   3275: 	my $colspan=3+scalar(@parts);
1.433     banghart 3276: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3277:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3278: 	$result='<span class="LC_warning">'.
                   3279: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3280: 	        $section_display, $stu_status).
1.433     banghart 3281: 	    '</span>';
1.96      albertel 3282:     }
1.324     albertel 3283:     $result.=&show_grading_menu_form($symb);
1.41      ng       3284:     return $result;
                   3285: }
                   3286: 
1.44      ng       3287: #--- call by previous routine to display each student
1.41      ng       3288: sub viewstudentgrade {
1.324     albertel 3289:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3290:     my ($uname,$udom) = split(/:/,$student);
                   3291:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3292:     my %aggregates = (); 
1.233     albertel 3293:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3294: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3295: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3296: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3297: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3298: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3299:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3300:     foreach my $apart (@$parts) {
                   3301: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3302: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3303:         $result.='<td align="center">';
1.269     raeburn  3304:         my ($aggtries,$totaltries);
                   3305:         unless (exists($aggregates{$part})) {
1.270     albertel 3306: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3307: 
                   3308: 	    $aggtries = $totaltries;
1.269     raeburn  3309:             if ($$last_resets{$part}) {  
1.270     albertel 3310:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3311: 					   $part);
                   3312:             }
1.269     raeburn  3313:             $result.='<input type="hidden" name="'.
                   3314:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3315:             $result.='<input type="hidden" name="'.
                   3316:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3317:             $aggregates{$part} = 1;
                   3318:         }
1.41      ng       3319: 	if ($type eq 'awarded') {
1.320     albertel 3320: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3321: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3322: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3323: 	    $result.='<input type="text" name="'.
1.89      albertel 3324: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3325: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3326: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3327: 	} elsif ($type eq 'solved') {
                   3328: 	    my ($status,$foo)=split(/_/,$score,2);
                   3329: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3330: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3331: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3332: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3333: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3334: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3335: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3336: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3337: 	    $result.='<option>reset status</option>';
1.126     ng       3338: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3339: 	} else {
                   3340: 	    $result.='<input type="hidden" name="'.
                   3341: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3342: 		    "\n";
1.233     albertel 3343: 	    $result.='<input type="text" name="'.
1.122     ng       3344: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3345: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3346: 	}
                   3347:     }
                   3348:     $result.='</tr>';
                   3349:     return $result;
1.38      ng       3350: }
                   3351: 
1.44      ng       3352: #--- change scores for all the students in a section/class
                   3353: #    record does not get update if unchanged
1.38      ng       3354: sub editgrades {
1.41      ng       3355:     my ($request) = @_;
                   3356: 
1.324     albertel 3357:     my $symb=&get_symb($request);
1.433     banghart 3358:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3359:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3360:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3361:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3362: 
1.44      ng       3363:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3364:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3365: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3366: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3367: 
                   3368:     my %scoreptr = (
                   3369: 		    'correct'  =>'correct_by_override',
                   3370: 		    'incorrect'=>'incorrect_by_override',
                   3371: 		    'excused'  =>'excused',
                   3372: 		    'ungraded' =>'ungraded_attempted',
                   3373: 		    'nothing'  => '',
                   3374: 		    );
1.257     albertel 3375:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3376: 
1.44      ng       3377:     my (@partid);
                   3378:     my %weight = ();
1.54      albertel 3379:     my %columns = ();
1.44      ng       3380:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3381: 
1.324     albertel 3382:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3383:     my $header;
1.257     albertel 3384:     while ($ctr < $env{'form.totalparts'}) {
                   3385: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3386: 	push @partid,$partid;
1.257     albertel 3387: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3388: 	$ctr++;
1.54      albertel 3389:     }
1.324     albertel 3390:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3391:     foreach my $partid (@partid) {
                   3392: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3393: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3394: 	$columns{$partid}=2;
                   3395: 	foreach my $stores (@parts) {
                   3396: 	    my ($part,$type) = &split_part_type($stores);
                   3397: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3398: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3399: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3400: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3401: 	    $display =~ s/Number of Attempts/Tries/;
                   3402: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3403: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3404: 	    $columns{$partid}+=2;
                   3405: 	}
                   3406:     }
                   3407:     foreach my $partid (@partid) {
1.324     albertel 3408: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3409: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3410: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3411: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3412: 
1.44      ng       3413:     }
                   3414:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3415:     $result .= $header;
1.44      ng       3416:     $result .= '</tr>'."\n";
1.93      albertel 3417:     my $noupdate;
1.126     ng       3418:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3419:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3420: 	my $line;
1.257     albertel 3421: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3422: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3423: 	my %newrecord;
                   3424: 	my $updateflag = 0;
1.281     albertel 3425: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3426: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3427: 	if (!&canmodify($usec)) {
1.126     ng       3428: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3429: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3430: 	    next;
                   3431: 	}
1.269     raeburn  3432:         my %aggregate = ();
                   3433:         my $aggregateflag = 0;
1.281     albertel 3434: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3435: 	foreach (@partid) {
1.257     albertel 3436: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3437: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3438: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3439: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3440: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3441: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3442: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3443: 	    my $score;
                   3444: 	    if ($partial eq '') {
1.257     albertel 3445: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3446: 	    } elsif ($partial > 0) {
                   3447: 		$score = 'correct_by_override';
                   3448: 	    } elsif ($partial == 0) {
                   3449: 		$score = 'incorrect_by_override';
                   3450: 	    }
1.257     albertel 3451: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3452: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3453: 
1.292     albertel 3454: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3455: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3456: 	    if ($dropMenu eq 'reset status' &&
                   3457: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3458: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3459: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3460: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3461: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3462: 		$updateflag = 1;
1.269     raeburn  3463:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3464:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3465:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3466:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3467:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3468:                     $aggregateflag = 1;
                   3469:                 }
1.139     albertel 3470: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3471: 		$updateflag = 1;
                   3472: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3473: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3474: 		$rec_update++;
1.125     ng       3475: 	    }
                   3476: 
1.93      albertel 3477: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3478: 		'<td align="center">'.$awarded.
                   3479: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3480: 
1.54      albertel 3481: 
                   3482: 	    my $partid=$_;
                   3483: 	    foreach my $stores (@parts) {
                   3484: 		my ($part,$type) = &split_part_type($stores);
                   3485: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3486: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3487: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3488: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3489: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3490: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3491: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3492: 		    $updateflag=1;
                   3493: 		}
1.93      albertel 3494: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3495: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3496: 	    }
1.44      ng       3497: 	}
1.93      albertel 3498: 	$line.='</tr>'."\n";
1.301     albertel 3499: 
                   3500: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3501: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3502: 
1.44      ng       3503: 	if ($updateflag) {
                   3504: 	    $count++;
1.257     albertel 3505: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3506: 				    $udom,$uname);
1.301     albertel 3507: 
                   3508: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3509: 					      $cnum,$udom,$uname)) {
                   3510: 		# need to figure out if should be in queue.
                   3511: 		my %record =  
                   3512: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3513: 					     $udom,$uname);
                   3514: 		my $all_graded = 1;
                   3515: 		my $none_graded = 1;
                   3516: 		foreach my $part (@parts) {
                   3517: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3518: 			$all_graded = 0;
                   3519: 		    } else {
                   3520: 			$none_graded = 0;
                   3521: 		    }
                   3522: 		}
                   3523: 
                   3524: 		if ($all_graded || $none_graded) {
                   3525: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3526: 							   $symb,$cdom,$cnum,
                   3527: 							   $udom,$uname);
                   3528: 		}
                   3529: 	    }
                   3530: 
1.126     ng       3531: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3532: 	    $updateCtr++;
1.93      albertel 3533: 	} else {
1.126     ng       3534: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3535: 	    $noupdateCtr++;
1.44      ng       3536: 	}
1.269     raeburn  3537:         if ($aggregateflag) {
                   3538:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3539: 				  $cdom,$cnum);
1.269     raeburn  3540:         }
1.93      albertel 3541:     }
                   3542:     if ($noupdate) {
1.126     ng       3543: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3544: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3545: 	$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       3546:     }
1.72      ng       3547:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3548: 	&show_grading_menu_form ($symb);
1.125     ng       3549:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3550: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3551: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3552:     return $title.$msg.$result;
1.5       albertel 3553: }
1.54      albertel 3554: 
                   3555: sub split_part_type {
                   3556:     my ($partstr) = @_;
                   3557:     my ($temp,@allparts)=split(/_/,$partstr);
                   3558:     my $type=pop(@allparts);
1.439     albertel 3559:     my $part=join('_',@allparts);
1.54      albertel 3560:     return ($part,$type);
                   3561: }
                   3562: 
1.44      ng       3563: #------------- end of section for handling grading by section/class ---------
                   3564: #
                   3565: #----------------------------------------------------------------------------
                   3566: 
1.5       albertel 3567: 
1.44      ng       3568: #----------------------------------------------------------------------------
                   3569: #
                   3570: #-------------------------- Next few routines handles grading by csv upload
                   3571: #
                   3572: #--- Javascript to handle csv upload
1.27      albertel 3573: sub csvupload_javascript_reverse_associate {
1.246     albertel 3574:     my $error1=&mt('You need to specify the username or ID');
                   3575:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3576:   return(<<ENDPICK);
                   3577:   function verify(vf) {
                   3578:     var foundsomething=0;
                   3579:     var founduname=0;
1.243     albertel 3580:     var foundID=0;
1.27      albertel 3581:     for (i=0;i<=vf.nfields.value;i++) {
                   3582:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3583:       if (i==0 && tw!=0) { foundID=1; }
                   3584:       if (i==1 && tw!=0) { founduname=1; }
                   3585:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3586:     }
1.246     albertel 3587:     if (founduname==0 && foundID==0) {
                   3588: 	alert('$error1');
                   3589: 	return;
1.27      albertel 3590:     }
                   3591:     if (foundsomething==0) {
1.246     albertel 3592: 	alert('$error2');
                   3593: 	return;
1.27      albertel 3594:     }
                   3595:     vf.submit();
                   3596:   }
                   3597:   function flip(vf,tf) {
                   3598:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3599:     var i;
                   3600:     for (i=0;i<=vf.nfields.value;i++) {
                   3601:       //can not pick the same destination field for both name and domain
                   3602:       if (((i ==0)||(i ==1)) && 
                   3603:           ((tf==0)||(tf==1)) && 
                   3604:           (i!=tf) &&
                   3605:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3606:         eval('vf.f'+i+'.selectedIndex=0;')
                   3607:       }
                   3608:     }
                   3609:   }
                   3610: ENDPICK
                   3611: }
                   3612: 
                   3613: sub csvupload_javascript_forward_associate {
1.246     albertel 3614:     my $error1=&mt('You need to specify the username or ID');
                   3615:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3616:   return(<<ENDPICK);
                   3617:   function verify(vf) {
                   3618:     var foundsomething=0;
                   3619:     var founduname=0;
1.243     albertel 3620:     var foundID=0;
1.27      albertel 3621:     for (i=0;i<=vf.nfields.value;i++) {
                   3622:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3623:       if (tw==1) { foundID=1; }
                   3624:       if (tw==2) { founduname=1; }
                   3625:       if (tw>3) { foundsomething=1; }
1.27      albertel 3626:     }
1.246     albertel 3627:     if (founduname==0 && foundID==0) {
                   3628: 	alert('$error1');
                   3629: 	return;
1.27      albertel 3630:     }
                   3631:     if (foundsomething==0) {
1.246     albertel 3632: 	alert('$error2');
                   3633: 	return;
1.27      albertel 3634:     }
                   3635:     vf.submit();
                   3636:   }
                   3637:   function flip(vf,tf) {
                   3638:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3639:     var i;
                   3640:     //can not pick the same destination field twice
                   3641:     for (i=0;i<=vf.nfields.value;i++) {
                   3642:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3643:         eval('vf.f'+i+'.selectedIndex=0;')
                   3644:       }
                   3645:     }
                   3646:   }
                   3647: ENDPICK
                   3648: }
                   3649: 
1.26      albertel 3650: sub csvuploadmap_header {
1.324     albertel 3651:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3652:     my $javascript;
1.257     albertel 3653:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3654: 	$javascript=&csvupload_javascript_reverse_associate();
                   3655:     } else {
                   3656: 	$javascript=&csvupload_javascript_forward_associate();
                   3657:     }
1.45      ng       3658: 
1.324     albertel 3659:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3660:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3661:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3662:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3663:     $request->print(<<ENDPICK);
1.26      albertel 3664: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3665: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3666: $result
1.326     albertel 3667: <hr />
1.26      albertel 3668: <h3>Identify fields</h3>
                   3669: Total number of records found in file: $distotal <hr />
                   3670: Enter as many fields as you can. The system will inform you and bring you back
                   3671: to this page if the data selected is insufficient to run your class.<hr />
                   3672: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3673: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3674: <input type="hidden" name="associate"  value="" />
                   3675: <input type="hidden" name="phase"      value="three" />
                   3676: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3677: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3678: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3679: <input type="hidden" name="upfile_associate" 
1.257     albertel 3680:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3681: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3682: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3683: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3684: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3685: <hr />
                   3686: <script type="text/javascript" language="Javascript">
                   3687: $javascript
                   3688: </script>
                   3689: ENDPICK
1.118     ng       3690:     return '';
1.26      albertel 3691: 
                   3692: }
                   3693: 
                   3694: sub csvupload_fields {
1.324     albertel 3695:     my ($symb) = @_;
                   3696:     my (@parts) = &getpartlist($symb);
1.243     albertel 3697:     my @fields=(['ID','Student ID'],
                   3698: 		['username','Student Username'],
                   3699: 		['domain','Student Domain']);
1.324     albertel 3700:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3701:     foreach my $part (sort(@parts)) {
                   3702: 	my @datum;
                   3703: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3704: 	my $name=$part;
                   3705: 	if  (!$display) { $display = $name; }
                   3706: 	@datum=($name,$display);
1.244     albertel 3707: 	if ($name=~/^stores_(.*)_awarded/) {
                   3708: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3709: 	}
1.41      ng       3710: 	push(@fields,\@datum);
                   3711:     }
                   3712:     return (@fields);
1.26      albertel 3713: }
                   3714: 
                   3715: sub csvuploadmap_footer {
1.41      ng       3716:     my ($request,$i,$keyfields) =@_;
                   3717:     $request->print(<<ENDPICK);
1.26      albertel 3718: </table>
                   3719: <input type="hidden" name="nfields" value="$i" />
                   3720: <input type="hidden" name="keyfields" value="$keyfields" />
                   3721: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3722: </form>
                   3723: ENDPICK
                   3724: }
                   3725: 
1.283     albertel 3726: sub checkforfile_js {
1.86      ng       3727:     my $result =<<CSVFORMJS;
                   3728: <script type="text/javascript" language="javascript">
                   3729:     function checkUpload(formname) {
                   3730: 	if (formname.upfile.value == "") {
                   3731: 	    alert("Please use the browse button to select a file from your local directory.");
                   3732: 	    return false;
                   3733: 	}
                   3734: 	formname.submit();
                   3735:     }
                   3736:     </script>
                   3737: CSVFORMJS
1.283     albertel 3738:     return $result;
                   3739: }
                   3740: 
                   3741: sub upcsvScores_form {
                   3742:     my ($request) = shift;
1.324     albertel 3743:     my ($symb)=&get_symb($request);
1.283     albertel 3744:     if (!$symb) {return '';}
                   3745:     my $result=&checkforfile_js();
1.257     albertel 3746:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3747:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3748:     $result.=$table;
1.326     albertel 3749:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3750:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3751:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3752: 	'.</b></td></tr>'."\n";
                   3753:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3754:     my $upload=&mt("Upload Scores");
1.86      ng       3755:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3756:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3757:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3758:     $result.=<<ENDUPFORM;
1.106     albertel 3759: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3760: <input type="hidden" name="symb" value="$symb" />
                   3761: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3762: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3763: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3764: $upfile_select
1.370     www      3765: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3766: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3767: </form>
                   3768: ENDUPFORM
1.370     www      3769:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3770:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3771:     .'</td></tr></table>'."\n";
1.86      ng       3772:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3773:     $result.=&show_grading_menu_form($symb);
1.86      ng       3774:     return $result;
                   3775: }
                   3776: 
                   3777: 
1.26      albertel 3778: sub csvuploadmap {
1.41      ng       3779:     my ($request)= @_;
1.324     albertel 3780:     my ($symb)=&get_symb($request);
1.41      ng       3781:     if (!$symb) {return '';}
1.72      ng       3782: 
1.41      ng       3783:     my $datatoken;
1.257     albertel 3784:     if (!$env{'form.datatoken'}) {
1.41      ng       3785: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3786:     } else {
1.257     albertel 3787: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3788: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3789:     }
1.41      ng       3790:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3791:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3792:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3793:     my ($i,$keyfields);
                   3794:     if (@records) {
1.324     albertel 3795: 	my @fields=&csvupload_fields($symb);
1.45      ng       3796: 
1.257     albertel 3797: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3798: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3799: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3800: 							  \@fields);
                   3801: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3802: 	    chop($keyfields);
                   3803: 	} else {
                   3804: 	    unshift(@fields,['none','']);
                   3805: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3806: 							    \@fields);
1.311     banghart 3807:             foreach my $rec (@records) {
                   3808:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3809:                 if (%temp) {
                   3810:                     $keyfields=join(',',sort(keys(%temp)));
                   3811:                     last;
                   3812:                 }
                   3813:             }
1.41      ng       3814: 	}
                   3815:     }
                   3816:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3817:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3818: 
1.41      ng       3819:     return '';
1.27      albertel 3820: }
                   3821: 
1.246     albertel 3822: sub csvuploadoptions {
1.41      ng       3823:     my ($request)= @_;
1.324     albertel 3824:     my ($symb)=&get_symb($request);
1.257     albertel 3825:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3826:     my $ignore=&mt('Ignore First Line');
                   3827:     $request->print(<<ENDPICK);
                   3828: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3829: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3830: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3831: <!--
1.246     albertel 3832: <p>
                   3833: <label>
                   3834:    <input type="checkbox" name="show_full_results" />
                   3835:    Show a table of all changes
                   3836: </label>
                   3837: </p>
1.302     albertel 3838: -->
1.246     albertel 3839: <p>
                   3840: <label>
                   3841:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3842:    Overwrite any existing score
                   3843: </label>
                   3844: </p>
                   3845: ENDPICK
                   3846:     my %fields=&get_fields();
                   3847:     if (!defined($fields{'domain'})) {
1.257     albertel 3848: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3849: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3850:     }
1.257     albertel 3851:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3852: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3853: 	my $cleankey=$1;
                   3854: 	if ($cleankey eq 'command') { next; }
                   3855: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3856: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3857:     }
                   3858:     # FIXME do a check for any duplicated user ids...
                   3859:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3860:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3861: <hr /></form>'."\n");
1.324     albertel 3862:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3863:     return '';
                   3864: }
                   3865: 
                   3866: sub get_fields {
                   3867:     my %fields;
1.257     albertel 3868:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3869:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3870: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3871: 	    if ($env{'form.f'.$i} ne 'none') {
                   3872: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3873: 	    }
                   3874: 	} else {
1.257     albertel 3875: 	    if ($env{'form.f'.$i} ne 'none') {
                   3876: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3877: 	    }
                   3878: 	}
1.27      albertel 3879:     }
1.246     albertel 3880:     return %fields;
                   3881: }
                   3882: 
                   3883: sub csvuploadassign {
                   3884:     my ($request)= @_;
1.324     albertel 3885:     my ($symb)=&get_symb($request);
1.246     albertel 3886:     if (!$symb) {return '';}
1.345     bowersj2 3887:     my $error_msg = '';
1.246     albertel 3888:     &Apache::loncommon::load_tmp_file($request);
                   3889:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3890:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3891:     my %fields=&get_fields();
1.41      ng       3892:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3893:     my $courseid=$env{'request.course.id'};
1.97      albertel 3894:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3895:     my @notallowed;
1.41      ng       3896:     my @skipped;
                   3897:     my $countdone=0;
                   3898:     foreach my $grade (@gradedata) {
                   3899: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3900: 	my $domain;
                   3901: 	if ($entries{$fields{'domain'}}) {
                   3902: 	    $domain=$entries{$fields{'domain'}};
                   3903: 	} else {
1.257     albertel 3904: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3905: 	}
1.243     albertel 3906: 	$domain=~s/\s//g;
1.41      ng       3907: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3908: 	$username=~s/\s//g;
1.243     albertel 3909: 	if (!$username) {
                   3910: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3911: 	    $id=~s/\s//g;
1.243     albertel 3912: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3913: 	    $username=$ids{$id};
                   3914: 	}
1.41      ng       3915: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3916: 	    my $id=$entries{$fields{'ID'}};
                   3917: 	    $id=~s/\s//g;
                   3918: 	    if ($id) {
                   3919: 		push(@skipped,"$id:$domain");
                   3920: 	    } else {
                   3921: 		push(@skipped,"$username:$domain");
                   3922: 	    }
1.41      ng       3923: 	    next;
                   3924: 	}
1.108     albertel 3925: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3926: 	if (!&canmodify($usec)) {
                   3927: 	    push(@notallowed,"$username:$domain");
                   3928: 	    next;
                   3929: 	}
1.244     albertel 3930: 	my %points;
1.41      ng       3931: 	my %grades;
                   3932: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3933: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3934: 		$dest eq 'domain') { next; }
                   3935: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3936: 	    if ($dest=~/stores_(.*)_points/) {
                   3937: 		my $part=$1;
                   3938: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3939: 					      $symb,$domain,$username);
1.345     bowersj2 3940:                 if ($wgt) {
                   3941:                     $entries{$fields{$dest}}=~s/\s//g;
                   3942:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 3943:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   3944:                                           : 'correct_by_override';
1.345     bowersj2 3945:                     $grades{"resource.$part.awarded"}=$pcr;
                   3946:                     $grades{"resource.$part.solved"}=$award;
                   3947:                     $points{$part}=1;
                   3948:                 } else {
                   3949:                     $error_msg = "<br />" .
                   3950:                         &mt("Some point values were assigned"
                   3951:                             ." for problems with a weight "
                   3952:                             ."of zero. These values were "
                   3953:                             ."ignored.");
                   3954:                 }
1.244     albertel 3955: 	    } else {
                   3956: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3957: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3958: 		my $store_key=$dest;
                   3959: 		$store_key=~s/^stores/resource/;
                   3960: 		$store_key=~s/_/\./g;
                   3961: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3962: 	    }
1.41      ng       3963: 	}
1.398     albertel 3964: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3965: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3966: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3967: 					   $env{'request.course.id'},
                   3968: 					   $domain,$username);
                   3969: 	if ($result eq 'ok') {
                   3970: 	    $request->print('.');
                   3971: 	} else {
                   3972: 	    $request->print("<p>
1.398     albertel 3973:                               <span class=\"LC_error\">
                   3974:                                  Failed to save student $username:$domain.
                   3975:                                  Message when trying to save was ($result)
                   3976:                               </span>
1.302     albertel 3977:                              </p>" );
                   3978: 	}
1.41      ng       3979: 	$request->rflush();
                   3980: 	$countdone++;
                   3981:     }
1.398     albertel 3982:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3983:     if (@skipped) {
1.398     albertel 3984: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3985: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3986:     }
                   3987:     if (@notallowed) {
1.398     albertel 3988: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3989: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3990:     }
1.106     albertel 3991:     $request->print("<br />\n");
1.324     albertel 3992:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3993:     return $error_msg;
1.26      albertel 3994: }
1.44      ng       3995: #------------- end of section for handling csv file upload ---------
                   3996: #
                   3997: #-------------------------------------------------------------------
                   3998: #
1.122     ng       3999: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4000: #
                   4001: #--- Select a page/sequence and a student to grade
1.68      ng       4002: sub pickStudentPage {
                   4003:     my ($request) = shift;
                   4004: 
                   4005:     $request->print(<<LISTJAVASCRIPT);
                   4006: <script type="text/javascript" language="javascript">
                   4007: 
                   4008: function checkPickOne(formname) {
1.76      ng       4009:     if (radioSelection(formname.student) == null) {
1.68      ng       4010: 	alert("Please select the student you wish to grade.");
                   4011: 	return;
                   4012:     }
1.125     ng       4013:     ptr = pullDownSelection(formname.selectpage);
                   4014:     formname.page.value = formname["page"+ptr].value;
                   4015:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4016:     formname.submit();
                   4017: }
                   4018: 
                   4019: </script>
                   4020: LISTJAVASCRIPT
1.118     ng       4021:     &commonJSfunctions($request);
1.324     albertel 4022:     my ($symb) = &get_symb($request);
1.257     albertel 4023:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4024:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4025:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4026: 
1.398     albertel 4027:     my $result='<h3><span class="LC_info">&nbsp;'.
                   4028: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       4029: 
1.80      ng       4030:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       4031:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 4032:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4033:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4034: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4035: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4036:     my $ctr=0;
1.68      ng       4037:     foreach (@$titles) {
                   4038: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4039: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4040: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4041: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4042: 	$ctr++;
1.68      ng       4043:     }
1.326     albertel 4044:     $result.= '</select>'."<br />\n";
1.70      ng       4045:     $ctr=0;
                   4046:     foreach (@$titles) {
                   4047: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4048: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4049: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4050: 	$ctr++;
                   4051:     }
1.72      ng       4052:     $result.='<input type="hidden" name="page" />'."\n".
                   4053: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4054: 
1.401     albertel 4055:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4056: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4057: 
1.71      ng       4058:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4059: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4060: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4061: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4062:     
                   4063:     $result.=&build_section_inputs();
1.442     banghart 4064:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4065:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4066: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4067: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4068: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4069: 
1.382     albertel 4070:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4071: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4072: 
1.80      ng       4073:     $result.='&nbsp;<input type="button" '.
1.126     ng       4074: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4075: 
1.68      ng       4076:     $request->print($result);
                   4077: 
1.326     albertel 4078:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4079: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4080: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4081: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4082: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4083: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4084: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4085:  
1.76      ng       4086:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4087:     my $ptr = 1;
1.294     albertel 4088:     foreach my $student (sort 
                   4089: 			 {
                   4090: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4091: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4092: 			     }
                   4093: 			     return $a cmp $b;
                   4094: 			 } (keys(%$fullname))) {
1.68      ng       4095: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4096: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4097: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4098: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4099: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4100: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4101: 	$ptr++;
                   4102:     }
1.381     albertel 4103:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4104:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4105:     $studentTable.='<input type="button" '.
                   4106: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4107: 
1.324     albertel 4108:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4109:     $request->print($studentTable);
                   4110: 
                   4111:     return '';
                   4112: }
                   4113: 
                   4114: sub getSymbMap {
1.132     bowersj2 4115:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4116: 
                   4117:     my %symbx = ();
                   4118:     my @titles = ();
1.117     bowersj2 4119:     my $minder = 0;
                   4120: 
                   4121:     # Gather every sequence that has problems.
1.240     albertel 4122:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4123: 					       1,0,1);
1.117     bowersj2 4124:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4125: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4126: 	    my $title = $minder.'.'.
                   4127: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4128: 	    push(@titles, $title); # minder in case two titles are identical
                   4129: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4130: 	    $minder++;
1.241     albertel 4131: 	}
1.68      ng       4132:     }
                   4133:     return \@titles,\%symbx;
                   4134: }
                   4135: 
1.72      ng       4136: #
                   4137: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4138: sub displayPage {
                   4139:     my ($request) = shift;
                   4140: 
1.324     albertel 4141:     my ($symb) = &get_symb($request);
1.257     albertel 4142:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4143:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4144:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4145:     my $pageTitle = $env{'form.page'};
1.103     albertel 4146:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4147:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4148:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4149: 
                   4150:     #need to make sure we have the correct data for later EXT calls, 
                   4151:     #thus invalidate the cache
                   4152:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4153:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4154:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4155:     &Apache::lonnet::clear_EXT_cache_status();
                   4156: 
1.103     albertel 4157:     if (!&canview($usec)) {
1.398     albertel 4158: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4159: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4160: 	return;
                   4161:     }
1.398     albertel 4162:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4163:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4164: 	'</h3>'."\n";
1.382     albertel 4165:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4166: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4167:     } else {
                   4168: 	delete($env{'form.CODE'});
                   4169:     }
1.71      ng       4170:     &sub_page_js($request);
                   4171:     $request->print($result);
                   4172: 
1.132     bowersj2 4173:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4174:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4175:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4176:     if (!$map) {
1.398     albertel 4177: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4178: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4179: 	return; 
                   4180:     }
1.68      ng       4181:     my $iterator = $navmap->getIterator($map->map_start(),
                   4182: 					$map->map_finish());
                   4183: 
1.71      ng       4184:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4185: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4186: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4187: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4188: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4189: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4190: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4191: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4192: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4193: 
1.382     albertel 4194:     if (defined($env{'form.CODE'})) {
                   4195: 	$studentTable.=
                   4196: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4197:     }
1.381     albertel 4198:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4199: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4200: 	'/check.gif" height="16" border="0" />';
                   4201: 
1.118     ng       4202:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4203: 	' symbol.'."\n".
1.71      ng       4204: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4205: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4206: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4207: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4208: 
1.329     albertel 4209:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4210:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4211:     $iterator->next(); # skip the first BEGIN_MAP
                   4212:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4213:     while ($depth > 0) {
1.68      ng       4214:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4215:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4216: 
1.385     albertel 4217:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4218: 	    my $parts = $curRes->parts();
1.68      ng       4219:             my $title = $curRes->compTitle();
1.71      ng       4220: 	    my $symbx = $curRes->symb();
1.196     albertel 4221: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4222: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4223: 	    $studentTable.='<td valign="top">';
1.382     albertel 4224: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4225: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4226: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4227: 					     undef,'both',\%form);
1.71      ng       4228: 	    } else {
1.382     albertel 4229: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4230: 		$companswer =~ s|<form(.*?)>||g;
                   4231: 		$companswer =~ s|</form>||g;
1.71      ng       4232: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4233: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4234: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4235: #		}
1.116     ng       4236: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4237: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4238: 	    }
                   4239: 
1.257     albertel 4240: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4241: 
1.257     albertel 4242: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4243: 		if ($record{'version'} eq '') {
1.398     albertel 4244: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4245: 		} else {
1.116     ng       4246: 		    my %responseType = ();
                   4247: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4248: 			my @responseIds =$curRes->responseIds($partid);
                   4249: 			my @responseType =$curRes->responseType($partid);
                   4250: 			my %responseIds;
                   4251: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4252: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4253: 			}
                   4254: 			$responseType{$partid} = \%responseIds;
1.116     ng       4255: 		    }
1.148     albertel 4256: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4257: 
1.71      ng       4258: 		}
1.257     albertel 4259: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4260: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4261: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4262: 									$env{'request.course.id'},
1.71      ng       4263: 									'','.submission');
                   4264:  
                   4265: 	    }
1.103     albertel 4266: 	    if (&canmodify($usec)) {
                   4267: 		foreach my $partid (@{$parts}) {
                   4268: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4269: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4270: 		    $question++;
                   4271: 		}
1.196     albertel 4272: 		$prob++;
1.71      ng       4273: 	    }
                   4274: 	    $studentTable.='</td></tr>';
1.68      ng       4275: 
1.103     albertel 4276: 	}
1.68      ng       4277:         $curRes = $iterator->next();
                   4278:     }
                   4279: 
1.381     albertel 4280:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4281: 	'<input type="button" value="Save" '.
1.381     albertel 4282: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4283: 	'</form>'."\n";
1.324     albertel 4284:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4285:     $request->print($studentTable);
                   4286: 
                   4287:     return '';
1.119     ng       4288: }
                   4289: 
                   4290: sub displaySubByDates {
1.148     albertel 4291:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4292:     my $isCODE=0;
1.335     albertel 4293:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4294:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4295:     my $studentTable=&Apache::loncommon::start_data_table().
                   4296: 	&Apache::loncommon::start_data_table_header_row().
                   4297: 	'<th>'.&mt('Date/Time').'</th>'.
                   4298: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4299: 	'<th>'.&mt('Submission').'</th>'.
                   4300: 	'<th>'.&mt('Status').'</th>'.
                   4301: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4302:     my ($version);
                   4303:     my %mark;
1.148     albertel 4304:     my %orders;
1.119     ng       4305:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4306:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4307: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4308:     }
1.335     albertel 4309: 
                   4310:     my $interaction;
1.119     ng       4311:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4312: 	my $timestamp = 
                   4313: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4314: 	if (exists($$record{$version.':resource.0.version'})) {
                   4315: 	    $interaction = $$record{$version.':resource.0.version'};
                   4316: 	}
                   4317: 
                   4318: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4319: 		             : "$version:resource");
1.467     albertel 4320: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4321: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4322: 	if ($isCODE) {
                   4323: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4324: 	}
1.119     ng       4325: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4326: 	my @displaySub = ();
                   4327: 	foreach my $partid (@{$parts}) {
1.335     albertel 4328: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4329: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4330: 	    
                   4331: 
1.122     ng       4332: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4333: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4334: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4335: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4336: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4337: 
                   4338: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4339: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4340: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4341: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4342: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4343: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4344: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4345: 		    } else {
1.467     albertel 4346: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4347: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4348: 		    }
1.335     albertel 4349: 		    my $responseType=($isTask ? 'Task'
                   4350:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4351: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4352: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4353: 			$orders{$partid}->{$responseId}=
                   4354: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4355: 		    }
1.147     albertel 4356: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4357: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4358: 		}
                   4359: 	    }
1.335     albertel 4360: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4361: 		$displaySub[1].='Checked in by '.
                   4362: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4363: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4364: 		    '<br />';
                   4365: 	    }
                   4366: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4367: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4368: 		    lc($$record{"$where.$partid.award"}).' '.
                   4369: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4370: 		    '<br />';
                   4371: 	    }
1.335     albertel 4372: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4373: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4374: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4375: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4376: 		$displaySub[2].=
                   4377: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4378: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4379: 	    }
                   4380: 	}
                   4381: 	# needed because old essay regrader has not parts info
                   4382: 	if (exists $$record{"$version:resource.regrader"}) {
                   4383: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4384: 	}
                   4385: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4386: 	if ($displaySub[2]) {
1.467     albertel 4387: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4388: 	}
1.467     albertel 4389: 	$studentTable.='&nbsp;</td>'.
                   4390: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4391:     }
1.467     albertel 4392:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4393:     return $studentTable;
1.71      ng       4394: }
                   4395: 
                   4396: sub updateGradeByPage {
                   4397:     my ($request) = shift;
                   4398: 
1.257     albertel 4399:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4400:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4401:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4402:     my $pageTitle = $env{'form.page'};
1.103     albertel 4403:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4404:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4405:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4406:     if (!&canmodify($usec)) {
1.398     albertel 4407: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4408: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4409: 	return;
                   4410:     }
1.398     albertel 4411:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4412:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4413: 	'</h3>'."\n";
1.70      ng       4414: 
1.68      ng       4415:     $request->print($result);
                   4416: 
1.132     bowersj2 4417:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4418:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4419:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4420:     if (!$map) {
1.398     albertel 4421: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4422: 	my ($symb)=&get_symb($request);
                   4423: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4424: 	return; 
                   4425:     }
1.71      ng       4426:     my $iterator = $navmap->getIterator($map->map_start(),
                   4427: 					$map->map_finish());
1.70      ng       4428: 
1.71      ng       4429:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4430: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4431: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4432: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4433: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4434: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4435: 
                   4436:     $iterator->next(); # skip the first BEGIN_MAP
                   4437:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4438:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4439:     while ($depth > 0) {
1.71      ng       4440:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4441:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4442: 
1.385     albertel 4443:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4444: 	    my $parts = $curRes->parts();
1.71      ng       4445:             my $title = $curRes->compTitle();
                   4446: 	    my $symbx = $curRes->symb();
1.196     albertel 4447: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4448: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4449: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4450: 
                   4451: 	    my %newrecord=();
                   4452: 	    my @displayPts=();
1.269     raeburn  4453:             my %aggregate = ();
                   4454:             my $aggregateflag = 0;
1.71      ng       4455: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4456: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4457: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4458: 
1.257     albertel 4459: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4460: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4461: 		my $partial = $newpts/$wgt;
                   4462: 		my $score;
                   4463: 		if ($partial > 0) {
                   4464: 		    $score = 'correct_by_override';
1.125     ng       4465: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4466: 		    $score = 'incorrect_by_override';
                   4467: 		}
1.257     albertel 4468: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4469: 		if ($dropMenu eq 'excused') {
1.71      ng       4470: 		    $partial = '';
                   4471: 		    $score = 'excused';
1.125     ng       4472: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4473: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4474: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4475: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4476: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4477: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4478: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4479: 		    $changeflag++;
                   4480: 		    $newpts = '';
1.269     raeburn  4481:                     
                   4482:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4483:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4484:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4485:                     if ($aggtries > 0) {
                   4486:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4487:                         $aggregateflag = 1;
                   4488:                     }
1.71      ng       4489: 		}
1.324     albertel 4490: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4491: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4492: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4493: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4494: 		    '&nbsp;<br />';
1.207     albertel 4495: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4496: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4497: 		    '&nbsp;<br />';
1.71      ng       4498: 		$question++;
1.380     albertel 4499: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4500: 
1.71      ng       4501: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4502: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4503: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4504: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4505: 
                   4506: 		$changeflag++;
                   4507: 	    }
                   4508: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4509: 		my %record = 
                   4510: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4511: 					     $udom,$uname);
                   4512: 
                   4513: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4514: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4515: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4516: 		    $newrecord{'resource.CODE'} = '';
                   4517: 		}
1.257     albertel 4518: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4519: 					$udom,$uname);
1.382     albertel 4520: 		%record = &Apache::lonnet::restore($symbx,
                   4521: 						   $env{'request.course.id'},
                   4522: 						   $udom,$uname);
1.380     albertel 4523: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4524: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4525: 	    }
1.380     albertel 4526: 	    
1.269     raeburn  4527:             if ($aggregateflag) {
                   4528:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4529:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4530:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4531:             }
1.125     ng       4532: 
1.71      ng       4533: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4534: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4535: 		'</tr>';
1.68      ng       4536: 
1.196     albertel 4537: 	    $prob++;
1.68      ng       4538: 	}
1.71      ng       4539:         $curRes = $iterator->next();
1.68      ng       4540:     }
1.98      albertel 4541: 
1.71      ng       4542:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4543:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4544:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4545: 		  'The scores were changed for '.
                   4546: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4547:     $request->print($grademsg.$studentTable);
1.68      ng       4548: 
1.70      ng       4549:     return '';
                   4550: }
                   4551: 
1.72      ng       4552: #-------- end of section for handling grading by page/sequence ---------
                   4553: #
                   4554: #-------------------------------------------------------------------
                   4555: 
1.75      albertel 4556: #--------------------Scantron Grading-----------------------------------
                   4557: #
                   4558: #------ start of section for handling grading by page/sequence ---------
                   4559: 
1.423     albertel 4560: =pod
                   4561: 
                   4562: =head1 Bubble sheet grading routines
                   4563: 
1.424     albertel 4564:   For this documentation:
                   4565: 
                   4566:    'scanline' refers to the full line of characters
                   4567:    from the file that we are parsing that represents one entire sheet
                   4568: 
                   4569:    'bubble line' refers to the data
                   4570:    representing the line of bubbles that are on the physical bubble sheet
                   4571: 
                   4572: 
                   4573: The overall process is that a scanned in bubble sheet data is uploaded
                   4574: into a course. When a user wants to grade, they select a
                   4575: sequence/folder of resources, a file of bubble sheet info, and pick
                   4576: one of the predefined configurations for what each scanline looks
                   4577: like.
                   4578: 
                   4579: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4580: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4581: because too light bubbling), 'double bubble' (each bubble line should
                   4582: have no more that one letter picked), invalid or duplicated CODE,
                   4583: invalid student ID
                   4584: 
                   4585: If the CODE option is used that determines the randomization of the
                   4586: homework problems, either way the student ID is looked up into a
                   4587: username:domain.
                   4588: 
                   4589: During the validation phase the instructor can choose to skip scanlines. 
                   4590: 
1.435     foxr     4591: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4592: 
                   4593:   scantron_original_filename (unmodified original file)
                   4594:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4595:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4596: 
                   4597: Also there is a separate hash nohist_scantrondata that contains extra
                   4598: correction information that isn't representable in the bubble sheet
                   4599: file (see &scantron_getfile() for more information)
                   4600: 
                   4601: After all scanlines are either valid, marked as valid or skipped, then
                   4602: foreach line foreach problem in the picked sequence, an ssi request is
                   4603: made that simulates a user submitting their selected letter(s) against
                   4604: the homework problem.
1.423     albertel 4605: 
                   4606: =over 4
                   4607: 
                   4608: 
                   4609: 
                   4610: =item defaultFormData
                   4611: 
                   4612:   Returns html hidden inputs used to hold context/default values.
                   4613: 
                   4614:  Arguments:
                   4615:   $symb - $symb of the current resource 
                   4616: 
                   4617: =cut
1.422     foxr     4618: 
1.81      albertel 4619: sub defaultFormData {
1.324     albertel 4620:     my ($symb)=@_;
1.447     foxr     4621:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4622:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4623:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4624: }
                   4625: 
1.447     foxr     4626: 
1.423     albertel 4627: =pod 
                   4628: 
                   4629: =item getSequenceDropDown
                   4630: 
                   4631:    Return html dropdown of possible sequences to grade
                   4632:  
                   4633:  Arguments:
                   4634:    $symb - $symb of the current resource 
                   4635: 
                   4636: =cut
1.422     foxr     4637: 
1.75      albertel 4638: sub getSequenceDropDown {
1.423     albertel 4639:     my ($symb)=@_;
1.75      albertel 4640:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4641:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4642:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4643:     my $ctr=0;
                   4644:     foreach (@$titles) {
                   4645: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4646: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4647: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4648: 	    '>'.$showtitle.'</option>'."\n";
                   4649: 	$ctr++;
                   4650:     }
                   4651:     $result.= '</select>';
                   4652:     return $result;
                   4653: }
                   4654: 
1.423     albertel 4655: 
                   4656: =pod 
                   4657: 
                   4658: =item scantron_filenames
                   4659: 
                   4660:    Returns a list of the scantron files in the current course 
                   4661: 
                   4662: =cut
1.422     foxr     4663: 
1.202     albertel 4664: sub scantron_filenames {
1.257     albertel 4665:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4666:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4667:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4668: 				    &propath($cdom,$cname));
1.202     albertel 4669:     my @possiblenames;
1.201     albertel 4670:     foreach my $filename (sort(@files)) {
1.157     albertel 4671: 	($filename)=split(/&/,$filename);
                   4672: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4673: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4674: 	push(@possiblenames,$filename);
                   4675:     }
                   4676:     return @possiblenames;
                   4677: }
                   4678: 
1.423     albertel 4679: =pod 
                   4680: 
                   4681: =item scantron_uploads
                   4682: 
                   4683:    Returns  html drop-down list of scantron files in current course.
                   4684: 
                   4685:  Arguments:
                   4686:    $file2grade - filename to set as selected in the dropdown
                   4687: 
                   4688: =cut
1.422     foxr     4689: 
1.202     albertel 4690: sub scantron_uploads {
1.209     ng       4691:     my ($file2grade) = @_;
1.202     albertel 4692:     my $result=	'<select name="scantron_selectfile">';
                   4693:     $result.="<option></option>";
                   4694:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4695: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4696:     }
                   4697:     $result.="</select>";
                   4698:     return $result;
                   4699: }
                   4700: 
1.423     albertel 4701: =pod 
                   4702: 
                   4703: =item scantron_scantab
                   4704: 
                   4705:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4706:   file.
                   4707: 
                   4708: =cut
1.422     foxr     4709: 
1.82      albertel 4710: sub scantron_scantab {
                   4711:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4712:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4713:     $result.='<option></option>'."\n";
1.82      albertel 4714:     foreach my $line (<$fh>) {
                   4715: 	my ($name,$descrip)=split(/:/,$line);
                   4716: 	if ($name =~ /^\#/) { next; }
                   4717: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4718:     }
                   4719:     $result.='</select>'."\n";
                   4720: 
                   4721:     return $result;
                   4722: }
                   4723: 
1.423     albertel 4724: =pod 
                   4725: 
                   4726: =item scantron_CODElist
                   4727: 
                   4728:   Returns html drop down of the saved CODE lists from current course,
                   4729:   generated from earlier printings.
                   4730: 
                   4731: =cut
1.422     foxr     4732: 
1.186     albertel 4733: sub scantron_CODElist {
1.257     albertel 4734:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4735:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4736:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4737:     my $namechoice='<option></option>';
1.225     albertel 4738:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4739: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4740: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4741: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4742:     }
                   4743:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4744:     return $namechoice;
                   4745: }
                   4746: 
1.423     albertel 4747: =pod 
                   4748: 
                   4749: =item scantron_CODEunique
                   4750: 
                   4751:   Returns the html for "Each CODE to be used once" radio.
                   4752: 
                   4753: =cut
1.422     foxr     4754: 
1.186     albertel 4755: sub scantron_CODEunique {
1.381     albertel 4756:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4757:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4758:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4759:                 </span>
                   4760:                 <span style="white-space: nowrap;">
1.272     albertel 4761:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4762:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4763:                 </span>';
1.186     albertel 4764:     return $result;
                   4765: }
1.423     albertel 4766: 
                   4767: =pod 
                   4768: 
                   4769: =item scantron_selectphase
                   4770: 
                   4771:   Generates the initial screen to start the bubble sheet process.
                   4772:   Allows for - starting a grading run.
1.424     albertel 4773:              - downloading existing scan data (original, corrected
1.423     albertel 4774:                                                 or skipped info)
                   4775: 
                   4776:              - uploading new scan data
                   4777: 
                   4778:  Arguments:
                   4779:   $r          - The Apache request object
                   4780:   $file2grade - name of the file that contain the scanned data to score
                   4781: 
                   4782: =cut
1.186     albertel 4783: 
1.75      albertel 4784: sub scantron_selectphase {
1.209     ng       4785:     my ($r,$file2grade) = @_;
1.324     albertel 4786:     my ($symb)=&get_symb($r);
1.75      albertel 4787:     if (!$symb) {return '';}
1.423     albertel 4788:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4789:     my $default_form_data=&defaultFormData($symb);
                   4790:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4791:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4792:     my $format_selector=&scantron_scantab();
1.186     albertel 4793:     my $CODE_selector=&scantron_CODElist();
                   4794:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4795:     my $result;
1.422     foxr     4796: 
                   4797:     # Chunk of form to prompt for a file to grade and how:
                   4798: 
1.75      albertel 4799:     $result.= <<SCANTRONFORM;
1.162     albertel 4800:     <table width="100%" border="0">
1.75      albertel 4801:     <tr>
1.226     albertel 4802:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4803:       <td bgcolor="#777777">
1.203     albertel 4804:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4805:         $default_form_data
1.75      albertel 4806:         <table width="100%" border="0">
                   4807:           <tr bgcolor="#e6ffff">
1.174     albertel 4808:             <td colspan="2">
                   4809:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4810:             </td>
                   4811:           </tr>
                   4812:           <tr bgcolor="#ffffe6">
1.174     albertel 4813:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4814:           </tr>
                   4815:           <tr bgcolor="#ffffe6">
1.174     albertel 4816:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4817:           </tr>
1.82      albertel 4818:           <tr bgcolor="#ffffe6">
1.174     albertel 4819:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4820:           </tr>
1.157     albertel 4821:           <tr bgcolor="#ffffe6">
1.186     albertel 4822:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4823:           </tr>
                   4824:           <tr bgcolor="#ffffe6">
                   4825:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4826:           </tr>
                   4827:           <tr bgcolor="#ffffe6">
1.187     albertel 4828: 	    <td> Options: </td>
                   4829:             <td>
1.272     albertel 4830: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4831:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4832:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4833: 	    </td>
                   4834:           </tr>
                   4835:           <tr bgcolor="#ffffe6">
1.174     albertel 4836:             <td colspan="2">
1.265     www      4837:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4838:             </td>
                   4839:           </tr>
                   4840:         </table>
1.226     albertel 4841:        </td>
                   4842:      </form>
1.162     albertel 4843:     </tr>
                   4844: SCANTRONFORM
                   4845:    
                   4846:     $r->print($result);
                   4847: 
1.257     albertel 4848:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4849:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4850: 
1.422     foxr     4851: 	# Chunk of form to prompt for a scantron file upload.
                   4852: 
1.162     albertel 4853:         $r->print(<<SCANTRONFORM);
                   4854:     <tr>
                   4855:       <td bgcolor="#777777">
                   4856:         <table width="100%" border="0">
                   4857:           <tr bgcolor="#e6ffff">
                   4858:             <td>
1.174     albertel 4859:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4860:             </td>
                   4861:           </tr>
                   4862:           <tr bgcolor="#ffffe6">
                   4863:             <td>
                   4864: SCANTRONFORM
1.324     albertel 4865:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4866:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4867:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4868:     $r->print(<<UPLOAD);
                   4869:               <script type="text/javascript" language="javascript">
                   4870:     function checkUpload(formname) {
                   4871: 	if (formname.upfile.value == "") {
                   4872: 	    alert("Please use the browse button to select a file from your local directory.");
                   4873: 	    return false;
                   4874: 	}
                   4875: 	formname.submit();
                   4876:     }
                   4877:               </script>
                   4878: 
                   4879:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4880:                 $default_form_data
                   4881:                 <input name='courseid' type='hidden' value='$cnum' />
                   4882:                 <input name='domainid' type='hidden' value='$cdom' />
                   4883:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4884:                 File to upload:<input type="file" name="upfile" size="50" />
                   4885:                 <br />
                   4886:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4887:               </form>
                   4888: UPLOAD
1.162     albertel 4889: 
                   4890:         $r->print(<<SCANTRONFORM);
                   4891:             </td>
                   4892:           </tr>
1.75      albertel 4893:         </table>
                   4894:       </td>
                   4895:     </tr>
1.162     albertel 4896: SCANTRONFORM
                   4897:     }
1.422     foxr     4898: 
                   4899:     # Chunk of the form that prompts to view a scoring office file,
                   4900:     # corrected file, skipped records in a file.
                   4901: 
1.187     albertel 4902:     $r->print(<<SCANTRONFORM);
                   4903:     <tr>
1.226     albertel 4904:       <form action='/adm/grades' name='scantron_download'>
                   4905:         <td bgcolor="#777777">
1.379     albertel 4906: 	  $default_form_data
1.187     albertel 4907:           <input type="hidden" name="command" value="scantron_download" />
                   4908:           <table width="100%" border="0">
                   4909:             <tr bgcolor="#e6ffff">
                   4910:               <td colspan="2">
                   4911:                 &nbsp;<b>Download a scoring office file</b>
                   4912:               </td>
                   4913:             </tr>
                   4914:             <tr bgcolor="#ffffe6">
                   4915:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4916:             </tr>
                   4917:             <tr bgcolor="#ffffe6">
                   4918:               <td colspan="2">
1.293     www      4919:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4920:               </td>
                   4921:             </tr>
                   4922:           </table>
1.226     albertel 4923:         </td>
                   4924:       </form>
1.187     albertel 4925:     </tr>
                   4926: SCANTRONFORM
1.162     albertel 4927: 
1.457     banghart 4928:     $r->print('<tr><td bgcolor="#777777">');
                   4929:     &Apache::lonpickcode::code_list($r,2);
                   4930:     $r->print('</td></tr></table>');
                   4931:     $r->print($grading_menu_button);
1.162     albertel 4932:     return
1.75      albertel 4933: }
                   4934: 
1.423     albertel 4935: =pod
                   4936: 
                   4937: =item get_scantron_config
                   4938: 
                   4939:    Parse and return the scantron configuration line selected as a
                   4940:    hash of configuration file fields.
                   4941: 
                   4942:  Arguments:
                   4943:     which - the name of the configuration to parse from the file.
                   4944: 
                   4945: 
                   4946:  Returns:
                   4947:             If the named configuration is not in the file, an empty
                   4948:             hash is returned.
                   4949:     a hash with the fields
                   4950:       name         - internal name for the this configuration setup
                   4951:       description  - text to display to operator that describes this config
                   4952:       CODElocation - if 0 or the string 'none'
                   4953:                           - no CODE exists for this config
                   4954:                      if -1 || the string 'letter'
                   4955:                           - a CODE exists for this config and is
                   4956:                             a string of letters
                   4957:                      Unsupported value (but planned for future support)
                   4958:                           if a positive integer
                   4959:                                - The CODE exists as the first n items from
                   4960:                                  the question section of the form
                   4961:                           if the string 'number'
                   4962:                                - The CODE exists for this config and is
                   4963:                                  a string of numbers
                   4964:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4965:                      the CODE starts
                   4966:       CODElength  - length of the CODE
                   4967:       IDstart     - column where the student ID number starts
                   4968:       IDlength    - length of the student ID info
                   4969:       Qstart      - column where the information from the bubbled
                   4970:                     'questions' start
                   4971:       Qlength     - number of columns comprising a single bubble line from
                   4972:                     the sheet. (usually either 1 or 10)
1.424     albertel 4973:       Qon         - either a single character representing the character used
1.423     albertel 4974:                     to signal a bubble was chosen in the positional setup, or
                   4975:                     the string 'letter' if the letter of the chosen bubble is
                   4976:                     in the final, or 'number' if a number representing the
                   4977:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4978:       Qoff        - the character used to represent that a bubble was
                   4979:                     left blank
1.423     albertel 4980:       PaperID     - if the scanning process generates a unique number for each
                   4981:                     sheet scanned the column that this ID number starts in
                   4982:       PaperIDlength - number of columns that comprise the unique ID number
                   4983:                       for the sheet of paper
1.424     albertel 4984:       FirstName   - column that the first name starts in
1.423     albertel 4985:       FirstNameLength - number of columns that the first name spans
                   4986:  
                   4987:       LastName    - column that the last name starts in
                   4988:       LastNameLength - number of columns that the last name spans
                   4989: 
                   4990: =cut
1.422     foxr     4991: 
1.82      albertel 4992: sub get_scantron_config {
                   4993:     my ($which) = @_;
                   4994:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4995:     my %config;
1.157     albertel 4996:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4997:     foreach my $line (<$fh>) {
                   4998: 	my ($name,$descrip)=split(/:/,$line);
                   4999: 	if ($name ne $which ) { next; }
                   5000: 	chomp($line);
                   5001: 	my @config=split(/:/,$line);
                   5002: 	$config{'name'}=$config[0];
                   5003: 	$config{'description'}=$config[1];
                   5004: 	$config{'CODElocation'}=$config[2];
                   5005: 	$config{'CODEstart'}=$config[3];
                   5006: 	$config{'CODElength'}=$config[4];
                   5007: 	$config{'IDstart'}=$config[5];
                   5008: 	$config{'IDlength'}=$config[6];
                   5009: 	$config{'Qstart'}=$config[7];
                   5010: 	$config{'Qlength'}=$config[8];
                   5011: 	$config{'Qoff'}=$config[9];
                   5012: 	$config{'Qon'}=$config[10];
1.157     albertel 5013: 	$config{'PaperID'}=$config[11];
                   5014: 	$config{'PaperIDlength'}=$config[12];
                   5015: 	$config{'FirstName'}=$config[13];
                   5016: 	$config{'FirstNamelength'}=$config[14];
                   5017: 	$config{'LastName'}=$config[15];
                   5018: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5019: 	last;
                   5020:     }
                   5021:     return %config;
                   5022: }
                   5023: 
1.423     albertel 5024: =pod 
                   5025: 
                   5026: =item username_to_idmap
                   5027: 
                   5028:     creates a hash keyed by student id with values of the corresponding
                   5029:     student username:domain.
                   5030: 
                   5031:   Arguments:
                   5032: 
                   5033:     $classlist - reference to the class list hash. This is a hash
                   5034:                  keyed by student name:domain  whose elements are references
1.424     albertel 5035:                  to arrays containing various chunks of information
1.423     albertel 5036:                  about the student. (See loncoursedata for more info).
                   5037: 
                   5038:   Returns
                   5039:     %idmap - the constructed hash
                   5040: 
                   5041: =cut
                   5042: 
1.82      albertel 5043: sub username_to_idmap {
                   5044:     my ($classlist)= @_;
                   5045:     my %idmap;
                   5046:     foreach my $student (keys(%$classlist)) {
                   5047: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5048: 	    $student;
                   5049:     }
                   5050:     return %idmap;
                   5051: }
1.423     albertel 5052: 
                   5053: =pod
                   5054: 
1.424     albertel 5055: =item scantron_fixup_scanline
1.423     albertel 5056: 
                   5057:    Process a requested correction to a scanline.
                   5058: 
                   5059:   Arguments:
                   5060:     $scantron_config   - hash from &get_scantron_config()
                   5061:     $scan_data         - hash of correction information 
                   5062:                           (see &scantron_getfile())
                   5063:     $line              - existing scanline
                   5064:     $whichline         - line number of the passed in scanline
                   5065:     $field             - type of change to process 
                   5066:                          (either 
                   5067:                           'ID'     -> correct the student ID number
                   5068:                           'CODE'   -> correct the CODE
                   5069:                           'answer' -> fixup the submitted answers)
                   5070:     
                   5071:    $args               - hash of additional info,
                   5072:                           - 'ID' 
                   5073:                                'newid' -> studentID to use in replacement
1.424     albertel 5074:                                           of existing one
1.423     albertel 5075:                           - 'CODE' 
                   5076:                                'CODE_ignore_dup' - set to true if duplicates
                   5077:                                                    should be ignored.
                   5078: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5079:                                         if the existing unfound code should
1.423     albertel 5080:                                         be used as is
                   5081:                           - 'answer'
                   5082:                                'response' - new answer or 'none' if blank
                   5083:                                'question' - the bubble line to change
                   5084: 
                   5085:   Returns:
                   5086:     $line - the modified scanline
                   5087: 
                   5088:   Side effects: 
                   5089:     $scan_data - may be updated
                   5090: 
                   5091: =cut
                   5092: 
1.82      albertel 5093: 
1.157     albertel 5094: sub scantron_fixup_scanline {
                   5095:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5096: 
1.157     albertel 5097:     if ($field eq 'ID') {
                   5098: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5099: 	    return ($line,1,'New value too large');
1.157     albertel 5100: 	}
                   5101: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5102: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5103: 				     $args->{'newid'});
                   5104: 	}
                   5105: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5106: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5107: 	if ($args->{'newid'}=~/^\s*$/) {
                   5108: 	    &scan_data($scan_data,"$whichline.user",
                   5109: 		       $args->{'username'}.':'.$args->{'domain'});
                   5110: 	}
1.186     albertel 5111:     } elsif ($field eq 'CODE') {
1.192     albertel 5112: 	if ($args->{'CODE_ignore_dup'}) {
                   5113: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5114: 	}
                   5115: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5116: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5117: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5118: 		return ($line,1,'New CODE value too large');
                   5119: 	    }
                   5120: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5121: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5122: 	    }
                   5123: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5124: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5125: 	}
1.157     albertel 5126:     } elsif ($field eq 'answer') {
                   5127: 	my $length=$scantron_config->{'Qlength'};
                   5128: 	my $off=$scantron_config->{'Qoff'};
                   5129: 	my $on=$scantron_config->{'Qon'};
                   5130: 	my $answer=${off}x$length;
                   5131: 	if ($args->{'response'} eq 'none') {
                   5132: 	    &scan_data($scan_data,
                   5133: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5134: 	} else {
1.274     albertel 5135: 	    if ($on eq 'letter') {
                   5136: 		my @alphabet=('A'..'Z');
                   5137: 		$answer=$alphabet[$args->{'response'}];
                   5138: 	    } elsif ($on eq 'number') {
                   5139: 		$answer=$args->{'response'}+1;
1.389     albertel 5140: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5141: 	    } else {
                   5142: 		substr($answer,$args->{'response'},1)=$on;
                   5143: 	    }
1.157     albertel 5144: 	    &scan_data($scan_data,
                   5145: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5146: 	}
                   5147: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5148: 	substr($line,$where-1,$length)=$answer;
                   5149:     }
                   5150:     return $line;
                   5151: }
1.423     albertel 5152: 
                   5153: =pod
                   5154: 
                   5155: =item scan_data
                   5156: 
                   5157:     Edit or look up  an item in the scan_data hash.
                   5158: 
                   5159:   Arguments:
                   5160:     $scan_data  - The hash (see scantron_getfile)
                   5161:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5162:                   scantronfilename_key).
1.423     albertel 5163:     $data        - New value of the hash entry.
                   5164:     $delete      - If true, the entry is removed from the hash.
                   5165: 
                   5166:   Returns:
                   5167:     The new value of the hash table field (undefined if deleted).
                   5168: 
                   5169: =cut
                   5170: 
                   5171: 
1.157     albertel 5172: sub scan_data {
                   5173:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5174:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5175:     if (defined($value)) {
                   5176: 	$scan_data->{$filename.'_'.$key} = $value;
                   5177:     }
                   5178:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5179:     return $scan_data->{$filename.'_'.$key};
                   5180: }
1.423     albertel 5181: 
                   5182: =pod 
                   5183: 
                   5184: =item scantron_parse_scanline
                   5185: 
                   5186:   Decodes a scanline from the selected scantron file
                   5187: 
                   5188:  Arguments:
                   5189:     line             - The text of the scantron file line to process
                   5190:     whichline        - Line number
                   5191:     scantron_config  - Hash describing the format of the scantron lines.
                   5192:     scan_data        - Hash of extra information about the scanline
                   5193:                        (see scantron_getfile for more information)
                   5194:     just_header      - True if should not process question answers but only
                   5195:                        the stuff to the left of the answers.
                   5196:  Returns:
                   5197:    Hash containing the result of parsing the scanline
                   5198: 
                   5199:    Keys are all proceeded by the string 'scantron.'
                   5200: 
                   5201:        CODE    - the CODE in use for this scanline
                   5202:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5203:                  by the operator
                   5204:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5205:                             CODEs were selected, but the usage has been
                   5206:                             forced by the operator
                   5207:        ID  - student ID
                   5208:        PaperID - if used, the ID number printed on the sheet when the 
                   5209:                  paper was scanned
                   5210:        FirstName - first name from the sheet
                   5211:        LastName  - last name from the sheet
                   5212: 
                   5213:      if just_header was not true these key may also exist
                   5214: 
1.447     foxr     5215:        missingerror - a list of bubble ranges that are considered to be answers
                   5216:                       to a single question that don't have any bubbles filled in.
                   5217:                       Of the form questionnumber:firstbubblenumber:count.
                   5218:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5219:                       to a single question that have more than one bubble filled in.
                   5220:                       Of the form questionnumber::firstbubblenumber:count
                   5221:    
                   5222:                 In the above, count is the number of bubble responses in the
                   5223:                 input line needed to represent the possible answers to the question.
                   5224:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5225:                 per line would have count = 2.
                   5226: 
1.423     albertel 5227:        maxquest     - the number of the last bubble line that was parsed
                   5228: 
                   5229:        (<number> starts at 1)
                   5230:        <number>.answer - zero or more letters representing the selected
                   5231:                          letters from the scanline for the bubble line 
                   5232:                          <number>.
                   5233:                          if blank there was either no bubble or there where
                   5234:                          multiple bubbles, (consult the keys missingerror and
                   5235:                          doubleerror if this is an error condition)
                   5236: 
                   5237: =cut
                   5238: 
1.82      albertel 5239: sub scantron_parse_scanline {
1.423     albertel 5240:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5241:     my %record;
1.422     foxr     5242:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5243:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5244:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5245: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5246: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5247: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5248: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5249: 	    $record{'scantron.CODE'}=substr($data,
                   5250: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5251: 					    $$scantron_config{'CODElength'});
1.191     albertel 5252: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5253: 		$record{'scantron.useCODE'}=1;
                   5254: 	    }
1.192     albertel 5255: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5256: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5257: 	    }
1.82      albertel 5258: 	} else {
                   5259: 	    #FIXME interpret first N questions
                   5260: 	}
                   5261:     }
1.83      albertel 5262:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5263: 				  $$scantron_config{'IDlength'});
1.157     albertel 5264:     $record{'scantron.PaperID'}=
                   5265: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5266: 	       $$scantron_config{'PaperIDlength'});
                   5267:     $record{'scantron.FirstName'}=
                   5268: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5269: 	       $$scantron_config{'FirstNamelength'});
                   5270:     $record{'scantron.LastName'}=
                   5271: 	substr($data,$$scantron_config{'LastName'}-1,
                   5272: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5273:     if ($just_header) { return \%record; }
1.194     albertel 5274: 
1.82      albertel 5275:     my @alphabet=('A'..'Z');
                   5276:     my $questnum=0;
1.447     foxr     5277:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5278: 
1.82      albertel 5279:     while ($questions) {
1.447     foxr     5280: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5281: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5282: 
                   5283: 
                   5284: 
1.82      albertel 5285: 	$questnum++;
1.447     foxr     5286: 	my $currentquest = substr($questions,0,$answer_length);
                   5287: 	$questions       = substr($questions,0,$answer_length)='';
                   5288: 	if (length($currentquest) < $answer_length) { next; }
                   5289: 
                   5290: 	# Qon letter implies for each slot in currentquest we have:
                   5291: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5292:         #    about anything else (esp. a value of Qoff for missing
                   5293: 	#    bubbles.
                   5294: 
                   5295: 
1.239     albertel 5296: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5297: 
                   5298: 	    if ($currentquest =~ /\?/
                   5299: 		|| $currentquest =~ /\*/
                   5300: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5301: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5302: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5303: 		    my $bubble = substr($currentquest, $ans, 1);
                   5304: 		    if ($bubble =~ /[A-Z]/ ) {
                   5305: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5306: 		    } else {
                   5307: 			$record{"scantron.$ansnum.answer"}='';
                   5308: 		    }
1.447     foxr     5309: 		    $ansnum++;
                   5310: 		}
                   5311: 
1.389     albertel 5312: 	    } elsif (!defined($currentquest)
1.447     foxr     5313: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5314: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5315: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5316: 		    $record{"scantron.$ansnum.answer"}='';
                   5317: 		    $ansnum++;
                   5318: 
                   5319: 		}
1.239     albertel 5320: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5321: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5322: 		    $ansnum += $answers_needed;
1.239     albertel 5323: 		}
1.447     foxr     5324: 
1.239     albertel 5325: 	    } else {
1.447     foxr     5326: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5327: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5328: 		    $ansnum++;
                   5329: 		}
1.239     albertel 5330: 	    }
1.447     foxr     5331: 
                   5332: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5333: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5334:         #    and *? for double bubbles on a line.
                   5335: 	#    these answers are also stored as letters.
                   5336: 
1.239     albertel 5337: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5338: 	    if ($currentquest =~ /\?/
                   5339: 		|| $currentquest =~ /\*/
                   5340: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5341: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5342: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5343: 		    my $bubble = substr($currentquest, $ans, 1);
                   5344: 		    if ($bubble =~ /\d/) {
                   5345: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5346: 		    } else {
1.461     foxr     5347: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5348: 		    }
1.447     foxr     5349: 		    $ansnum++;
                   5350: 		}
                   5351: 
1.389     albertel 5352: 	    } elsif (!defined($currentquest)
1.447     foxr     5353: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5354: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5355: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5356: 		    $record{"scantron.$ansnum.answer"}='';
                   5357: 		    $ansnum++;
                   5358: 
                   5359: 		}
1.239     albertel 5360: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5361: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5362: 		    $ansnum += $answers_needed;
1.239     albertel 5363: 		}
1.447     foxr     5364: 
1.239     albertel 5365: 	    } else {
1.447     foxr     5366: 		$currentquest = &digits_to_letters($currentquest);
                   5367: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5368: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5369: 		    $ansnum++;
1.371     albertel 5370: 		}
1.239     albertel 5371: 	    }
1.82      albertel 5372: 	} else {
1.447     foxr     5373: 
                   5374: 	    # Otherwise there's a positional notation;
                   5375: 	    # each bubble line requires Qlength items, and there are filled in
                   5376: 	    # bubbles for each case where there 'Qon' characters.
                   5377: 	    #
                   5378: 
1.239     albertel 5379: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5380: 
                   5381: 	    # If the split only  giveas us one element.. the full length of the
                   5382: 	    # answser string, no bubbles are filled in:
                   5383: 
                   5384: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5385: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5386: 		    $record{"scantron.$ansnum.answer"}='';
                   5387: 		    $ansnum++;
                   5388: 
                   5389: 		}
1.239     albertel 5390: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5391: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5392: 		}
1.447     foxr     5393: 	    } elsif (scalar(@array) lt 2) {
                   5394: 
1.459     foxr     5395: 		my $location      = length($array[0]);
1.447     foxr     5396: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5397: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5398: 
                   5399: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5400: 		    if ($ans eq $line_num) {
                   5401: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5402: 		    } else {
                   5403: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5404: 		    }
                   5405: 		    $ansnum++;
                   5406: 		}
1.239     albertel 5407: 	    }
1.447     foxr     5408: 	    #  If there's more than one instance of a bubble character
                   5409: 	    #  That's a double bubble; with positional notation we can
                   5410: 	    #  record all the bubbles filled in as well as the 
                   5411: 	    #  fact this response consists of multiple bubbles.
                   5412: 	    #
                   5413: 	    else {
1.239     albertel 5414: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5415: 
                   5416: 		my $first_answer = $ansnum;
                   5417: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5418: 		    my $item = $first_answer+$ans;
                   5419: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5420: 		}
                   5421: 
1.239     albertel 5422: 		my @ans=@array;
1.462     foxr     5423: 		my $i=0;
                   5424: 		my $increment = 0;
1.239     albertel 5425: 		while ($#ans) {
1.462     foxr     5426: 		    $i+=length($ans[0]) + $increment;
                   5427: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5428: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5429: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5430: 		    shift(@ans);
1.462     foxr     5431: 		    $increment = 1;
1.239     albertel 5432: 		}
1.462     foxr     5433: 		$ansnum += $answers_needed;
1.239     albertel 5434: 	    }
1.82      albertel 5435: 	}
                   5436:     }
1.83      albertel 5437:     $record{'scantron.maxquest'}=$questnum;
                   5438:     return \%record;
1.82      albertel 5439: }
                   5440: 
1.423     albertel 5441: =pod
                   5442: 
                   5443: =item scantron_add_delay
                   5444: 
                   5445:    Adds an error message that occurred during the grading phase to a
                   5446:    queue of messages to be shown after grading pass is complete
                   5447: 
                   5448:  Arguments:
1.424     albertel 5449:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5450:    $scanline    - the scanline that caused the error
                   5451:    $errormesage - the error message
                   5452:    $errorcode   - a numeric code for the error
                   5453: 
                   5454:  Side Effects:
1.424     albertel 5455:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5456: 
                   5457: =cut
                   5458: 
1.82      albertel 5459: sub scantron_add_delay {
1.140     albertel 5460:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5461:     push(@$delayqueue,
                   5462: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5463: 	  'ecode' => $errorcode }
                   5464: 	 );
1.82      albertel 5465: }
                   5466: 
1.423     albertel 5467: =pod
                   5468: 
                   5469: =item scantron_find_student
                   5470: 
1.424     albertel 5471:    Finds the username for the current scanline
                   5472: 
                   5473:   Arguments:
                   5474:    $scantron_record - hash result from scantron_parse_scanline
                   5475:    $scan_data       - hash of correction information 
                   5476:                       (see &scantron_getfile() form more information)
                   5477:    $idmap           - hash from &username_to_idmap()
                   5478:    $line            - number of current scanline
                   5479:  
                   5480:   Returns:
                   5481:    Either 'username:domain' or undef if unknown
                   5482: 
1.423     albertel 5483: =cut
                   5484: 
1.82      albertel 5485: sub scantron_find_student {
1.157     albertel 5486:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5487:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5488:     if ($scanID =~ /^\s*$/) {
                   5489:  	return &scan_data($scan_data,"$line.user");
                   5490:     }
1.83      albertel 5491:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5492:  	if (lc($id) eq lc($scanID)) {
                   5493:  	    return $$idmap{$id};
                   5494:  	}
1.83      albertel 5495:     }
                   5496:     return undef;
                   5497: }
                   5498: 
1.423     albertel 5499: =pod
                   5500: 
                   5501: =item scantron_filter
                   5502: 
1.424     albertel 5503:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5504:    hidden resources was selected
                   5505: 
1.423     albertel 5506: =cut
                   5507: 
1.83      albertel 5508: sub scantron_filter {
                   5509:     my ($curres)=@_;
1.331     albertel 5510: 
                   5511:     if (ref($curres) && $curres->is_problem()) {
                   5512: 	# if the user has asked to not have either hidden
                   5513: 	# or 'randomout' controlled resources to be graded
                   5514: 	# don't include them
                   5515: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5516: 	    && $curres->randomout) {
                   5517: 	    return 0;
                   5518: 	}
1.83      albertel 5519: 	return 1;
                   5520:     }
                   5521:     return 0;
1.82      albertel 5522: }
                   5523: 
1.423     albertel 5524: =pod
                   5525: 
                   5526: =item scantron_process_corrections
                   5527: 
1.424     albertel 5528:    Gets correction information out of submitted form data and corrects
                   5529:    the scanline
                   5530: 
1.423     albertel 5531: =cut
                   5532: 
1.157     albertel 5533: sub scantron_process_corrections {
                   5534:     my ($r) = @_;
1.257     albertel 5535:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5536:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5537:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5538:     my $which=$env{'form.scantron_line'};
1.200     albertel 5539:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5540:     my ($skip,$err,$errmsg);
1.257     albertel 5541:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5542: 	$skip=1;
1.257     albertel 5543:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5544: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5545: 	    $env{'form.scantron_domain'};
1.157     albertel 5546: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5547: 	($line,$err,$errmsg)=
                   5548: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5549: 				     'ID',{'newid'=>$newid,
1.257     albertel 5550: 				    'username'=>$env{'form.scantron_username'},
                   5551: 				    'domain'=>$env{'form.scantron_domain'}});
                   5552:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5553: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5554: 	my $newCODE;
1.192     albertel 5555: 	my %args;
1.190     albertel 5556: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5557: 	    $newCODE='use_unfound';
1.190     albertel 5558: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5559: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5560: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5561: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5562: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5563: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5564: 	}
1.257     albertel 5565: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5566: 	    $args{'CODE_ignore_dup'}=1;
                   5567: 	}
                   5568: 	$args{'CODE'}=$newCODE;
1.186     albertel 5569: 	($line,$err,$errmsg)=
                   5570: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5571: 				     'CODE',\%args);
1.257     albertel 5572:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5573: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5574: 	    ($line,$err,$errmsg)=
                   5575: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5576: 					 $which,'answer',
                   5577: 					 { 'question'=>$question,
1.257     albertel 5578: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5579: 	    if ($err) { last; }
                   5580: 	}
                   5581:     }
                   5582:     if ($err) {
1.398     albertel 5583: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5584:     } else {
1.200     albertel 5585: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5586: 	&scantron_putfile($scanlines,$scan_data);
                   5587:     }
                   5588: }
                   5589: 
1.423     albertel 5590: =pod
                   5591: 
                   5592: =item reset_skipping_status
                   5593: 
1.424     albertel 5594:    Forgets the current set of remember skipped scanlines (and thus
                   5595:    reverts back to considering all lines in the
                   5596:    scantron_skipped_<filename> file)
                   5597: 
1.423     albertel 5598: =cut
                   5599: 
1.200     albertel 5600: sub reset_skipping_status {
                   5601:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5602:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5603:     &scantron_putfile(undef,$scan_data);
                   5604: }
                   5605: 
1.423     albertel 5606: =pod
                   5607: 
                   5608: =item start_skipping
                   5609: 
1.424     albertel 5610:    Marks a scanline to be skipped. 
                   5611: 
1.423     albertel 5612: =cut
                   5613: 
1.376     albertel 5614: sub start_skipping {
1.200     albertel 5615:     my ($scan_data,$i)=@_;
                   5616:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5617:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5618: 	$remembered{$i}=2;
                   5619:     } else {
                   5620: 	$remembered{$i}=1;
                   5621:     }
1.200     albertel 5622:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5623: }
                   5624: 
1.423     albertel 5625: =pod
                   5626: 
                   5627: =item should_be_skipped
                   5628: 
1.424     albertel 5629:    Checks whether a scanline should be skipped.
                   5630: 
1.423     albertel 5631: =cut
                   5632: 
1.200     albertel 5633: sub should_be_skipped {
1.376     albertel 5634:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5635:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5636: 	# not redoing old skips
1.376     albertel 5637: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5638: 	return 0;
                   5639:     }
                   5640:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5641: 
                   5642:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5643: 	return 0;
                   5644:     }
1.200     albertel 5645:     return 1;
                   5646: }
                   5647: 
1.423     albertel 5648: =pod
                   5649: 
                   5650: =item remember_current_skipped
                   5651: 
1.424     albertel 5652:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5653:    file and remembers them into scan_data for later use.
                   5654: 
1.423     albertel 5655: =cut
                   5656: 
1.200     albertel 5657: sub remember_current_skipped {
                   5658:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5659:     my %to_remember;
                   5660:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5661: 	if ($scanlines->{'skipped'}[$i]) {
                   5662: 	    $to_remember{$i}=1;
                   5663: 	}
                   5664:     }
1.376     albertel 5665: 
1.200     albertel 5666:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5667:     &scantron_putfile(undef,$scan_data);
                   5668: }
                   5669: 
1.423     albertel 5670: =pod
                   5671: 
                   5672: =item check_for_error
                   5673: 
1.424     albertel 5674:     Checks if there was an error when attempting to remove a specific
                   5675:     scantron_.. bubble sheet data file. Prints out an error if
                   5676:     something went wrong.
                   5677: 
1.423     albertel 5678: =cut
                   5679: 
1.200     albertel 5680: sub check_for_error {
                   5681:     my ($r,$result)=@_;
                   5682:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5683: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5684:     }
                   5685: }
1.157     albertel 5686: 
1.423     albertel 5687: =pod
                   5688: 
                   5689: =item scantron_warning_screen
                   5690: 
1.424     albertel 5691:    Interstitial screen to make sure the operator has selected the
                   5692:    correct options before we start the validation phase.
                   5693: 
1.423     albertel 5694: =cut
                   5695: 
1.203     albertel 5696: sub scantron_warning_screen {
                   5697:     my ($button_text)=@_;
1.257     albertel 5698:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5699:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5700:     my $CODElist;
1.284     albertel 5701:     if ($scantron_config{'CODElocation'} &&
                   5702: 	$scantron_config{'CODEstart'} &&
                   5703: 	$scantron_config{'CODElength'}) {
                   5704: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5705: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5706: 	$CODElist=
                   5707: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5708: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5709:     }
1.203     albertel 5710:     return (<<STUFF);
                   5711: <p>
1.398     albertel 5712: <span class="LC_warning">Please double check the information
                   5713:                  below before clicking on '$button_text'</span>
1.203     albertel 5714: </p>
                   5715: <table>
1.284     albertel 5716: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5717: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5718: $CODElist
1.203     albertel 5719: </table>
                   5720: <br />
                   5721: <p> If this information is correct, please click on '$button_text'.</p>
                   5722: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5723: 
                   5724: <br />
                   5725: STUFF
                   5726: }
                   5727: 
1.423     albertel 5728: =pod
                   5729: 
                   5730: =item scantron_do_warning
                   5731: 
1.424     albertel 5732:    Check if the operator has picked something for all required
                   5733:    fields. Error out if something is missing.
                   5734: 
1.423     albertel 5735: =cut
                   5736: 
1.203     albertel 5737: sub scantron_do_warning {
                   5738:     my ($r)=@_;
1.324     albertel 5739:     my ($symb)=&get_symb($r);
1.203     albertel 5740:     if (!$symb) {return '';}
1.324     albertel 5741:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5742:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5743:     if ( $env{'form.selectpage'} eq '' ||
                   5744: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5745: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5746: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5747: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5748: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5749: 	} 
1.257     albertel 5750: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5751: 	    $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 5752: 	} 
1.257     albertel 5753: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5754: 	    $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 5755: 	} 
                   5756:     } else {
1.265     www      5757: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5758: 	$r->print(<<STUFF);
1.203     albertel 5759: $warning
1.265     www      5760: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5761: <input type="hidden" name="command" value="scantron_validate" />
                   5762: STUFF
1.237     albertel 5763:     }
1.352     albertel 5764:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5765:     return '';
                   5766: }
                   5767: 
1.423     albertel 5768: =pod
                   5769: 
                   5770: =item scantron_form_start
                   5771: 
1.424     albertel 5772:     html hidden input for remembering all selected grading options
                   5773: 
1.423     albertel 5774: =cut
                   5775: 
1.203     albertel 5776: sub scantron_form_start {
                   5777:     my ($max_bubble)=@_;
                   5778:     my $result= <<SCANTRONFORM;
                   5779: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5780:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5781:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5782:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5783:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5784:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5785:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5786:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5787:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5788:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5789: SCANTRONFORM
1.447     foxr     5790: 
                   5791:   my $line = 0;
                   5792:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5793:        my $chunk =
                   5794: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5795:        $chunk .=
                   5796: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5797:        $result .= $chunk;
                   5798:        $line++;
                   5799:    }
1.203     albertel 5800:     return $result;
                   5801: }
                   5802: 
1.423     albertel 5803: =pod
                   5804: 
                   5805: =item scantron_validate_file
                   5806: 
1.424     albertel 5807:     Dispatch routine for doing validation of a bubble sheet data file.
                   5808: 
                   5809:     Also processes any necessary information resets that need to
                   5810:     occur before validation begins (ignore previous corrections,
                   5811:     restarting the skipped records processing)
                   5812: 
1.423     albertel 5813: =cut
                   5814: 
1.157     albertel 5815: sub scantron_validate_file {
                   5816:     my ($r) = @_;
1.324     albertel 5817:     my ($symb)=&get_symb($r);
1.157     albertel 5818:     if (!$symb) {return '';}
1.324     albertel 5819:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5820:     
                   5821:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5822:     # them when doing the corrections reset
1.257     albertel 5823:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5824: 	&reset_skipping_status();
                   5825:     }
1.257     albertel 5826:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5827: 	&remember_current_skipped();
1.257     albertel 5828: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5829:     }
                   5830: 
1.257     albertel 5831:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5832: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5833: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5834: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5835: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5836:     }
1.200     albertel 5837: 
1.257     albertel 5838:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5839: 	&scantron_process_corrections($r);
                   5840:     }
1.424     albertel 5841:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5842:     #get the student pick code ready
                   5843:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5844:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5845:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5846:     $r->print($result);
                   5847:     
1.334     albertel 5848:     my @validate_phases=( 'sequence',
                   5849: 			  'ID',
1.157     albertel 5850: 			  'CODE',
                   5851: 			  'doublebubble',
                   5852: 			  'missingbubbles');
1.257     albertel 5853:     if (!$env{'form.validatepass'}) {
                   5854: 	$env{'form.validatepass'} = 0;
1.157     albertel 5855:     }
1.257     albertel 5856:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5857: 
1.448     foxr     5858: 
1.157     albertel 5859:     my $stop=0;
                   5860:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5861: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5862: 	$r->rflush();
                   5863: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5864: 	{
                   5865: 	    no strict 'refs';
                   5866: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5867: 	}
                   5868:     }
                   5869:     if (!$stop) {
1.203     albertel 5870: 	my $warning=&scantron_warning_screen('Start Grading');
                   5871: 	$r->print(<<STUFF);
                   5872: Validation process complete.<br />
                   5873: $warning
                   5874: <input type="submit" name="submit" value="Start Grading" />
                   5875: <input type="hidden" name="command" value="scantron_process" />
                   5876: STUFF
                   5877: 
1.157     albertel 5878:     } else {
                   5879: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5880: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5881:     }
                   5882:     if ($stop) {
1.334     albertel 5883: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5884: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5885: 	    $r->print(' this error <br />');
                   5886: 
                   5887: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5888: 	} else {
                   5889: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5890: 	    $r->print(' using corrected info <br />');
                   5891: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5892: 	    $r->print(" this scanline saving it for later.");
                   5893: 	}
1.157     albertel 5894:     }
1.352     albertel 5895:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5896:     return '';
                   5897: }
                   5898: 
1.423     albertel 5899: 
                   5900: =pod
                   5901: 
                   5902: =item scantron_remove_file
                   5903: 
1.424     albertel 5904:    Removes the requested bubble sheet data file, makes sure that
                   5905:    scantron_original_<filename> is never removed
                   5906: 
                   5907: 
1.423     albertel 5908: =cut
                   5909: 
1.200     albertel 5910: sub scantron_remove_file {
1.192     albertel 5911:     my ($which)=@_;
1.257     albertel 5912:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5913:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5914:     my $file='scantron_';
1.200     albertel 5915:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5916: 	$file.=$which.'_';
1.192     albertel 5917:     } else {
                   5918: 	return 'refused';
                   5919:     }
1.257     albertel 5920:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5921:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5922: }
                   5923: 
1.423     albertel 5924: 
                   5925: =pod
                   5926: 
                   5927: =item scantron_remove_scan_data
                   5928: 
1.424     albertel 5929:    Removes all scan_data correction for the requested bubble sheet
                   5930:    data file.  (In the case that both the are doing skipped records we need
                   5931:    to remember the old skipped lines for the time being so that element
                   5932:    persists for a while.)
                   5933: 
1.423     albertel 5934: =cut
                   5935: 
1.200     albertel 5936: sub scantron_remove_scan_data {
1.257     albertel 5937:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5938:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5939:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5940:     my @todelete;
1.257     albertel 5941:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5942:     foreach my $key (@keys) {
                   5943: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5944: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5945: 		$key=~/remember_skipping/) {
                   5946: 		next;
                   5947: 	    }
1.192     albertel 5948: 	    push(@todelete,$key);
                   5949: 	}
                   5950:     }
1.200     albertel 5951:     my $result;
1.192     albertel 5952:     if (@todelete) {
1.200     albertel 5953: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5954:     }
                   5955:     return $result;
                   5956: }
                   5957: 
1.423     albertel 5958: 
                   5959: =pod
                   5960: 
                   5961: =item scantron_getfile
                   5962: 
1.424     albertel 5963:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5964:     the scan_data hash
                   5965:   
                   5966:   Arguments:
                   5967:     None
                   5968: 
                   5969:   Returns:
                   5970:     2 hash references
                   5971: 
                   5972:      - first one has 
                   5973:          orig      -
                   5974:          corrected -
                   5975:          skipped   -  each of which points to an array ref of the specified
                   5976:                       file broken up into individual lines
                   5977:          count     - number of scanlines
                   5978:  
                   5979:      - second is the scan_data hash possible keys are
1.425     albertel 5980:        ($number refers to scanline numbered $number and thus the key affects
                   5981:         only that scanline
                   5982:         $bubline refers to the specific bubble line element and the aspects
                   5983:         refers to that specific bubble line element)
                   5984: 
                   5985:        $number.user - username:domain to use
                   5986:        $number.CODE_ignore_dup 
                   5987:                     - ignore the duplicate CODE error 
                   5988:        $number.useCODE
                   5989:                     - use the CODE in the scanline as is
                   5990:        $number.no_bubble.$bubline
                   5991:                     - it is valid that there is no bubbled in bubble
                   5992:                       at $number $bubline
                   5993:        remember_skipping
                   5994:                     - a frozen hash containing keys of $number and values
                   5995:                       of either 
                   5996:                         1 - we are on a 'do skipped records pass' and plan
                   5997:                             on processing this line
                   5998:                         2 - we are on a 'do skipped records pass' and this
                   5999:                             scanline has been marked to skip yet again
1.424     albertel 6000: 
1.423     albertel 6001: =cut
                   6002: 
1.157     albertel 6003: sub scantron_getfile {
1.200     albertel 6004:     #FIXME really would prefer a scantron directory
1.257     albertel 6005:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6006:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6007:     my $lines;
                   6008:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6009: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6010:     my %scanlines;
                   6011:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6012:     my $temp=$scanlines{'orig'};
                   6013:     $scanlines{'count'}=$#$temp;
                   6014: 
                   6015:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6016: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6017:     if ($lines eq '-1') {
                   6018: 	$scanlines{'corrected'}=[];
                   6019:     } else {
                   6020: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6021:     }
                   6022:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6023: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6024:     if ($lines eq '-1') {
                   6025: 	$scanlines{'skipped'}=[];
                   6026:     } else {
                   6027: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6028:     }
1.175     albertel 6029:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6030:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6031:     my %scan_data = @tmp;
                   6032:     return (\%scanlines,\%scan_data);
                   6033: }
                   6034: 
1.423     albertel 6035: =pod
                   6036: 
                   6037: =item lonnet_putfile
                   6038: 
1.424     albertel 6039:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6040: 
                   6041:  Arguments:
                   6042:    $contents - data to store
                   6043:    $filename - filename to store $contents into
                   6044: 
                   6045:  Returns:
                   6046:    result value from &Apache::lonnet::finishuserfileupload
                   6047: 
1.423     albertel 6048: =cut
                   6049: 
1.157     albertel 6050: sub lonnet_putfile {
                   6051:     my ($contents,$filename)=@_;
1.257     albertel 6052:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6053:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6054:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6055:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6056: 
                   6057: }
                   6058: 
1.423     albertel 6059: =pod
                   6060: 
                   6061: =item scantron_putfile
                   6062: 
1.424     albertel 6063:     Stores the current version of the bubble sheet data files, and the
                   6064:     scan_data hash. (Does not modify the original version only the
                   6065:     corrected and skipped versions.
                   6066: 
                   6067:  Arguments:
                   6068:     $scanlines - hash ref that looks like the first return value from
                   6069:                  &scantron_getfile()
                   6070:     $scan_data - hash ref that looks like the second return value from
                   6071:                  &scantron_getfile()
                   6072: 
1.423     albertel 6073: =cut
                   6074: 
1.157     albertel 6075: sub scantron_putfile {
                   6076:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6077:     #FIXME really would prefer a scantron directory
1.257     albertel 6078:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6080:     if ($scanlines) {
                   6081: 	my $prefix='scantron_';
1.157     albertel 6082: # no need to update orig, shouldn't change
                   6083: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6084: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6085: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6086: 			$prefix.'corrected_'.
1.257     albertel 6087: 			$env{'form.scantron_selectfile'});
1.200     albertel 6088: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6089: 			$prefix.'skipped_'.
1.257     albertel 6090: 			$env{'form.scantron_selectfile'});
1.200     albertel 6091:     }
1.175     albertel 6092:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6093: }
                   6094: 
1.423     albertel 6095: =pod
                   6096: 
                   6097: =item scantron_get_line
                   6098: 
1.424     albertel 6099:    Returns the correct version of the scanline
                   6100: 
                   6101:  Arguments:
                   6102:     $scanlines - hash ref that looks like the first return value from
                   6103:                  &scantron_getfile()
                   6104:     $scan_data - hash ref that looks like the second return value from
                   6105:                  &scantron_getfile()
                   6106:     $i         - number of the requested line (starts at 0)
                   6107: 
                   6108:  Returns:
                   6109:    A scanline, (either the original or the corrected one if it
                   6110:    exists), or undef if the requested scanline should be
                   6111:    skipped. (Either because it's an skipped scanline, or it's an
                   6112:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6113:    pass.
                   6114: 
1.423     albertel 6115: =cut
                   6116: 
1.157     albertel 6117: sub scantron_get_line {
1.200     albertel 6118:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6119:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6120:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6121:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6122:     return $scanlines->{'orig'}[$i]; 
                   6123: }
                   6124: 
1.423     albertel 6125: =pod
                   6126: 
                   6127: =item scantron_todo_count
                   6128: 
1.424     albertel 6129:     Counts the number of scanlines that need processing.
                   6130: 
                   6131:  Arguments:
                   6132:     $scanlines - hash ref that looks like the first return value from
                   6133:                  &scantron_getfile()
                   6134:     $scan_data - hash ref that looks like the second return value from
                   6135:                  &scantron_getfile()
                   6136: 
                   6137:  Returns:
                   6138:     $count - number of scanlines to process
                   6139: 
1.423     albertel 6140: =cut
                   6141: 
1.200     albertel 6142: sub get_todo_count {
                   6143:     my ($scanlines,$scan_data)=@_;
                   6144:     my $count=0;
                   6145:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6146: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6147: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6148: 	$count++;
                   6149:     }
                   6150:     return $count;
                   6151: }
                   6152: 
1.423     albertel 6153: =pod
                   6154: 
                   6155: =item scantron_put_line
                   6156: 
1.424     albertel 6157:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6158:     data file.
                   6159: 
                   6160:  Arguments:
                   6161:     $scanlines - hash ref that looks like the first return value from
                   6162:                  &scantron_getfile()
                   6163:     $scan_data - hash ref that looks like the second return value from
                   6164:                  &scantron_getfile()
                   6165:     $i         - line number to update
                   6166:     $newline   - contents of the updated scanline
                   6167:     $skip      - if true make the line for skipping and update the
                   6168:                  'skipped' file
                   6169: 
1.423     albertel 6170: =cut
                   6171: 
1.157     albertel 6172: sub scantron_put_line {
1.200     albertel 6173:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6174:     if ($skip) {
                   6175: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6176: 	&start_skipping($scan_data,$i);
1.157     albertel 6177: 	return;
                   6178:     }
                   6179:     $scanlines->{'corrected'}[$i]=$newline;
                   6180: }
                   6181: 
1.423     albertel 6182: =pod
                   6183: 
                   6184: =item scantron_clear_skip
                   6185: 
1.424     albertel 6186:    Remove a line from the 'skipped' file
                   6187: 
                   6188:  Arguments:
                   6189:     $scanlines - hash ref that looks like the first return value from
                   6190:                  &scantron_getfile()
                   6191:     $scan_data - hash ref that looks like the second return value from
                   6192:                  &scantron_getfile()
                   6193:     $i         - line number to update
                   6194: 
1.423     albertel 6195: =cut
                   6196: 
1.376     albertel 6197: sub scantron_clear_skip {
                   6198:     my ($scanlines,$scan_data,$i)=@_;
                   6199:     if (exists($scanlines->{'skipped'}[$i])) {
                   6200: 	undef($scanlines->{'skipped'}[$i]);
                   6201: 	return 1;
                   6202:     }
                   6203:     return 0;
                   6204: }
                   6205: 
1.423     albertel 6206: =pod
                   6207: 
                   6208: =item scantron_filter_not_exam
                   6209: 
1.424     albertel 6210:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6211:    filter out resources that are not marked as 'exam' mode
                   6212: 
1.423     albertel 6213: =cut
                   6214: 
1.334     albertel 6215: sub scantron_filter_not_exam {
                   6216:     my ($curres)=@_;
                   6217:     
                   6218:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6219: 	# if the user has asked to not have either hidden
                   6220: 	# or 'randomout' controlled resources to be graded
                   6221: 	# don't include them
                   6222: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6223: 	    && $curres->randomout) {
                   6224: 	    return 0;
                   6225: 	}
                   6226: 	return 1;
                   6227:     }
                   6228:     return 0;
                   6229: }
                   6230: 
1.423     albertel 6231: =pod
                   6232: 
                   6233: =item scantron_validate_sequence
                   6234: 
1.424     albertel 6235:     Validates the selected sequence, checking for resource that are
                   6236:     not set to exam mode.
                   6237: 
1.423     albertel 6238: =cut
                   6239: 
1.334     albertel 6240: sub scantron_validate_sequence {
                   6241:     my ($r,$currentphase) = @_;
                   6242: 
                   6243:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6244:     my (undef,undef,$sequence)=
                   6245: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6246: 
                   6247:     my $map=$navmap->getResourceByUrl($sequence);
                   6248: 
                   6249:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6250:                                     value="ignore" />');
                   6251:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6252: 	my @resources=
                   6253: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6254: 	if (@resources) {
1.357     banghart 6255: 	    $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 6256: 	    return (1,$currentphase);
                   6257: 	}
                   6258:     }
                   6259: 
                   6260:     return (0,$currentphase+1);
                   6261: }
                   6262: 
1.423     albertel 6263: =pod
                   6264: 
                   6265: =item scantron_validate_ID
                   6266: 
1.424     albertel 6267:    Validates all scanlines in the selected file to not have any
                   6268:    invalid or underspecified student IDs
                   6269: 
1.423     albertel 6270: =cut
                   6271: 
1.157     albertel 6272: sub scantron_validate_ID {
                   6273:     my ($r,$currentphase) = @_;
                   6274:     
                   6275:     #get student info
                   6276:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6277:     my %idmap=&username_to_idmap($classlist);
                   6278: 
                   6279:     #get scantron line setup
1.257     albertel 6280:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6281:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6282:     
                   6283:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6284: 
                   6285:     my %found=('ids'=>{},'usernames'=>{});
                   6286:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6287: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6288: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6289: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6290: 						 $scan_data);
                   6291: 	my $id=$$scan_record{'scantron.ID'};
                   6292: 	my $found;
                   6293: 	foreach my $checkid (keys(%idmap)) {
                   6294: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6295: 	}
                   6296: 	if ($found) {
                   6297: 	    my $username=$idmap{$found};
                   6298: 	    if ($found{'ids'}{$found}) {
                   6299: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6300: 					 $line,'duplicateID',$found);
1.194     albertel 6301: 		return(1,$currentphase);
1.157     albertel 6302: 	    } elsif ($found{'usernames'}{$username}) {
                   6303: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6304: 					 $line,'duplicateID',$username);
1.194     albertel 6305: 		return(1,$currentphase);
1.157     albertel 6306: 	    }
1.186     albertel 6307: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6308: 	    $found{'ids'}{$found}++;
                   6309: 	    $found{'usernames'}{$username}++;
                   6310: 	} else {
                   6311: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6312: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6313: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6314: 		    &scantron_get_correction($r,$i,$scan_record,
                   6315: 					     \%scantron_config,
                   6316: 					     $line,'duplicateID',$username);
1.194     albertel 6317: 		    return(1,$currentphase);
1.157     albertel 6318: 		} elsif (!defined($username)) {
                   6319: 		    &scantron_get_correction($r,$i,$scan_record,
                   6320: 					     \%scantron_config,
                   6321: 					     $line,'incorrectID');
1.194     albertel 6322: 		    return(1,$currentphase);
1.157     albertel 6323: 		}
                   6324: 		$found{'usernames'}{$username}++;
                   6325: 	    } else {
                   6326: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6327: 					 $line,'incorrectID');
1.194     albertel 6328: 		return(1,$currentphase);
1.157     albertel 6329: 	    }
                   6330: 	}
                   6331:     }
                   6332: 
                   6333:     return (0,$currentphase+1);
                   6334: }
                   6335: 
1.423     albertel 6336: =pod
                   6337: 
                   6338: =item scantron_get_correction
                   6339: 
1.424     albertel 6340:    Builds the interface screen to interact with the operator to fix a
                   6341:    specific error condition in a specific scanline
                   6342: 
                   6343:  Arguments:
                   6344:     $r           - Apache request object
                   6345:     $i           - number of the current scanline
                   6346:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6347:     $scan_config - hash ref as returned from &get_scantron_config()
                   6348:     $line        - full contents of the current scanline
                   6349:     $error       - error condition, valid values are
                   6350:                    'incorrectCODE', 'duplicateCODE',
                   6351:                    'doublebubble', 'missingbubble',
                   6352:                    'duplicateID', 'incorrectID'
                   6353:     $arg         - extra information needed
                   6354:        For errors:
                   6355:          - duplicateID   - paper number that this studentID was seen before on
                   6356:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6357:                            seen on before
                   6358:          - incorrectCODE - current incorrect CODE 
                   6359:          - doublebubble  - array ref of the bubble lines that have double
                   6360:                            bubble errors
                   6361:          - missingbubble - array ref of the bubble lines that have missing
                   6362:                            bubble errors
                   6363: 
1.423     albertel 6364: =cut
                   6365: 
1.157     albertel 6366: sub scantron_get_correction {
                   6367:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6368: 
1.454     banghart 6369: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6370: #to show both the current line and the previous one and allow skipping
                   6371: #the previous one or the current one
                   6372: 
1.161     albertel 6373:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6374:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6375: 	$r->print(" for PaperID <tt>".
                   6376: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6377:     } else {
                   6378: 	$r->print(" in scanline $i <pre>".
                   6379: 		  $line."</pre> \n");
                   6380:     }
1.242     albertel 6381:     my $message="<p>The ID on the form is  <tt>".
                   6382: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6383: 	"The name on the paper is ".
                   6384: 	$$scan_record{'scantron.LastName'}.",".
                   6385: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6386: 
1.157     albertel 6387:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6388:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6389:     if ($error =~ /ID$/) {
1.186     albertel 6390: 	if ($error eq 'incorrectID') {
1.157     albertel 6391: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6392: 	} elsif ($error eq 'duplicateID') {
                   6393: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6394: 	}
1.242     albertel 6395: 	$r->print($message);
1.157     albertel 6396: 	$r->print("<p>How should I handle this? <br /> \n");
                   6397: 	$r->print("\n<ul><li> ");
                   6398: 	#FIXME it would be nice if this sent back the user ID and
                   6399: 	#could do partial userID matches
                   6400: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6401: 				       'scantron_username','scantron_domain'));
                   6402: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6403: 	$r->print("\n@".
1.257     albertel 6404: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6405: 
                   6406: 	$r->print('</li>');
1.186     albertel 6407:     } elsif ($error =~ /CODE$/) {
                   6408: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6409: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6410: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6411: 	    $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 6412: 	}
1.224     albertel 6413: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6414: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6415: 	$r->print($message);
1.186     albertel 6416: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6417: 	$r->print("\n<br /> ");
1.194     albertel 6418: 	my $i=0;
1.273     albertel 6419: 	if ($error eq 'incorrectCODE' 
                   6420: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6421: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6422: 	    if ($closest > 0) {
                   6423: 		foreach my $testcode (@{$closest}) {
                   6424: 		    my $checked='';
1.401     albertel 6425: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6426: 		    $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' />");
                   6427: 		    $r->print("\n<br />");
                   6428: 		    $i++;
                   6429: 		}
1.194     albertel 6430: 	    }
                   6431: 	}
1.273     albertel 6432: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6433: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6434: 	    $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>");
                   6435: 	    $r->print("\n<br />");
                   6436: 	}
1.194     albertel 6437: 
1.188     albertel 6438: 	$r->print(<<ENDSCRIPT);
                   6439: <script type="text/javascript">
                   6440: function change_radio(field) {
1.190     albertel 6441:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6442:     var i;
                   6443:     for (i=0;i<slct.length;i++) {
                   6444:         if (slct[i].value==field) { slct[i].checked=true; }
                   6445:     }
                   6446: }
                   6447: </script>
                   6448: ENDSCRIPT
1.187     albertel 6449: 	my $href="/adm/pickcode?".
1.359     www      6450: 	   "form=".&escape("scantronupload").
                   6451: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6452: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6453: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6454: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6455: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6456: 	    $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')\" />");
                   6457: 	    $r->print("\n<br />");
                   6458: 	}
1.272     albertel 6459: 	$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 6460: 	$r->print("\n<br /><br />");
1.157     albertel 6461:     } elsif ($error eq 'doublebubble') {
                   6462: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6463: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6464: 		  join(',',@{$arg}).'" />');
1.242     albertel 6465: 	$r->print($message);
1.157     albertel 6466: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6467: 	foreach my $question (@{$arg}) {
1.447     foxr     6468: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6469: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6470: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6471: 				      @select_array);
1.157     albertel 6472: 	}
                   6473:     } elsif ($error eq 'missingbubble') {
                   6474: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6475: 	$r->print($message);
1.157     albertel 6476: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6477: 	$r->print("Some questions have no scanned bubbles\n");
                   6478: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6479: 		  join(',',@{$arg}).'" />');
                   6480: 	foreach my $question (@{$arg}) {
1.448     foxr     6481: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6482: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6483: 	}
                   6484:     } else {
                   6485: 	$r->print("\n<ul>");
                   6486:     }
                   6487:     $r->print("\n</li></ul>");
                   6488: 
                   6489: }
1.423     albertel 6490: 
                   6491: =pod
                   6492: 
                   6493: =item scantron_bubble_selector
                   6494:   
                   6495:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6496:    possibly showing the existing the selected bubbles if known
1.423     albertel 6497: 
                   6498:  Arguments:
                   6499:     $r           - Apache request object
                   6500:     $scan_config - hash from &get_scantron_config()
                   6501:     $quest       - number of the bubble line to make a corrector for
1.461     foxr     6502:     $lines       - array of answer lines.
1.423     albertel 6503: 
                   6504: =cut
                   6505: 
1.157     albertel 6506: sub scantron_bubble_selector {
1.461     foxr     6507:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6508:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6509: 
1.461     foxr     6510: 
1.274     albertel 6511:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6512: 
1.461     foxr     6513:     my $bubble_length = scalar(@lines);
1.460     foxr     6514: 
1.447     foxr     6515: 
1.274     albertel 6516:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6517: 
1.448     foxr     6518:     my $response = $quest-1;
                   6519:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6520: 
1.422     foxr     6521:     my $total_lines = $lines*2;
1.157     albertel 6522:     my @alphabet=('A'..'Z');
1.422     foxr     6523:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6524: 
                   6525:     for (my $l = 0; $l < $lines; $l++) {
                   6526: 	if ($l != 0) {
                   6527: 	    $r->print('<tr>');
                   6528: 	}
1.462     foxr     6529: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6530: 	for (my $i=0;$i<$max;$i++) {
                   6531: 	    $r->print("\n".'<td align="center">');
                   6532: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6533: 		$r->print('X'); 
                   6534: 		shift(@selected) ;
                   6535: 	    } else { 
                   6536: 		$r->print('&nbsp;'); 
                   6537: 	    }
                   6538: 	    $r->print('</td>');
                   6539: 	    
                   6540: 	}
                   6541: 
                   6542: 	if ($l == 0) {
                   6543: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6544: 
                   6545: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6546: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6547: 	
                   6548: 	}
                   6549: 
                   6550: 	$r->print('</tr><tr>');
                   6551: 
                   6552: 	# FIXME: This may have to be a bit more clever for
                   6553: 	#        multiline questions (different values e.g..).
                   6554: 
                   6555: 	for (my $i=0;$i<$max;$i++) {
                   6556: 	    $r->print("\n".
                   6557: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6558: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6559: 	}
                   6560: 	$r->print('</tr>');
                   6561: 
                   6562: 	    
1.157     albertel 6563:     }
1.422     foxr     6564:     $r->print('</table>');
1.157     albertel 6565: }
                   6566: 
1.423     albertel 6567: =pod
                   6568: 
                   6569: =item num_matches
                   6570: 
1.424     albertel 6571:    Counts the number of characters that are the same between the two arguments.
                   6572: 
                   6573:  Arguments:
                   6574:    $orig - CODE from the scanline
                   6575:    $code - CODE to match against
                   6576: 
                   6577:  Returns:
                   6578:    $count - integer count of the number of same characters between the
                   6579:             two arguments
                   6580: 
1.423     albertel 6581: =cut
                   6582: 
1.194     albertel 6583: sub num_matches {
                   6584:     my ($orig,$code) = @_;
                   6585:     my @code=split(//,$code);
                   6586:     my @orig=split(//,$orig);
                   6587:     my $same=0;
                   6588:     for (my $i=0;$i<scalar(@code);$i++) {
                   6589: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6590:     }
                   6591:     return $same;
                   6592: }
                   6593: 
1.423     albertel 6594: =pod
                   6595: 
                   6596: =item scantron_get_closely_matching_CODEs
                   6597: 
1.424     albertel 6598:    Cycles through all CODEs and finds the set that has the greatest
                   6599:    number of same characters as the provided CODE
                   6600: 
                   6601:  Arguments:
                   6602:    $allcodes - hash ref returned by &get_codes()
                   6603:    $CODE     - CODE from the current scanline
                   6604: 
                   6605:  Returns:
                   6606:    2 element list
                   6607:     - first elements is number of how closely matching the best fit is 
                   6608:       (5 means best set has 5 matching characters)
                   6609:     - second element is an arrary ref containing the set of valid CODEs
                   6610:       that best fit the passed in CODE
                   6611: 
1.423     albertel 6612: =cut
                   6613: 
1.194     albertel 6614: sub scantron_get_closely_matching_CODEs {
                   6615:     my ($allcodes,$CODE)=@_;
                   6616:     my @CODEs;
                   6617:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6618: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6619:     }
                   6620: 
                   6621:     return ($#CODEs,$CODEs[-1]);
                   6622: }
                   6623: 
1.423     albertel 6624: =pod
                   6625: 
                   6626: =item get_codes
                   6627: 
1.424     albertel 6628:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6629:    set of remembered CODEs.
                   6630: 
                   6631:  Arguments:
                   6632:   $old_name - name of the set of remembered CODEs
                   6633:   $cdom     - domain of the course
                   6634:   $cnum     - internal course name
                   6635: 
                   6636:  Returns:
                   6637:   %allcodes - keys are the valid CODEs, values are all 1
                   6638: 
1.423     albertel 6639: =cut
                   6640: 
1.194     albertel 6641: sub get_codes {
1.280     foxr     6642:     my ($old_name, $cdom, $cnum) = @_;
                   6643:     if (!$old_name) {
                   6644: 	$old_name=$env{'form.scantron_CODElist'};
                   6645:     }
                   6646:     if (!$cdom) {
                   6647: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6648:     }
                   6649:     if (!$cnum) {
                   6650: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6651:     }
1.278     albertel 6652:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6653: 				    $cdom,$cnum);
                   6654:     my %allcodes;
                   6655:     if ($result{"type\0$old_name"} eq 'number') {
                   6656: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6657:     } else {
                   6658: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6659:     }
1.194     albertel 6660:     return %allcodes;
                   6661: }
                   6662: 
1.423     albertel 6663: =pod
                   6664: 
                   6665: =item scantron_validate_CODE
                   6666: 
1.424     albertel 6667:    Validates all scanlines in the selected file to not have any
                   6668:    invalid or underspecified CODEs and that none of the codes are
                   6669:    duplicated if this was requested.
                   6670: 
1.423     albertel 6671: =cut
                   6672: 
1.157     albertel 6673: sub scantron_validate_CODE {
                   6674:     my ($r,$currentphase) = @_;
1.257     albertel 6675:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6676:     if ($scantron_config{'CODElocation'} &&
                   6677: 	$scantron_config{'CODEstart'} &&
                   6678: 	$scantron_config{'CODElength'}) {
1.257     albertel 6679: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6680: 	    &FIXME_blow_up()
                   6681: 	}
                   6682:     } else {
                   6683: 	return (0,$currentphase+1);
                   6684:     }
                   6685:     
                   6686:     my %usedCODEs;
                   6687: 
1.194     albertel 6688:     my %allcodes=&get_codes();
1.186     albertel 6689: 
1.447     foxr     6690:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6691: 
1.186     albertel 6692:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6693:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6694: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6695: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6696: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6697: 						 $scan_data);
                   6698: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6699: 	my $error=0;
1.224     albertel 6700: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6701: 	    &scantron_get_correction($r,$i,$scan_record,
                   6702: 				     \%scantron_config,
                   6703: 				     $line,'incorrectCODE',\%allcodes);
                   6704: 	    return(1,$currentphase);
                   6705: 	}
1.221     albertel 6706: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6707: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6708: 	    &scantron_get_correction($r,$i,$scan_record,
                   6709: 				     \%scantron_config,
1.194     albertel 6710: 				     $line,'incorrectCODE',\%allcodes);
                   6711: 	    return(1,$currentphase);
1.186     albertel 6712: 	}
1.214     albertel 6713: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6714: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6715: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6716: 	    &scantron_get_correction($r,$i,$scan_record,
                   6717: 				     \%scantron_config,
1.194     albertel 6718: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6719: 	    return(1,$currentphase);
1.186     albertel 6720: 	}
1.194     albertel 6721: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6722:     }
1.157     albertel 6723:     return (0,$currentphase+1);
                   6724: }
                   6725: 
1.423     albertel 6726: =pod
                   6727: 
                   6728: =item scantron_validate_doublebubble
                   6729: 
1.424     albertel 6730:    Validates all scanlines in the selected file to not have any
                   6731:    bubble lines with multiple bubbles marked.
                   6732: 
1.423     albertel 6733: =cut
                   6734: 
1.157     albertel 6735: sub scantron_validate_doublebubble {
                   6736:     my ($r,$currentphase) = @_;
                   6737:     #get student info
                   6738:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6739:     my %idmap=&username_to_idmap($classlist);
                   6740: 
                   6741:     #get scantron line setup
1.257     albertel 6742:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6743:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6744: 
                   6745:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6746: 
1.157     albertel 6747:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6748: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6749: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6750: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6751: 						 $scan_data);
                   6752: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6753: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6754: 				 'doublebubble',
                   6755: 				 $$scan_record{'scantron.doubleerror'});
                   6756:     	return (1,$currentphase);
                   6757:     }
                   6758:     return (0,$currentphase+1);
                   6759: }
                   6760: 
1.423     albertel 6761: =pod
                   6762: 
                   6763: =item scantron_get_maxbubble
                   6764: 
1.424     albertel 6765:    Returns the maximum number of bubble lines that are expected to
                   6766:    occur. Does this by walking the selected sequence rendering the
                   6767:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6768:    for what the current value of the problem counter is.
                   6769: 
1.447     foxr     6770:    Caches the results to $env{'form.scantron_maxbubble'},
                   6771:    $env{'form.scantron.bubble_lines.n'} and 
                   6772:    $env{'form.scantron.first_bubble_line.n'}
                   6773:    which are the total number of bubble, lines, the number of bubble
                   6774:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6775: 
1.423     albertel 6776: =cut
                   6777: 
1.330     albertel 6778: sub scantron_get_maxbubble {    
1.257     albertel 6779:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6780: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6781: 	&restore_bubble_lines();
1.257     albertel 6782: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6783:     }
1.330     albertel 6784: 
1.447     foxr     6785:     my (undef, undef, $sequence) =
1.257     albertel 6786: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6787: 
1.447     foxr     6788:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6789:     my $map=$navmap->getResourceByUrl($sequence);
                   6790:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6791: 
                   6792:     &Apache::lonxml::clear_problem_counter();
                   6793: 
1.435     foxr     6794:     my $uname       = $env{'form.student'};
                   6795:     my $udom        = $env{'form.userdom'};
                   6796:     my $cid         = $env{'request.course.id'};
                   6797:     my $total_lines = 0;
                   6798:     %bubble_lines_per_response = ();
1.447     foxr     6799:     %first_bubble_line         = ();
1.435     foxr     6800: 
1.447     foxr     6801:   
                   6802:     my $response_number = 0;
                   6803:     my $bubble_line     = 0;
1.191     albertel 6804:     foreach my $resource (@resources) {
1.435     foxr     6805: 	my $symb = $resource->symb();
1.447     foxr     6806: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6807: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6808: 					('symb' => $resource->symb()),
                   6809: 					('grade_target' => 'analyze'),
                   6810: 					('grade_courseid' => $cid),
                   6811: 					('grade_domain' => $udom),
                   6812: 					('grade_username' => $uname));
1.436     albertel 6813: 	my (undef, $an) =
1.435     foxr     6814: 	    split(/_HASH_REF__/,$result, 2);
                   6815: 
                   6816: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6817: 
                   6818: 
                   6819: 
                   6820: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6821: 
1.460     foxr     6822: 
                   6823: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
1.447     foxr     6824: 
                   6825: 	    # TODO - make this a persistent hash not an array.
                   6826: 
                   6827: 
                   6828: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6829: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6830: 	    $response_number++;
                   6831: 
                   6832: 	    $bubble_line +=  $lines;
                   6833: 	    $total_lines +=  $lines;
1.435     foxr     6834: 	}
                   6835: 
1.191     albertel 6836:     }
                   6837:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6838: 
                   6839:     &save_bubble_lines();
1.330     albertel 6840:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6841: 	$total_lines;
1.257     albertel 6842:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6843: }
                   6844: 
1.423     albertel 6845: =pod
                   6846: 
                   6847: =item scantron_validate_missingbubbles
                   6848: 
1.424     albertel 6849:    Validates all scanlines in the selected file to not have any
1.447     foxr     6850:     answers that don't have bubbles that have not been verified
                   6851:     to be bubble free.
1.424     albertel 6852: 
1.423     albertel 6853: =cut
                   6854: 
1.157     albertel 6855: sub scantron_validate_missingbubbles {
                   6856:     my ($r,$currentphase) = @_;
                   6857:     #get student info
                   6858:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6859:     my %idmap=&username_to_idmap($classlist);
                   6860: 
                   6861:     #get scantron line setup
1.257     albertel 6862:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6863:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6864:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6865:     if (!$max_bubble) { $max_bubble=2**31; }
                   6866:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6867: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6868: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6869: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6870: 						 $scan_data);
                   6871: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6872: 	my @to_correct;
                   6873: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6874: 	    if ($missing > $max_bubble) { next; }
                   6875: 	    push(@to_correct,$missing);
                   6876: 	}
                   6877: 	if (@to_correct) {
                   6878: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6879: 				     $line,'missingbubble',\@to_correct);
                   6880: 	    return (1,$currentphase);
                   6881: 	}
                   6882: 
                   6883:     }
                   6884:     return (0,$currentphase+1);
                   6885: }
                   6886: 
1.423     albertel 6887: =pod
                   6888: 
                   6889: =item scantron_process_students
                   6890: 
                   6891:    Routine that does the actual grading of the bubble sheet information.
                   6892: 
                   6893:    The parsed scanline hash is added to %env 
                   6894: 
                   6895:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6896:    foreach resource , with the form data of
                   6897: 
                   6898: 	'submitted'     =>'scantron' 
                   6899: 	'grade_target'  =>'grade',
                   6900: 	'grade_username'=> username of student
                   6901: 	'grade_domain'  => domain of student
                   6902: 	'grade_courseid'=> of course
                   6903: 	'grade_symb'    => symb of resource to grade
                   6904: 
                   6905:     This triggers a grading pass. The problem grading code takes care
                   6906:     of converting the bubbled letter information (now in %env) into a
                   6907:     valid submission.
                   6908: 
                   6909: =cut
                   6910: 
1.82      albertel 6911: sub scantron_process_students {
1.75      albertel 6912:     my ($r) = @_;
1.257     albertel 6913:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6914:     my ($symb)=&get_symb($r);
1.81      albertel 6915:     if (!$symb) {return '';}
1.324     albertel 6916:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6917: 
1.257     albertel 6918:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6919:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6920:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6921:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6922:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6923:     my $map=$navmap->getResourceByUrl($sequence);
                   6924:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6925: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6926:     my $result= <<SCANTRONFORM;
1.81      albertel 6927: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6928:   <input type="hidden" name="command" value="scantron_configphase" />
                   6929:   $default_form_data
                   6930: SCANTRONFORM
1.82      albertel 6931:     $r->print($result);
                   6932: 
                   6933:     my @delayqueue;
1.140     albertel 6934:     my %completedstudents;
                   6935:     
1.200     albertel 6936:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6937:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6938:  				    'Scantron Progress',$count,
1.195     albertel 6939: 				    'inline',undef,'scantronupload');
1.140     albertel 6940:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6941: 					  'Processing first student');
                   6942:     my $start=&Time::HiRes::time();
1.158     albertel 6943:     my $i=-1;
1.200     albertel 6944:     my ($uname,$udom,$started);
1.447     foxr     6945: 
                   6946:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6947: 
1.157     albertel 6948:     while ($i<$scanlines->{'count'}) {
                   6949:  	($uname,$udom)=('','');
                   6950:  	$i++;
1.200     albertel 6951:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6952:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6953: 	if ($started) {
                   6954: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6955: 						     'last student');
                   6956: 	}
                   6957: 	$started=1;
1.157     albertel 6958:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6959:  						 $scan_data);
                   6960:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6961:  					      \%idmap,$i)) {
                   6962:   	    &scantron_add_delay(\@delayqueue,$line,
                   6963:  				'Unable to find a student that matches',1);
                   6964:  	    next;
                   6965:   	}
                   6966:  	if (exists $completedstudents{$uname}) {
                   6967:  	    &scantron_add_delay(\@delayqueue,$line,
                   6968:  				'Student '.$uname.' has multiple sheets',2);
                   6969:  	    next;
                   6970:  	}
                   6971:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6972: 
                   6973: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6974:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6975: 
                   6976: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6977: 	    &scantron_putfile($scanlines,$scan_data);
                   6978: 	}
1.161     albertel 6979: 	
                   6980: 	my $i=0;
1.83      albertel 6981: 	foreach my $resource (@resources) {
1.85      albertel 6982: 	    $i++;
1.193     albertel 6983: 	    my %form=('submitted'     =>'scantron',
                   6984: 		      'grade_target'  =>'grade',
                   6985: 		      'grade_username'=>$uname,
                   6986: 		      'grade_domain'  =>$udom,
1.257     albertel 6987: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6988: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6989: 	    if (exists($scan_record->{'scantron.CODE'})
                   6990: 		&& 
                   6991: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6992: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6993: 	    } else {
                   6994: 		$form{'CODE'}='';
1.193     albertel 6995: 	    }
                   6996: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6997: 	    if ($result ne '') {
                   6998: 	    }
1.213     albertel 6999: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7000: 	}
1.140     albertel 7001: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7002: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7003:     } continue {
1.330     albertel 7004: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7005: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7006:     }
1.140     albertel 7007:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7008: #    my $lasttime = &Time::HiRes::time()-$start;
                   7009: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7010: 
1.200     albertel 7011:     $r->print("</form>");
1.324     albertel 7012:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7013:     return '';
1.75      albertel 7014: }
1.157     albertel 7015: 
1.423     albertel 7016: =pod
                   7017: 
                   7018: =item scantron_upload_scantron_data
                   7019: 
                   7020:     Creates the screen for adding a new bubble sheet data file to a course.
                   7021: 
                   7022: =cut
                   7023: 
1.157     albertel 7024: sub scantron_upload_scantron_data {
                   7025:     my ($r)=@_;
1.257     albertel 7026:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7027:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7028: 							  'domainid',
                   7029: 							  'coursename');
1.257     albertel 7030:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7031: 						   'domainid');
1.324     albertel 7032:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 7033:     $r->print(<<UPLOAD);
                   7034: <script type="text/javascript" language="javascript">
                   7035:     function checkUpload(formname) {
                   7036: 	if (formname.upfile.value == "") {
                   7037: 	    alert("Please use the browse button to select a file from your local directory.");
                   7038: 	    return false;
                   7039: 	}
                   7040: 	formname.submit();
                   7041:     }
                   7042: </script>
                   7043: 
                   7044: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7045: $default_form_data
1.181     albertel 7046: <table>
                   7047: <tr><td>$select_link </td></tr>
                   7048: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7049: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7050: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7051: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7052: </table>
1.157     albertel 7053: <input name='command' value='scantronupload_save' type='hidden' />
                   7054: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7055: </form>
                   7056: UPLOAD
                   7057:     return '';
                   7058: }
                   7059: 
1.423     albertel 7060: =pod
                   7061: 
                   7062: =item scantron_upload_scantron_data_save
                   7063: 
                   7064:    Adds a provided bubble information data file to the course if user
                   7065:    has the correct privileges to do so.  
                   7066: 
                   7067: =cut
                   7068: 
1.157     albertel 7069: sub scantron_upload_scantron_data_save {
                   7070:     my($r)=@_;
1.324     albertel 7071:     my ($symb)=&get_symb($r,1);
1.182     albertel 7072:     my $doanotherupload=
                   7073: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7074: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7075: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7076: 	'</form>'."\n";
1.257     albertel 7077:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7078: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7079: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7080: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7081: 	if ($symb) {
1.324     albertel 7082: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7083: 	} else {
                   7084: 	    $r->print($doanotherupload);
                   7085: 	}
1.162     albertel 7086: 	return '';
                   7087:     }
1.257     albertel 7088:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7089:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7090:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7091:     #FIXME
                   7092:     #copied from lonnet::userfileupload()
                   7093:     #make that function able to target a specified course
                   7094:     # Replace Windows backslashes by forward slashes
                   7095:     $fname=~s/\\/\//g;
                   7096:     # Get rid of everything but the actual filename
                   7097:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7098:     # Replace spaces by underscores
                   7099:     $fname=~s/\s+/\_/g;
                   7100:     # Replace all other weird characters by nothing
                   7101:     $fname=~s/[^\w\.\-]//g;
                   7102:     # See if there is anything left
                   7103:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7104:     my $uploadedfile=$fname;
1.157     albertel 7105:     $fname='scantron_orig_'.$fname;
1.257     albertel 7106:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7107: 	$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 7108:     } else {
1.275     albertel 7109: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7110: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7111: 	    $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 7112: 	} else {
1.398     albertel 7113: 	    $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 7114: 	}
                   7115:     }
1.174     albertel 7116:     if ($symb) {
1.209     ng       7117: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7118:     } else {
1.182     albertel 7119: 	$r->print($doanotherupload);
1.174     albertel 7120:     }
1.157     albertel 7121:     return '';
                   7122: }
                   7123: 
1.423     albertel 7124: =pod
                   7125: 
                   7126: =item valid_file
                   7127: 
1.424     albertel 7128:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7129: 
                   7130: =cut
                   7131: 
1.202     albertel 7132: sub valid_file {
                   7133:     my ($requested_file)=@_;
                   7134:     foreach my $filename (sort(&scantron_filenames())) {
                   7135: 	if ($requested_file eq $filename) { return 1; }
                   7136:     }
                   7137:     return 0;
                   7138: }
                   7139: 
1.423     albertel 7140: =pod
                   7141: 
                   7142: =item scantron_download_scantron_data
                   7143: 
                   7144:    Shows a list of the three internal files (original, corrected,
                   7145:    skipped) for a specific bubble sheet data file that exists in the
                   7146:    course.
                   7147: 
                   7148: =cut
                   7149: 
1.202     albertel 7150: sub scantron_download_scantron_data {
                   7151:     my ($r)=@_;
1.324     albertel 7152:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7153:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7154:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7155:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7156:     if (! &valid_file($file)) {
                   7157: 	$r->print(<<ERROR);
                   7158: 	<p>
                   7159: 	    The requested file name was invalid.
                   7160:         </p>
                   7161: ERROR
1.324     albertel 7162: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7163: 	return;
                   7164:     }
                   7165:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7166:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7167:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7168:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7169:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7170:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7171:     $r->print(<<DOWNLOAD);
                   7172:     <p>
                   7173: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7174:     </p>
                   7175:     <p>
                   7176: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7177:     </p>
                   7178:     <p>
                   7179: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7180:     </p>
                   7181: DOWNLOAD
1.324     albertel 7182:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7183:     return '';
                   7184: }
1.157     albertel 7185: 
1.423     albertel 7186: =pod
                   7187: 
                   7188: =back
                   7189: 
                   7190: =cut
                   7191: 
1.75      albertel 7192: #-------- end of section for handling grading scantron forms -------
                   7193: #
                   7194: #-------------------------------------------------------------------
                   7195: 
1.72      ng       7196: #-------------------------- Menu interface -------------------------
                   7197: #
                   7198: #--- Show a Grading Menu button - Calls the next routine ---
                   7199: sub show_grading_menu_form {
1.324     albertel 7200:     my ($symb)=@_;
1.125     ng       7201:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7202: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7203: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7204: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7205: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7206: 	'</form>'."\n";
                   7207:     return $result;
                   7208: }
                   7209: 
1.77      ng       7210: # -- Retrieve choices for grading form
                   7211: sub savedState {
                   7212:     my %savedState = ();
1.257     albertel 7213:     if ($env{'form.saveState'}) {
                   7214: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7215: 	    my ($key,$value) = split(/=/,$_,2);
                   7216: 	    $savedState{$key} = $value;
                   7217: 	}
                   7218:     }
                   7219:     return \%savedState;
                   7220: }
1.76      ng       7221: 
1.443     banghart 7222: sub grading_menu {
                   7223:     my ($request) = @_;
                   7224:     my ($symb)=&get_symb($request);
                   7225:     if (!$symb) {return '';}
                   7226:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7227:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7228: 
1.444     banghart 7229:     $request->print($table);
1.443     banghart 7230:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7231:                   'handgrade'=>$hdgrade,
                   7232:                   'probTitle'=>$probTitle,
                   7233:                   'command'=>'submit_options',
                   7234:                   'saveState'=>"",
                   7235:                   'gradingMenu'=>1,
                   7236:                   'showgrading'=>"yes");
                   7237:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7238:     my @menu = ({ url => $url,
                   7239:                      name => &mt('Manual Grading/View Submissions'),
                   7240:                      short_description => 
                   7241:     &mt('Start the process of hand grading submissions.'),
                   7242:                  });
                   7243:     $fields{'command'} = 'csvform';
                   7244:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7245:     push (@menu, { url => $url,
                   7246:                    name => &mt('Upload Scores'),
                   7247:                    short_description => 
                   7248:             &mt('Specify a file containing the class scores for current resource.')});
                   7249:     $fields{'command'} = 'processclicker';
                   7250:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7251:     push (@menu, { url => $url,
                   7252:                    name => &mt('Process Clicker'),
                   7253:                    short_description => 
                   7254:             &mt('Specify a file containing the clicker information for this resource.')});
                   7255:     $fields{'command'} = 'scantron_selectphase';
                   7256:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7257:     push (@menu, { url => $url,
1.454     banghart 7258:                    name => &mt('Grade/Manage Scantron Forms'),
                   7259:                    short_description => 
                   7260:             &mt('')});
1.443     banghart 7261:     $fields{'command'} = 'verify';
                   7262:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7263:     push (@menu, { url => "",
1.443     banghart 7264:                    name => &mt('Verify Receipt'),
                   7265:                    short_description => 
                   7266:             &mt('')});
                   7267:     #
                   7268:     # Create the menu
                   7269:     my $Str;
1.444     banghart 7270:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7271:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7272:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7273:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7274: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7275: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7276: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7277: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7278: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7279: 
1.443     banghart 7280:     foreach my $menudata (@menu) {
1.445     banghart 7281:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7282:             $Str .='    <h3><a '.
                   7283:                 $menudata->{'jscript'}.
                   7284:                 ' href="'.
                   7285:                 $menudata->{'url'}.'" >'.
                   7286:                 $menudata->{'name'}."</a></h3>\n";
                   7287:         } else {
1.458     banghart 7288:             $Str .='    <h3><input type="button" value="Verify Receipt" '.
1.445     banghart 7289:                 $menudata->{'jscript'}.
1.458     banghart 7290:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7291:                 ' /></h3>';
1.446     banghart 7292:             $Str .= ('&nbsp;'x8).
                   7293:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7294:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7295:         }
1.443     banghart 7296:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7297:             "\n";
                   7298:     }
                   7299:     $Str .="</dl>\n";
1.444     banghart 7300:     $Str .="</form>\n";
1.443     banghart 7301:     $request->print(<<GRADINGMENUJS);
                   7302: <script type="text/javascript" language="javascript">
                   7303:     function checkChoice(formname,val,cmdx) {
                   7304: 	if (val <= 2) {
                   7305: 	    var cmd = radioSelection(formname.radioChoice);
                   7306: 	    var cmdsave = cmd;
                   7307: 	} else {
                   7308: 	    cmd = cmdx;
                   7309: 	    cmdsave = 'submission';
                   7310: 	}
                   7311: 	formname.command.value = cmd;
                   7312: 	if (val < 5) formname.submit();
                   7313: 	if (val == 5) {
1.458     banghart 7314: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7315: 	        return false;
                   7316: 	    } else {
                   7317: 	        formname.submit();
                   7318: 	    }
1.445     banghart 7319: 	}
                   7320:     }
1.443     banghart 7321: 
                   7322:     function checkReceiptNo(formname,nospace) {
                   7323: 	var receiptNo = formname.receipt.value;
                   7324: 	var checkOpt = false;
                   7325: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7326: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7327: 	if (checkOpt) {
                   7328: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7329: 	    formname.receipt.value = "";
                   7330: 	    formname.receipt.focus();
                   7331: 	    return false;
                   7332: 	}
                   7333: 	return true;
                   7334:     }
                   7335: </script>
                   7336: GRADINGMENUJS
                   7337:     &commonJSfunctions($request);
                   7338:     return $Str;    
                   7339: }
                   7340: 
                   7341: 
                   7342: #--- Displays the submissions first page -------
                   7343: sub submit_options {
1.72      ng       7344:     my ($request) = @_;
1.324     albertel 7345:     my ($symb)=&get_symb($request);
1.72      ng       7346:     if (!$symb) {return '';}
1.76      ng       7347:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7348: 
                   7349:     $request->print(<<GRADINGMENUJS);
                   7350: <script type="text/javascript" language="javascript">
1.116     ng       7351:     function checkChoice(formname,val,cmdx) {
                   7352: 	if (val <= 2) {
                   7353: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7354: 	    var cmdsave = cmd;
1.116     ng       7355: 	} else {
                   7356: 	    cmd = cmdx;
1.118     ng       7357: 	    cmdsave = 'submission';
1.116     ng       7358: 	}
                   7359: 	formname.command.value = cmd;
1.118     ng       7360: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7361: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7362: 	if (val < 5) formname.submit();
                   7363: 	if (val == 5) {
1.72      ng       7364: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7365: 	    formname.submit();
                   7366: 	}
1.238     albertel 7367: 	if (val < 7) formname.submit();
1.72      ng       7368:     }
                   7369: 
                   7370:     function checkReceiptNo(formname,nospace) {
                   7371: 	var receiptNo = formname.receipt.value;
                   7372: 	var checkOpt = false;
                   7373: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7374: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7375: 	if (checkOpt) {
                   7376: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7377: 	    formname.receipt.value = "";
                   7378: 	    formname.receipt.focus();
                   7379: 	    return false;
                   7380: 	}
                   7381: 	return true;
                   7382:     }
                   7383: </script>
                   7384: GRADINGMENUJS
1.118     ng       7385:     &commonJSfunctions($request);
1.398     albertel 7386:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7387:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7388:     $result.=$table;
1.76      ng       7389:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7390:     my $savedState = &savedState();
1.118     ng       7391:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7392:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7393:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7394:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7395: 
                   7396:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7397: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7398: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7399: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7400: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7401: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7402: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7403: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7404: 
1.446     banghart 7405:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7406: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7407: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7408: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7409: 
1.326     albertel 7410:     $result.='<table width="100%" border="0">';
1.442     banghart 7411:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7412:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7413:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7414:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
1.455     banghart 7415:     $result.='<td><b>'.&mt('Submission Status').'</td>'."\n";
1.442     banghart 7416:     $result.='</tr>';
1.116     ng       7417:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7418: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7419:     if (ref($sections)) {
1.155     albertel 7420: 	foreach (sort (@$sections)) {
                   7421: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7422: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7423: 	}
1.116     ng       7424:     }
1.401     albertel 7425:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7426:     $result.= '</td><td>'."\n";
                   7427:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7428:     $result.='</td><td>'."\n";
                   7429:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7430: 
1.455     banghart 7431:     $result.='</td>';
                   7432:     $result.='<td><select name="submitonly" size="3">'.
1.145     albertel 7433: 	'<option value="yes" '.
1.401     albertel 7434: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7435: 	'<option value="queued" '.
1.401     albertel 7436: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7437: 	'<option value="graded" '.
1.401     albertel 7438: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7439: 	'<option value="incorrect" '.
1.401     albertel 7440: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7441: 	'<option value="all" '.
1.455     banghart 7442: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>';
1.72      ng       7443: 
1.455     banghart 7444:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
                   7445: 	'<input type="radio" name="radioChoice" value="submission" '.
                   7446: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
                   7447: 	'</label> </td></tr>'."\n";
                   7448: 
                   7449:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3">'.
1.288     albertel 7450: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7451: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7452: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7453: 
1.455     banghart 7454:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
                   7455: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
                   7456: 	'</td></tr>'."\n";
                   7457: 
                   7458: 
                   7459:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="3">'.
                   7460: 	'<br /><label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7461: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.455     banghart 7462: 	'The <b>complete</b> set/page/sequence/folder: For one student</label></td></tr>'."\n";
1.46      ng       7463: 
1.455     banghart 7464:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
1.126     ng       7465: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7466: 	'</td></tr></table>'."\n";
                   7467: 
1.446     banghart 7468:     $result.='</td>'; #<td valign="top">';
1.116     ng       7469: 
1.446     banghart 7470: #    $result.='<table width="100%" border="0">';
                   7471: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7472: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7473: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7474: #
                   7475: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7476: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7477: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7478: #
                   7479: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7480: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7481: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7482: #
                   7483: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7484: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7485: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7486: #	    ' '.&mt('receipt').': '.
                   7487: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7488: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7489: #	    '</td></tr>'."\n";
                   7490: #    } 
                   7491: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7492: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7493: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7494: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7495: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7496: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7497: #
                   7498: #    $result.='</table>'."\n".'</td>';
                   7499:     $result.= '</tr></table>'."\n".
1.401     albertel 7500: 	'</td></tr></table></form>'."\n";
1.44      ng       7501:     return $result;
1.2       albertel 7502: }
                   7503: 
1.285     albertel 7504: sub reset_perm {
                   7505:     undef(%perm);
                   7506: }
                   7507: 
                   7508: sub init_perm {
                   7509:     &reset_perm();
1.300     albertel 7510:     foreach my $test_perm ('vgr','mgr','opa') {
                   7511: 
                   7512: 	my $scope = $env{'request.course.id'};
                   7513: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7514: 
                   7515: 	    $scope .= '/'.$env{'request.course.sec'};
                   7516: 	    if ( $perm{$test_perm}=
                   7517: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7518: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7519: 	    } else {
                   7520: 		delete($perm{$test_perm});
                   7521: 	    }
1.285     albertel 7522: 	}
                   7523:     }
                   7524: }
                   7525: 
1.400     www      7526: sub gather_clicker_ids {
1.408     albertel 7527:     my %clicker_ids;
1.400     www      7528: 
                   7529:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7530: 
                   7531:     # Set up a couple variables.
1.407     albertel 7532:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7533:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7534:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7535: 
1.407     albertel 7536:     foreach my $student (keys(%$classlist)) {
1.438     www      7537:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7538:         my $username = $classlist->{$student}->[$username_idx];
                   7539:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7540:         my $clickers =
1.408     albertel 7541: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7542:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7543:             $id=~s/^[\#0]+//;
1.421     www      7544:             $id=~s/[\-\:]//g;
1.407     albertel 7545:             if (exists($clicker_ids{$id})) {
1.408     albertel 7546: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7547:             } else {
1.408     albertel 7548: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7549:             }
                   7550:         }
                   7551:     }
1.407     albertel 7552:     return %clicker_ids;
1.400     www      7553: }
                   7554: 
1.402     www      7555: sub gather_adv_clicker_ids {
1.408     albertel 7556:     my %clicker_ids;
1.402     www      7557:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7558:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7559:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7560:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7561:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7562:             my ($puname,$pudom)=split(/\:/,$person);
                   7563:             my $clickers =
1.408     albertel 7564: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7565:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7566: 		$id=~s/^[\#0]+//;
1.421     www      7567:                 $id=~s/[\-\:]//g;
1.408     albertel 7568: 		if (exists($clicker_ids{$id})) {
                   7569: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7570: 		} else {
                   7571: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7572: 		}
1.405     www      7573:             }
1.402     www      7574:         }
                   7575:     }
1.407     albertel 7576:     return %clicker_ids;
1.402     www      7577: }
                   7578: 
1.413     www      7579: sub clicker_grading_parameters {
                   7580:     return ('gradingmechanism' => 'scalar',
                   7581:             'upfiletype' => 'scalar',
                   7582:             'specificid' => 'scalar',
                   7583:             'pcorrect' => 'scalar',
                   7584:             'pincorrect' => 'scalar');
                   7585: }
                   7586: 
1.400     www      7587: sub process_clicker {
                   7588:     my ($r)=@_;
                   7589:     my ($symb)=&get_symb($r);
                   7590:     if (!$symb) {return '';}
                   7591:     my $result=&checkforfile_js();
                   7592:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7593:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7594:     $result.=$table;
                   7595:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7596:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7597:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7598:         '.</b></td></tr>'."\n";
                   7599:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7600: # Attempt to restore parameters from last session, set defaults if not present
                   7601:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7602:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7603:                                                  \%Saveable_Parameters);
                   7604:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7605:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7606:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7607:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7608: 
                   7609:     my %checked;
                   7610:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7611:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7612:           $checked{$gradingmechanism}="checked='checked'";
                   7613:        }
                   7614:     }
                   7615: 
1.400     www      7616:     my $upload=&mt("Upload File");
                   7617:     my $type=&mt("Type");
1.402     www      7618:     my $attendance=&mt("Award points just for participation");
                   7619:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7620:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7621:     my $pcorrect=&mt("Percentage points for correct solution");
                   7622:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7623:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7624: 						   ('iclicker' => 'i>clicker',
                   7625:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7626:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7627:     $result.=<<ENDUPFORM;
1.402     www      7628: <script type="text/javascript">
                   7629: function sanitycheck() {
                   7630: // Accept only integer percentages
                   7631:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7632:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7633: // Find out grading choice
                   7634:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7635:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7636:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7637:       }
                   7638:    }
                   7639: // By default, new choice equals user selection
                   7640:    newgradingchoice=gradingchoice;
                   7641: // Not good to give more points for false answers than correct ones
                   7642:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7643:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7644:    }
                   7645: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7646:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7647:       document.forms.gradesupload.pcorrect.value=100;
                   7648:       document.forms.gradesupload.pincorrect.value=100;
                   7649:    }
                   7650: // If the values are different, cannot be attendance only
                   7651:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7652:        (gradingchoice=='attendance')) {
                   7653:        newgradingchoice='personnel';
                   7654:    }
                   7655: // Change grading choice to new one
                   7656:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7657:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7658:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7659:       } else {
                   7660:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7661:       }
                   7662:    }
                   7663: // Remember the old state
                   7664:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7665: }
                   7666: </script>
1.400     www      7667: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7668: <input type="hidden" name="symb" value="$symb" />
                   7669: <input type="hidden" name="command" value="processclickerfile" />
                   7670: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7671: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7672: <input type="file" name="upfile" size="50" />
                   7673: <br /><label>$type: $selectform</label>
1.451     albertel 7674: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7675: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7676: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7677: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7678: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7679: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7680: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7681: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7682: </form>
                   7683: ENDUPFORM
                   7684:     $result.='</td></tr></table>'."\n".
                   7685:              '</td></tr></table><br /><br />'."\n";
                   7686:     $result.=&show_grading_menu_form($symb);
                   7687:     return $result;
                   7688: }
                   7689: 
                   7690: sub process_clicker_file {
                   7691:     my ($r)=@_;
                   7692:     my ($symb)=&get_symb($r);
                   7693:     if (!$symb) {return '';}
1.413     www      7694: 
                   7695:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7696:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7697:                                               \%Saveable_Parameters);
                   7698: 
1.400     www      7699:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7700:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7701: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7702: 	return $result.&show_grading_menu_form($symb);
1.404     www      7703:     }
1.407     albertel 7704:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7705:     my %correct_ids;
1.404     www      7706:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7707: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7708:     }
                   7709:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7710: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7711: 	   $correct_id=~tr/a-z/A-Z/;
                   7712: 	   $correct_id=~s/\s//gs;
                   7713: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7714:            $correct_id=~s/[\-\:]//g;
1.414     www      7715:            if ($correct_id) {
                   7716: 	      $correct_ids{$correct_id}='specified';
                   7717:            }
                   7718:         }
1.400     www      7719:     }
1.404     www      7720:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7721: 	$result.=&mt('Score based on attendance only');
1.404     www      7722:     } else {
1.408     albertel 7723: 	my $number=0;
1.411     www      7724: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7725: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7726: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7727: 	    if ($correct_ids{$id} eq 'specified') {
                   7728: 		$result.=&mt('specified');
                   7729: 	    } else {
                   7730: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7731: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7732: 	    }
                   7733: 	    $number++;
                   7734: 	}
1.411     www      7735:         $result.="</p>\n";
1.408     albertel 7736: 	if ($number==0) {
                   7737: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7738: 	    return $result.&show_grading_menu_form($symb);
                   7739: 	}
1.404     www      7740:     }
1.405     www      7741:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7742:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7743: 		     '<span class="LC_error">',
                   7744: 		     '</span>',
                   7745: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7746:         return $result.&show_grading_menu_form($symb);
                   7747:     }
1.410     www      7748: 
                   7749: # Were able to get all the info needed, now analyze the file
                   7750: 
1.411     www      7751:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7752:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7753:     my $heading=&mt('Scanning clicker file');
                   7754:     $result.=(<<ENDHEADER);
                   7755: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7756: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7757: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7758: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7759: <input type="hidden" name="symb" value="$symb" />
                   7760: <input type="hidden" name="command" value="assignclickergrades" />
                   7761: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7762: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7763: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7764: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7765: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7766: ENDHEADER
1.408     albertel 7767:     my %responses;
                   7768:     my @questiontitles;
1.405     www      7769:     my $errormsg='';
                   7770:     my $number=0;
                   7771:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7772: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7773:     }
1.419     www      7774:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7775:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7776:     }
1.411     www      7777:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7778:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7779:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7780:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7781:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7782:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7783:              '<br />';
1.414     www      7784: # Remember Question Titles
                   7785: # FIXME: Possibly need delimiter other than ":"
                   7786:     for (my $i=0;$i<$number;$i++) {
                   7787:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7788:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7789:     }
1.411     www      7790:     my $correct_count=0;
                   7791:     my $student_count=0;
                   7792:     my $unknown_count=0;
1.414     www      7793: # Match answers with usernames
                   7794: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7795:     foreach my $id (keys(%responses)) {
1.410     www      7796:        if ($correct_ids{$id}) {
1.414     www      7797:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7798:           $correct_count++;
1.410     www      7799:        } elsif ($clicker_ids{$id}) {
1.437     www      7800:           if ($clicker_ids{$id}=~/\,/) {
                   7801: # More than one user with the same clicker!
                   7802:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7803:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7804:                            "<select name='multi".$id."'>";
                   7805:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7806:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7807:              }
                   7808:              $result.='</select>';
                   7809:              $unknown_count++;
                   7810:           } else {
                   7811: # Good: found one and only one user with the right clicker
                   7812:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7813:              $student_count++;
                   7814:           }
1.410     www      7815:        } else {
1.411     www      7816:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7817:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7818:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7819:                    "\n".&mt("Domain").": ".
                   7820:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7821:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7822:           $unknown_count++;
1.410     www      7823:        }
1.405     www      7824:     }
1.412     www      7825:     $result.='<hr />'.
                   7826:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7827:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7828:        if ($correct_count==0) {
                   7829:           $errormsg.="Found no correct answers answers for grading!";
                   7830:        } elsif ($correct_count>1) {
1.414     www      7831:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7832:        }
                   7833:     }
1.428     www      7834:     if ($number<1) {
                   7835:        $errormsg.="Found no questions.";
                   7836:     }
1.412     www      7837:     if ($errormsg) {
                   7838:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7839:     } else {
                   7840:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7841:     }
                   7842:     $result.='</form></td></tr></table>'."\n".
1.410     www      7843:              '</td></tr></table><br /><br />'."\n";
1.404     www      7844:     return $result.&show_grading_menu_form($symb);
1.400     www      7845: }
                   7846: 
1.405     www      7847: sub iclicker_eval {
1.406     www      7848:     my ($questiontitles,$responses)=@_;
1.405     www      7849:     my $number=0;
                   7850:     my $errormsg='';
                   7851:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7852:         my %components=&Apache::loncommon::record_sep($line);
                   7853:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7854: 	if ($entries[0] eq 'Question') {
                   7855: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7856: 		$$questiontitles[$number]=$entries[$i];
                   7857: 		$number++;
                   7858: 	    }
                   7859: 	}
                   7860: 	if ($entries[0]=~/^\#/) {
                   7861: 	    my $id=$entries[0];
                   7862: 	    my @idresponses;
                   7863: 	    $id=~s/^[\#0]+//;
                   7864: 	    for (my $i=0;$i<$number;$i++) {
                   7865: 		my $idx=3+$i*6;
                   7866: 		push(@idresponses,$entries[$idx]);
                   7867: 	    }
                   7868: 	    $$responses{$id}=join(',',@idresponses);
                   7869: 	}
1.405     www      7870:     }
                   7871:     return ($errormsg,$number);
                   7872: }
                   7873: 
1.419     www      7874: sub interwrite_eval {
                   7875:     my ($questiontitles,$responses)=@_;
                   7876:     my $number=0;
                   7877:     my $errormsg='';
1.420     www      7878:     my $skipline=1;
                   7879:     my $questionnumber=0;
                   7880:     my %idresponses=();
1.419     www      7881:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7882:         my %components=&Apache::loncommon::record_sep($line);
                   7883:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7884:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7885:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7886:         next if $skipline;
                   7887:         if ($entries[0]!=$questionnumber) {
                   7888:            $questionnumber=$entries[0];
                   7889:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7890:            $number++;
1.419     www      7891:         }
1.420     www      7892:         my $id=$entries[4];
                   7893:         $id=~s/^[\#0]+//;
1.421     www      7894:         $id=~s/^v\d*\://i;
                   7895:         $id=~s/[\-\:]//g;
1.420     www      7896:         $idresponses{$id}[$number]=$entries[6];
                   7897:     }
                   7898:     foreach my $id (keys %idresponses) {
                   7899:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7900:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7901:     }
                   7902:     return ($errormsg,$number);
                   7903: }
                   7904: 
1.414     www      7905: sub assign_clicker_grades {
                   7906:     my ($r)=@_;
                   7907:     my ($symb)=&get_symb($r);
                   7908:     if (!$symb) {return '';}
1.416     www      7909: # See which part we are saving to
                   7910:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7911: # FIXME: This should probably look for the first handgradeable part
                   7912:     my $part=$$partlist[0];
                   7913: # Start screen output
1.414     www      7914:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7915: 
1.414     www      7916:     my $heading=&mt('Assigning grades based on clicker file');
                   7917:     $result.=(<<ENDHEADER);
                   7918: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7919: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7920: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7921: ENDHEADER
                   7922: # Get correct result
                   7923: # FIXME: Possibly need delimiter other than ":"
                   7924:     my @correct=();
1.415     www      7925:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7926:     my $number=$env{'form.number'};
                   7927:     if ($gradingmechanism ne 'attendance') {
1.414     www      7928:        foreach my $key (keys(%env)) {
                   7929:           if ($key=~/^form\.correct\:/) {
                   7930:              my @input=split(/\,/,$env{$key});
                   7931:              for (my $i=0;$i<=$#input;$i++) {
                   7932:                  if (($correct[$i]) && ($input[$i]) &&
                   7933:                      ($correct[$i] ne $input[$i])) {
                   7934:                     $result.='<br /><span class="LC_warning">'.
                   7935:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7936:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7937:                  } elsif ($input[$i]) {
                   7938:                     $correct[$i]=$input[$i];
                   7939:                  }
                   7940:              }
                   7941:           }
                   7942:        }
1.415     www      7943:        for (my $i=0;$i<$number;$i++) {
1.414     www      7944:           if (!$correct[$i]) {
                   7945:              $result.='<br /><span class="LC_error">'.
                   7946:                       &mt('No correct result given for question "[_1]"!',
                   7947:                           $env{'form.question:'.$i}).'</span>';
                   7948:           }
                   7949:        }
                   7950:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7951:     }
                   7952: # Start grading
1.415     www      7953:     my $pcorrect=$env{'form.pcorrect'};
                   7954:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7955:     my $storecount=0;
1.415     www      7956:     foreach my $key (keys(%env)) {
1.420     www      7957:        my $user='';
1.415     www      7958:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7959:           $user=$1;
                   7960:        }
                   7961:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7962:           my $id=$1;
                   7963:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7964:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7965:           } elsif ($env{'form.multi'.$id}) {
                   7966:              $user=$env{'form.multi'.$id};
1.420     www      7967:           }
                   7968:        }
                   7969:        if ($user) { 
1.415     www      7970:           my @answer=split(/\,/,$env{$key});
                   7971:           my $sum=0;
                   7972:           for (my $i=0;$i<$number;$i++) {
                   7973:              if ($answer[$i]) {
                   7974:                 if ($gradingmechanism eq 'attendance') {
                   7975:                    $sum+=$pcorrect;
                   7976:                 } else {
                   7977:                    if ($answer[$i] eq $correct[$i]) {
                   7978:                       $sum+=$pcorrect;
                   7979:                    } else {
                   7980:                       $sum+=$pincorrect;
                   7981:                    }
                   7982:                 }
                   7983:              }
                   7984:           }
1.416     www      7985:           my $ave=$sum/(100*$number);
                   7986: # Store
                   7987:           my ($username,$domain)=split(/\:/,$user);
                   7988:           my %grades=();
                   7989:           $grades{"resource.$part.solved"}='correct_by_override';
                   7990:           $grades{"resource.$part.awarded"}=$ave;
                   7991:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7992:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7993:                                                  $env{'request.course.id'},
                   7994:                                                  $domain,$username);
                   7995:           if ($returncode ne 'ok') {
                   7996:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7997:           } else {
                   7998:              $storecount++;
                   7999:           }
1.415     www      8000:        }
                   8001:     }
                   8002: # We are done
1.416     www      8003:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8004:              '</td></tr></table>'."\n".
1.414     www      8005:              '</td></tr></table><br /><br />'."\n";
                   8006:     return $result.&show_grading_menu_form($symb);
                   8007: }
                   8008: 
1.1       albertel 8009: sub handler {
1.41      ng       8010:     my $request=$_[0];
1.434     albertel 8011:     &reset_caches();
1.257     albertel 8012:     if ($env{'browser.mathml'}) {
1.141     www      8013: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8014:     } else {
1.141     www      8015: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8016:     }
                   8017:     $request->send_http_header;
1.44      ng       8018:     return '' if $request->header_only;
1.41      ng       8019:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8020:     my $symb=&get_symb($request,1);
1.160     albertel 8021:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8022:     my $command=$commands[0];
1.447     foxr     8023: 
1.160     albertel 8024:     if ($#commands > 0) {
                   8025: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8026:     }
1.447     foxr     8027: 
                   8028: 
1.353     albertel 8029:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8030:     if ($symb eq '' && $command eq '') {
1.257     albertel 8031: 	if ($env{'user.adv'}) {
                   8032: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8033: 		($env{'form.codethree'})) {
                   8034: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8035: 		    $env{'form.codethree'};
1.41      ng       8036: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8037: 		    &Apache::lonnet::checkin($token);
                   8038: 		if ($tsymb) {
1.137     albertel 8039: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8040: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8041: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8042: 					  ('grade_username' => $tuname,
                   8043: 					   'grade_domain' => $tudom,
                   8044: 					   'grade_courseid' => $tcrsid,
                   8045: 					   'grade_symb' => $tsymb)));
1.41      ng       8046: 		    } else {
1.45      ng       8047: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8048: 		    }
1.41      ng       8049: 		} else {
1.45      ng       8050: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8051: 		}
1.14      www      8052: 	    } else {
1.41      ng       8053: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8054: 	    }
                   8055: 	}
                   8056:     } else {
1.285     albertel 8057: 	&init_perm();
1.104     albertel 8058: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8059: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8060: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8061: 	    &pickStudentPage($request);
1.103     albertel 8062: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8063: 	    &displayPage($request);
1.104     albertel 8064: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8065: 	    &updateGradeByPage($request);
1.104     albertel 8066: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8067: 	    &processGroup($request);
1.104     albertel 8068: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8069: 	    $request->print(&grading_menu($request));
                   8070: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8071: 	    $request->print(&submit_options($request));
1.104     albertel 8072: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8073: 	    $request->print(&viewgrades($request));
1.104     albertel 8074: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8075: 	    $request->print(&processHandGrade($request));
1.106     albertel 8076: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8077: 	    $request->print(&editgrades($request));
1.106     albertel 8078: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8079: 	    $request->print(&verifyreceipt($request));
1.400     www      8080:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8081:             $request->print(&process_clicker($request));
                   8082:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8083:             $request->print(&process_clicker_file($request));
1.414     www      8084:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8085:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8086: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8087: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8088: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8089: 	    $request->print(&csvupload($request));
1.106     albertel 8090: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8091: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8092: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8093: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8094: 		$request->print(&csvuploadoptions($request));
1.41      ng       8095: 	    } else {
1.257     albertel 8096: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8097: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8098: 		} else {
1.257     albertel 8099: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8100: 		}
                   8101: 		$request->print(&csvuploadmap($request));
                   8102: 	    }
1.246     albertel 8103: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8104: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8105: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8106: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8107:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8108:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8109: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8110: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8111: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8112: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8113:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8114:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8115: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8116:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8117:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8118:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8119: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8120:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8121:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8122: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8123:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8124: 	} elsif ($command) {
1.157     albertel 8125: 	    $request->print("Access Denied ($command)");
1.26      albertel 8126: 	}
1.2       albertel 8127:     }
1.353     albertel 8128:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8129:     &reset_caches();
1.44      ng       8130:     return '';
                   8131: }
                   8132: 
1.1       albertel 8133: 1;
                   8134: 
1.13      albertel 8135: __END__;

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