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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.475   ! albertel    4: # $Id: grades.pm,v 1.474 2007/11/01 00:47:42 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".
1.474     albertel  868: 	'<label><input type="radio" name="lastSub" value="last" /> last submission &amp; parts info </label>'."\n".
1.267     albertel  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.474     albertel  905:     $gradeTable.= &Apache::loncommon::start_data_table().
                    906: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        907:     my $loop = 0;
                    908:     while ($loop < 2) {
1.474     albertel  909: 	$gradeTable.='<th>No.</th><th>Select</th>'.
                    910: 	    '<th>'.&nameUserString('header').'&nbsp;'.'Section/Group</th>';
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.474     albertel  916: 		$gradeTable.='<th>Part: '.$display_part.
                    917: 		    ' Status</h>';
1.110     ng        918: 	    }
1.301     albertel  919: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  920: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        921: 	}
                    922: 	$loop++;
1.126     ng        923: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        924:     }
1.474     albertel  925:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\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.474     albertel  981: 	    if ($ctr%2 ==1) {
                    982: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                    983: 	    }
1.126     ng        984: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  985:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    986:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    987: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    988: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel  989: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng        990: 
1.257     albertel  991: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        992: 		foreach (sort keys(%status)) {
                    993: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  994: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        995: 		}
1.41      ng        996: 	    }
1.126     ng        997: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel  998: 	    if ($ctr%2 ==0) {
                    999: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1000: 	    }
1.41      ng       1001: 	}
                   1002:     }
1.110     ng       1003:     if ($ctr%2 ==1) {
1.126     ng       1004: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1005: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1006: 		&& $submitonly ne 'queued'
                   1007: 		&& $submitonly ne 'all') {
1.110     ng       1008: 		foreach (@$partlist) {
                   1009: 		    $gradeTable.='<td>&nbsp;</td>';
                   1010: 		}
1.301     albertel 1011: 	    } elsif ($submitonly eq 'queued') {
                   1012: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1013: 	    }
1.474     albertel 1014: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1015:     }
                   1016: 
1.474     albertel 1017:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1018: 	'<input type="button" '.
                   1019: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1020: 	'value="Next->" /></form>'."\n";
1.45      ng       1021:     if ($ctr == 0) {
1.96      albertel 1022: 	my $num_students=(scalar(keys(%$fullname)));
                   1023: 	if ($num_students eq 0) {
1.398     albertel 1024: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1025: 	} else {
1.171     albertel 1026: 	    my $submissions='submissions';
                   1027: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1028: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1029: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1030: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1031: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1032: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1033: 	}
1.46      ng       1034:     } elsif ($ctr == 1) {
1.474     albertel 1035: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1036:     }
1.324     albertel 1037:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1038:     $request->print($gradeTable);
1.44      ng       1039:     return '';
1.10      ng       1040: }
                   1041: 
1.44      ng       1042: #---- Called from the listStudents routine
1.249     albertel 1043: 
                   1044: sub check_script {
                   1045:     my ($form, $type)=@_;
                   1046:     my $chkallscript='<script type="text/javascript">
                   1047:     function checkall() {
                   1048:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1049:             ele = document.forms.'.$form.'.elements[i];
                   1050:             if (ele.name == "'.$type.'") {
                   1051:             document.forms.'.$form.'.elements[i].checked=true;
                   1052:                                        }
                   1053:         }
                   1054:     }
                   1055: 
                   1056:     function checksec() {
                   1057:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1058:             ele = document.forms.'.$form.'.elements[i];
                   1059:            string = document.forms.'.$form.'.chksec.value;
                   1060:            if
                   1061:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1062:               document.forms.'.$form.'.elements[i].checked=true;
                   1063:             }
                   1064:         }
                   1065:     }
                   1066: 
                   1067: 
                   1068:     function uncheckall() {
                   1069:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1070:             ele = document.forms.'.$form.'.elements[i];
                   1071:             if (ele.name == "'.$type.'") {
                   1072:             document.forms.'.$form.'.elements[i].checked=false;
                   1073:                                        }
                   1074:         }
                   1075:     }
                   1076: 
                   1077: </script>'."\n";
                   1078:     return $chkallscript;
                   1079: }
                   1080: 
                   1081: sub check_buttons {
                   1082:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1083:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1084:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1085:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1086:     return $buttons;
                   1087: }
                   1088: 
1.44      ng       1089: #     Displays the submissions for one student or a group of students
1.34      ng       1090: sub processGroup {
1.41      ng       1091:     my ($request)  = shift;
                   1092:     my $ctr        = 0;
1.155     albertel 1093:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1094:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1095: 
1.396     banghart 1096:     foreach my $student (@stuchecked) {
                   1097: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1098: 	$env{'form.student'}        = $uname;
                   1099: 	$env{'form.userdom'}        = $udom;
                   1100: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1101: 	&submission($request,$ctr,$total);
                   1102: 	$ctr++;
                   1103:     }
                   1104:     return '';
1.35      ng       1105: }
1.34      ng       1106: 
1.44      ng       1107: #------------------------------------------------------------------------------------
                   1108: #
                   1109: #-------------------------- Next few routines handles grading by student, essentially
                   1110: #                           handles essay response type problem/part
                   1111: #
                   1112: #--- Javascript to handle the submission page functionality ---
                   1113: sub sub_page_js {
                   1114:     my $request = shift;
                   1115:     $request->print(<<SUBJAVASCRIPT);
                   1116: <script type="text/javascript" language="javascript">
1.71      ng       1117:     function updateRadio(formname,id,weight) {
1.125     ng       1118: 	var gradeBox = formname["GD_BOX"+id];
                   1119: 	var radioButton = formname["RADVAL"+id];
                   1120: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1121: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1122: 	gradeBox.value = pts;
                   1123: 	var resetbox = false;
                   1124: 	if (isNaN(pts) || pts < 0) {
                   1125: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1126: 	    for (var i=0; i<radioButton.length; i++) {
                   1127: 		if (radioButton[i].checked) {
                   1128: 		    gradeBox.value = i;
                   1129: 		    resetbox = true;
                   1130: 		}
                   1131: 	    }
                   1132: 	    if (!resetbox) {
                   1133: 		formtextbox.value = "";
                   1134: 	    }
                   1135: 	    return;
1.44      ng       1136: 	}
1.71      ng       1137: 
                   1138: 	if (pts > weight) {
                   1139: 	    var resp = confirm("You entered a value ("+pts+
                   1140: 			       ") greater than the weight for the part. Accept?");
                   1141: 	    if (resp == false) {
1.125     ng       1142: 		gradeBox.value = oldpts;
1.71      ng       1143: 		return;
                   1144: 	    }
1.44      ng       1145: 	}
1.13      albertel 1146: 
1.71      ng       1147: 	for (var i=0; i<radioButton.length; i++) {
                   1148: 	    radioButton[i].checked=false;
                   1149: 	    if (pts == i && pts != "") {
                   1150: 		radioButton[i].checked=true;
                   1151: 	    }
                   1152: 	}
                   1153: 	updateSelect(formname,id);
1.125     ng       1154: 	formname["stores"+id].value = "0";
1.41      ng       1155:     }
1.5       albertel 1156: 
1.72      ng       1157:     function writeBox(formname,id,pts) {
1.125     ng       1158: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1159: 	if (checkSolved(formname,id) == 'update') {
                   1160: 	    gradeBox.value = pts;
                   1161: 	} else {
1.125     ng       1162: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1163: 	    gradeBox.value = oldpts;
1.125     ng       1164: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1165: 	    for (var i=0; i<radioButton.length; i++) {
                   1166: 		radioButton[i].checked=false;
1.72      ng       1167: 		if (i == oldpts) {
1.71      ng       1168: 		    radioButton[i].checked=true;
                   1169: 		}
                   1170: 	    }
1.41      ng       1171: 	}
1.125     ng       1172: 	formname["stores"+id].value = "0";
1.71      ng       1173: 	updateSelect(formname,id);
                   1174: 	return;
1.41      ng       1175:     }
1.44      ng       1176: 
1.71      ng       1177:     function clearRadBox(formname,id) {
                   1178: 	if (checkSolved(formname,id) == 'noupdate') {
                   1179: 	    updateSelect(formname,id);
                   1180: 	    return;
                   1181: 	}
1.125     ng       1182: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1183: 	for (var i=0; i<gradeSelect.length; i++) {
                   1184: 	    if (gradeSelect[i].selected) {
                   1185: 		var selectx=i;
                   1186: 	    }
                   1187: 	}
1.125     ng       1188: 	var stores = formname["stores"+id];
1.71      ng       1189: 	if (selectx == stores.value) { return };
1.125     ng       1190: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1191: 	gradeBox.value = "";
1.125     ng       1192: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1193: 	for (var i=0; i<radioButton.length; i++) {
                   1194: 	    radioButton[i].checked=false;
                   1195: 	}
                   1196: 	stores.value = selectx;
                   1197:     }
1.5       albertel 1198: 
1.71      ng       1199:     function checkSolved(formname,id) {
1.125     ng       1200: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1201: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1202: 	    if (!reply) {return "noupdate";}
1.120     ng       1203: 	    formname.overRideScore.value = 'yes';
1.41      ng       1204: 	}
1.71      ng       1205: 	return "update";
1.13      albertel 1206:     }
1.71      ng       1207: 
                   1208:     function updateSelect(formname,id) {
1.125     ng       1209: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1210: 	return;
1.41      ng       1211:     }
1.33      ng       1212: 
1.121     ng       1213: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1214:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1215: 	formname.gradeOpt.value = val;
1.71      ng       1216: 	if (val == "Save & Next") {
                   1217: 	    for (i=0;i<=total;i++) {
                   1218: 		for (j=0;j<parttot;j++) {
1.125     ng       1219: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1220: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1221: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1222: 			if (points == "") {
1.125     ng       1223: 			    var name = formname["name"+i].value;
1.129     ng       1224: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1225: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1226: 					       ", part "+partid+". Continue?");
1.71      ng       1227: 			    if (resp == false) {
1.125     ng       1228: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1229: 				return false;
                   1230: 			    }
                   1231: 			}
                   1232: 		    }
                   1233: 		    
                   1234: 		}
                   1235: 	    }
                   1236: 	    
                   1237: 	}
1.121     ng       1238: 	if (val == "Grade Student") {
                   1239: 	    formname.showgrading.value = "yes";
                   1240: 	    if (formname.Status.value == "") {
                   1241: 		formname.Status.value = "Active";
                   1242: 	    }
                   1243: 	    formname.studentNo.value = total;
                   1244: 	}
1.120     ng       1245: 	formname.submit();
                   1246:     }
                   1247: 
1.71      ng       1248: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1249:     function checkSubmitPage(formname,total) {
                   1250: 	noscore = new Array(100);
                   1251: 	var ptr = 0;
                   1252: 	for (i=1;i<total;i++) {
1.125     ng       1253: 	    var partid = formname["q_"+i].value;
1.127     ng       1254: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1255: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1256: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1257: 		if (points == "" && status != "correct_by_student") {
                   1258: 		    noscore[ptr] = i;
                   1259: 		    ptr++;
                   1260: 		}
                   1261: 	    }
                   1262: 	}
                   1263: 	if (ptr != 0) {
                   1264: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1265: 	    var prolist = "";
                   1266: 	    if (ptr == 1) {
                   1267: 		prolist = noscore[0];
                   1268: 	    } else {
                   1269: 		var i = 0;
                   1270: 		while (i < ptr-1) {
                   1271: 		    prolist += noscore[i]+", ";
                   1272: 		    i++;
                   1273: 		}
                   1274: 		prolist += "and "+noscore[i];
                   1275: 	    }
                   1276: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1277: 	    if (resp == false) {
                   1278: 		return false;
                   1279: 	    }
                   1280: 	}
1.45      ng       1281: 
1.71      ng       1282: 	formname.submit();
                   1283:     }
                   1284: </script>
                   1285: SUBJAVASCRIPT
                   1286: }
1.45      ng       1287: 
1.71      ng       1288: #--- javascript for essay type problem --
                   1289: sub sub_page_kw_js {
                   1290:     my $request = shift;
1.80      ng       1291:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1292:     &commonJSfunctions($request);
1.350     albertel 1293: 
1.351     albertel 1294:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1295:     <script text="text/javascript">
                   1296:     function checkInput() {
                   1297:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1298:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1299:       var usrctr = document.msgcenter.usrctr.value;
                   1300:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1301:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1302: 
                   1303:       var msgchk = "";
                   1304:       if (document.msgcenter.subchk.checked) {
                   1305:          msgchk = "msgsub,";
                   1306:       }
                   1307:       var includemsg = 0;
                   1308:       for (var i=1; i<=nmsg; i++) {
                   1309:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1310:           var frmmsg = document.msgcenter["msg"+i];
                   1311:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1312:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1313:           showflg.value = "1";
                   1314:           var chkbox = document.msgcenter["msgn"+i];
                   1315:           if (chkbox.checked) {
                   1316:              msgchk += "savemsg"+i+",";
                   1317:              includemsg = 1;
                   1318:           }
                   1319:       }
                   1320:       if (document.msgcenter.newmsgchk.checked) {
                   1321:          msgchk += "newmsg"+usrctr;
                   1322:          includemsg = 1;
                   1323:       }
                   1324:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1325:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1326:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1327:       includemsg.value = msgchk;
                   1328: 
                   1329:       self.close()
                   1330: 
                   1331:     }
                   1332:     </script>
                   1333: INNERJS
                   1334: 
1.351     albertel 1335:     my $inner_js_highlight_central=<<INNERJS;
                   1336:  <script type="text/javascript">
                   1337:     function updateChoice(flag) {
                   1338:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1339:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1340:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1341:       opener.document.SCORE.refresh.value = "on";
                   1342:       if (opener.document.SCORE.keywords.value!=""){
                   1343:          opener.document.SCORE.submit();
                   1344:       }
                   1345:       self.close()
                   1346:     }
                   1347: </script>
                   1348: INNERJS
                   1349: 
                   1350:     my $start_page_msg_central = 
                   1351:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1352: 				       {'js_ready'  => 1,
                   1353: 					'only_body' => 1,
                   1354: 					'bgcolor'   =>'#FFFFFF',});
                   1355:     my $end_page_msg_central = 
                   1356: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1357: 
                   1358: 
                   1359:     my $start_page_highlight_central = 
                   1360:         &Apache::loncommon::start_page('Highlight Central',
                   1361: 				       $inner_js_highlight_central,
1.350     albertel 1362: 				       {'js_ready'  => 1,
                   1363: 					'only_body' => 1,
                   1364: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1365:     my $end_page_highlight_central = 
1.350     albertel 1366: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1367: 
1.219     www      1368:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1369:     $docopen=~s/^document\.//;
1.71      ng       1370:     $request->print(<<SUBJAVASCRIPT);
                   1371: <script type="text/javascript" language="javascript">
1.45      ng       1372: 
1.44      ng       1373: //===================== Show list of keywords ====================
1.122     ng       1374:   function keywords(formname) {
                   1375:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1376:     if (nret==null) return;
1.122     ng       1377:     formname.keywords.value = nret;
1.44      ng       1378: 
1.122     ng       1379:     if (formname.keywords.value != "") {
1.128     ng       1380: 	formname.refresh.value = "on";
1.122     ng       1381: 	formname.submit();
1.44      ng       1382:     }
                   1383:     return;
                   1384:   }
                   1385: 
                   1386: //===================== Script to view submitted by ==================
                   1387:   function viewSubmitter(submitter) {
                   1388:     document.SCORE.refresh.value = "on";
                   1389:     document.SCORE.NCT.value = "1";
                   1390:     document.SCORE.unamedom0.value = submitter;
                   1391:     document.SCORE.submit();
                   1392:     return;
                   1393:   }
                   1394: 
                   1395: //===================== Script to add keyword(s) ==================
                   1396:   function getSel() {
                   1397:     if (document.getSelection) txt = document.getSelection();
                   1398:     else if (document.selection) txt = document.selection.createRange().text;
                   1399:     else return;
                   1400:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1401:     if (cleantxt=="") {
1.46      ng       1402: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1403: 	return;
                   1404:     }
                   1405:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1406:     if (nret==null) return;
1.127     ng       1407:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1408:     if (document.SCORE.keywords.value != "") {
1.127     ng       1409: 	document.SCORE.refresh.value = "on";
1.44      ng       1410: 	document.SCORE.submit();
                   1411:     }
                   1412:     return;
                   1413:   }
                   1414: 
                   1415: //====================== Script for composing message ==============
1.80      ng       1416:    // preload images
                   1417:    img1 = new Image();
                   1418:    img1.src = "$iconpath/mailbkgrd.gif";
                   1419:    img2 = new Image();
                   1420:    img2.src = "$iconpath/mailto.gif";
                   1421: 
1.44      ng       1422:   function msgCenter(msgform,usrctr,fullname) {
                   1423:     var Nmsg  = msgform.savemsgN.value;
                   1424:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1425:     var subject = msgform.msgsub.value;
1.127     ng       1426:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1427:     re = /msgsub/;
                   1428:     var shwsel = "";
                   1429:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1430:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1431:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1432:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1433: 	var testmsg = "savemsg"+i+",";
                   1434: 	re = new RegExp(testmsg,"g");
1.44      ng       1435: 	shwsel = "";
                   1436: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1437: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1438: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1439: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1440: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1441:     }
1.125     ng       1442:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1443:     shwsel = "";
                   1444:     re = /newmsg/;
                   1445:     if (re.test(msgchk)) { shwsel = "checked" }
                   1446:     newMsg(newmsg,shwsel);
                   1447:     msgTail(); 
                   1448:     return;
                   1449:   }
                   1450: 
1.123     ng       1451:   function checkEntities(strx) {
                   1452:     if (strx.length == 0) return strx;
                   1453:     var orgStr = ["&", "<", ">", '"']; 
                   1454:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1455:     var counter = 0;
                   1456:     while (counter < 4) {
                   1457: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1458: 	counter++;
                   1459:     }
                   1460:     return strx;
                   1461:   }
                   1462: 
                   1463:   function strReplace(strx, orgStr, newStr) {
                   1464:     return strx.split(orgStr).join(newStr);
                   1465:   }
                   1466: 
1.44      ng       1467:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1468:     var height = 70*Nmsg+250;
1.44      ng       1469:     var scrollbar = "no";
                   1470:     if (height > 600) {
                   1471: 	height = 600;
                   1472: 	scrollbar = "yes";
                   1473:     }
1.118     ng       1474:     var xpos = (screen.width-600)/2;
                   1475:     xpos = (xpos < 0) ? '0' : xpos;
                   1476:     var ypos = (screen.height-height)/2-30;
                   1477:     ypos = (ypos < 0) ? '0' : ypos;
                   1478: 
1.206     albertel 1479:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1480:     pWin.focus();
                   1481:     pDoc = pWin.document;
1.219     www      1482:     pDoc.$docopen;
1.351     albertel 1483:     pDoc.write('$start_page_msg_central');
1.76      ng       1484: 
                   1485:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1486:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1487:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1488: 
                   1489:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1490:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1491:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1492: }
                   1493:     function displaySubject(msg,shwsel) {
1.76      ng       1494:     pDoc = pWin.document;
                   1495:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1496:     pDoc.write("<td>Subject<\\/td>");
                   1497:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1498:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1499: }
                   1500: 
1.72      ng       1501:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1502:     pDoc = pWin.document;
                   1503:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1504:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1505:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1506:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1507: }
                   1508: 
                   1509:   function newMsg(newmsg,shwsel) {
1.76      ng       1510:     pDoc = pWin.document;
                   1511:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1512:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1513:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1514:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1515: }
                   1516: 
                   1517:   function msgTail() {
1.76      ng       1518:     pDoc = pWin.document;
1.465     albertel 1519:     pDoc.write("<\\/table>");
                   1520:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1521:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1522:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1523:     pDoc.write("<\\/form>");
1.351     albertel 1524:     pDoc.write('$end_page_msg_central');
1.128     ng       1525:     pDoc.close();
1.44      ng       1526: }
                   1527: 
                   1528: //====================== Script for keyword highlight options ==============
                   1529:   function kwhighlight() {
                   1530:     var kwclr    = document.SCORE.kwclr.value;
                   1531:     var kwsize   = document.SCORE.kwsize.value;
                   1532:     var kwstyle  = document.SCORE.kwstyle.value;
                   1533:     var redsel = "";
                   1534:     var grnsel = "";
                   1535:     var blusel = "";
                   1536:     if (kwclr=="red")   {var redsel="checked"};
                   1537:     if (kwclr=="green") {var grnsel="checked"};
                   1538:     if (kwclr=="blue")  {var blusel="checked"};
                   1539:     var sznsel = "";
                   1540:     var sz1sel = "";
                   1541:     var sz2sel = "";
                   1542:     if (kwsize=="0")  {var sznsel="checked"};
                   1543:     if (kwsize=="+1") {var sz1sel="checked"};
                   1544:     if (kwsize=="+2") {var sz2sel="checked"};
                   1545:     var synsel = "";
                   1546:     var syisel = "";
                   1547:     var sybsel = "";
                   1548:     if (kwstyle=="")    {var synsel="checked"};
                   1549:     if (kwstyle=="<i>") {var syisel="checked"};
                   1550:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1551:     highlightCentral();
                   1552:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1553:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1554:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1555:     highlightend();
                   1556:     return;
                   1557:   }
                   1558: 
                   1559:   function highlightCentral() {
1.76      ng       1560: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1561:     var xpos = (screen.width-400)/2;
                   1562:     xpos = (xpos < 0) ? '0' : xpos;
                   1563:     var ypos = (screen.height-330)/2-30;
                   1564:     ypos = (ypos < 0) ? '0' : ypos;
                   1565: 
1.206     albertel 1566:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1567:     hwdWin.focus();
                   1568:     var hDoc = hwdWin.document;
1.219     www      1569:     hDoc.$docopen;
1.351     albertel 1570:     hDoc.write('$start_page_highlight_central');
1.76      ng       1571:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1572:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1573: 
                   1574:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1575:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1576:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1577:   }
                   1578: 
                   1579:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1580:     var hDoc = hwdWin.document;
                   1581:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1582:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1583:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1584:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1585:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1586:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1587:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1588:     hDoc.write("<\\/tr>");
1.44      ng       1589:   }
                   1590: 
                   1591:   function highlightend() { 
1.76      ng       1592:     var hDoc = hwdWin.document;
1.465     albertel 1593:     hDoc.write("<\\/table>");
                   1594:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1595:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1596:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1597:     hDoc.write("<\\/form>");
1.351     albertel 1598:     hDoc.write('$end_page_highlight_central');
1.128     ng       1599:     hDoc.close();
1.44      ng       1600:   }
                   1601: 
                   1602: </script>
                   1603: SUBJAVASCRIPT
                   1604: }
                   1605: 
1.349     albertel 1606: sub get_increment {
1.348     bowersj2 1607:     my $increment = $env{'form.increment'};
                   1608:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1609:         $increment != .1) {
                   1610:         $increment = 1;
                   1611:     }
                   1612:     return $increment;
                   1613: }
                   1614: 
1.71      ng       1615: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1616: sub gradeBox {
1.322     albertel 1617:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1618:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1619: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1620: 	'/check.gif" height="16" border="0" />';
                   1621:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1622:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1623:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1624:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1625:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1626: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1627:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1628:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1629:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1630: 				       [$partid]);
                   1631:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1632:     if ($last_resets{$partid}) {
                   1633:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1634:     }
1.71      ng       1635:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1636: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1637:     my $ctr = 0;
1.348     bowersj2 1638:     my $thisweight = 0;
1.349     albertel 1639:     my $increment = &get_increment();
1.71      ng       1640:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1641:     while ($thisweight<=$wgt) {
1.381     albertel 1642: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1643: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1644: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1645: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1646: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1647:         $thisweight += $increment;
1.71      ng       1648: 	$ctr++;
                   1649:     }
                   1650:     $result.='</tr></table>';
                   1651:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1652:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1653: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1654: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1655: 	$wgt.')" /></td>'."\n";
                   1656:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1657: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1658: 	' </td><td>'."\n";
                   1659:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1660: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1661:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1662: 	$result.='<option></option>'.
1.401     albertel 1663: 	    '<option selected="selected">excused</option>';
1.71      ng       1664:     } else {
1.401     albertel 1665: 	$result.='<option selected="selected"></option>'.
1.125     ng       1666: 	    '<option>excused</option>';
1.71      ng       1667:     }
1.125     ng       1668:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1669:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1670:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1671: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1672: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1673: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1674:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1675:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1676:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1677:         $aggtries.'" />'."\n";
1.71      ng       1678:     $result.='</td></tr></table>'."\n";
1.323     banghart 1679:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1680:     return $result;
                   1681: }
1.322     albertel 1682: 
                   1683: sub handback_box {
1.323     banghart 1684:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1685:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1686:     my (@respids);
1.375     albertel 1687:      my @part_response_id = &flatten_responseType($responseType);
                   1688:     foreach my $part_response_id (@part_response_id) {
                   1689:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1690:         if ($part eq $partid) {
1.375     albertel 1691:             push(@respids,$resp);
1.323     banghart 1692:         }
                   1693:     }
1.318     banghart 1694:     my $result;
1.323     banghart 1695:     foreach my $respid (@respids) {
1.322     albertel 1696: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1697: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1698: 	next if (!@$files);
                   1699: 	my $file_counter = 1;
1.313     banghart 1700: 	foreach my $file (@$files) {
1.368     banghart 1701: 	    if ($file =~ /\/portfolio\//) {
                   1702:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1703:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1704:     	        $file_disp = "$name.$ext";
                   1705:     	        $file = $file_path.$file_disp;
                   1706:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1707:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1708:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1709:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.466     albertel 1710:     	        $result.='(File will be uploaded when you click on Save &amp; Next below.)<br />';
1.368     banghart 1711:     	        $file_counter++;
                   1712: 	    }
1.322     albertel 1713: 	}
1.313     banghart 1714:     }
1.318     banghart 1715:     return $result;    
1.71      ng       1716: }
1.44      ng       1717: 
1.58      albertel 1718: sub show_problem {
1.382     albertel 1719:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1720:     my $rendered;
1.382     albertel 1721:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1722:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1723:     if ($mode eq 'both' or $mode eq 'text') {
                   1724: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1725: 						       $env{'request.course.id'},
                   1726: 						       undef,\%form);
1.144     albertel 1727:     }
1.58      albertel 1728:     if ($removeform) {
                   1729: 	$rendered=~s|<form(.*?)>||g;
                   1730: 	$rendered=~s|</form>||g;
1.374     albertel 1731: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1732:     }
1.144     albertel 1733:     my $companswer;
                   1734:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1735: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1736: 	$companswer=
                   1737: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1738: 						    $env{'request.course.id'},
                   1739: 						    %form);
1.144     albertel 1740:     }
1.58      albertel 1741:     if ($removeform) {
                   1742: 	$companswer=~s|<form(.*?)>||g;
                   1743: 	$companswer=~s|</form>||g;
1.144     albertel 1744: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1745:     }
1.468     albertel 1746:     $rendered=
                   1747: 	'<div class="LC_grade_show_problem_header">'.
                   1748: 	&mt('View of the problem').
                   1749: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1750: 	$rendered.
                   1751: 	'</div>';
                   1752:     $companswer=
                   1753: 	'<div class="LC_grade_show_problem_header">'.
                   1754: 	&mt('Correct answer').
                   1755: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1756: 	$companswer.
                   1757: 	'</div>';
                   1758:     my $result;
1.144     albertel 1759:     if ($mode eq 'both') {
1.468     albertel 1760: 	$result=$rendered.$companswer;
1.144     albertel 1761:     } elsif ($mode eq 'text') {
1.468     albertel 1762: 	$result=$rendered;
1.144     albertel 1763:     } elsif ($mode eq 'answer') {
1.468     albertel 1764: 	$result=$companswer;
1.144     albertel 1765:     }
1.468     albertel 1766:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1767:     return $result;
1.58      albertel 1768: }
1.397     albertel 1769: 
1.396     banghart 1770: sub files_exist {
                   1771:     my ($r, $symb) = @_;
                   1772:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1773: 
1.396     banghart 1774:     foreach my $student (@students) {
                   1775:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1776:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1777: 					      $udom,$uname);
1.396     banghart 1778:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1779:         foreach my $submission (@$string) {
                   1780:             my ($partid,$respid) =
                   1781: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1782:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1783: 					   \%record);
                   1784:             return 1 if (@$files);
1.396     banghart 1785:         }
                   1786:     }
1.397     albertel 1787:     return 0;
1.396     banghart 1788: }
1.397     albertel 1789: 
1.394     banghart 1790: sub download_all_link {
                   1791:     my ($r,$symb) = @_;
1.395     albertel 1792:     my $all_students = 
                   1793: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1794: 
                   1795:     my $parts =
                   1796: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1797: 
1.394     banghart 1798:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1799:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1800:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1801:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1802:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1803: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1804:     return
                   1805: }
1.395     albertel 1806: 
1.432     banghart 1807: sub build_section_inputs {
                   1808:     my $section_inputs;
                   1809:     if ($env{'form.section'} eq '') {
                   1810:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1811:     } else {
                   1812:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1813:         foreach my $section (@sections) {
1.432     banghart 1814:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1815:         }
                   1816:     }
                   1817:     return $section_inputs;
                   1818: }
                   1819: 
1.44      ng       1820: # --------------------------- show submissions of a student, option to grade 
                   1821: sub submission {
                   1822:     my ($request,$counter,$total) = @_;
1.257     albertel 1823:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1824:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1825:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1826:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1827:     my $symb = &get_symb($request); 
                   1828:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1829: 
                   1830:     if (!&canview($usec)) {
1.398     albertel 1831: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1832: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1833: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1834: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1835: 	return;
                   1836:     }
                   1837: 
1.257     albertel 1838:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1839:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1840:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1841:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1842:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1843: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1844: 	'/check.gif" height="16" border="0" />';
1.41      ng       1845: 
1.426     albertel 1846:     my %old_essays;
1.41      ng       1847:     # header info
                   1848:     if ($counter == 0) {
                   1849: 	&sub_page_js($request);
1.257     albertel 1850: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1851: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1852: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1853: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1854: 	    &download_all_link($request, $symb);
                   1855: 	}
1.398     albertel 1856: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1857: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1858: 
1.44      ng       1859: 	# option to display problem, only once else it cause problems 
                   1860:         # with the form later since the problem has a form.
1.257     albertel 1861: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1862: 	    my $mode;
1.257     albertel 1863: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1864: 		$mode='both';
1.257     albertel 1865: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1866: 		$mode='text';
1.257     albertel 1867: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1868: 		$mode='answer';
                   1869: 	    }
1.329     albertel 1870: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1871: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1872: 	}
1.441     www      1873: 
1.44      ng       1874: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1875:         # if this subroutine has been called once.
1.41      ng       1876: 	my %keyhash = ();
1.257     albertel 1877: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1878: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1879: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1880: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1881: 
1.257     albertel 1882: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1883: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1884: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1885: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1886: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1887: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1888: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1889: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1890: 	}
1.257     albertel 1891: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1892: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1893: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1894: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1895: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1896: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1897: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1898: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1899: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1900: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1901: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1902: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1903: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1904: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1905: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1906: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1907: 			&build_section_inputs().
1.326     albertel 1908: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1909: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1910: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1911: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1912: 	if ($env{'form.handgrade'} eq 'yes') {
                   1913: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1914: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1915: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1916: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1917: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1918: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1919: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1920: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1921: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1922: 	    }
1.123     ng       1923: 	}
1.41      ng       1924: 	
                   1925: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1926: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1927: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1928: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1929: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1930: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1931: 		'" />'."\n".
                   1932: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1933: 	    $cts++;
                   1934: 	}
                   1935: 	$request->print($prnmsg);
1.32      ng       1936: 
1.257     albertel 1937: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1938: #
                   1939: # Print out the keyword options line
                   1940: #
1.41      ng       1941: 	    $request->print(<<KEYWORDS);
1.38      ng       1942: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1943: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1944: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1945:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1946: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1947: KEYWORDS
1.88      www      1948: #
                   1949: # Load the other essays for similarity check
                   1950: #
1.324     albertel 1951:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1952: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1953: 	    $apath=&escape($apath);
1.88      www      1954: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1955: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1956:         }
                   1957:     }
1.44      ng       1958: 
1.441     www      1959: # This is where output for one specific student would start
1.468     albertel 1960:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      1961:     $request->print("\n\n".
1.468     albertel 1962:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   1963: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   1964: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      1965: 
1.257     albertel 1966:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1967: 	my $mode;
1.257     albertel 1968: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1969: 	    $mode='both';
1.257     albertel 1970: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1971: 	    $mode='text';
1.257     albertel 1972: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1973: 	    $mode='answer';
                   1974: 	}
1.329     albertel 1975: 	&Apache::lonxml::clear_problem_counter();
1.475   ! albertel 1976: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 1977:     }
1.144     albertel 1978: 
1.257     albertel 1979:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1980:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1981: 
1.44      ng       1982:     # Display student info
1.41      ng       1983:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 1984:     my $result='<div class="LC_grade_submissions">';
                   1985:     
                   1986:     $result.='<div class="LC_grade_submissions_header">';
                   1987:     $result.= &mt('Submissions');
1.45      ng       1988:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1989: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 1990:     if ($env{'form.handgrade'} eq 'no') {
                   1991: 	$result.='<span class="LC_grade_check_note">'.
                   1992: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   1993: 
                   1994:     }
                   1995: 
                   1996: 
1.41      ng       1997: 
1.118     ng       1998:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 1999:     my $fullname;
                   2000:     my $col_fullnames = [];
1.257     albertel 2001:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2002: 	(my $sub_result,$fullname,$col_fullnames)=
                   2003: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2004: 				 $counter);
                   2005: 	$result.=$sub_result;
1.41      ng       2006:     }
1.44      ng       2007:     $request->print($result."\n");
1.468     albertel 2008:     $request->print('</div>'."\n");
1.44      ng       2009:     # print student answer/submission
                   2010:     # Options are (1) Handgaded submission only
                   2011:     #             (2) Last submission, includes submission that is not handgraded 
                   2012:     #                  (for multi-response type part)
                   2013:     #             (3) Last submission plus the parts info
                   2014:     #             (4) The whole record for this student
1.257     albertel 2015:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2016: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2017: 	
                   2018: 	my $lastsubonly;
                   2019: 
1.151     albertel 2020: 	if ($$timestamp eq '') {
1.468     albertel 2021: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2022: 	} else {
1.468     albertel 2023: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2024: 
1.151     albertel 2025: 	    my %seenparts;
1.375     albertel 2026: 	    my @part_response_id = &flatten_responseType($responseType);
                   2027: 	    foreach my $part (@part_response_id) {
1.393     albertel 2028: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2029: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2030: 
1.375     albertel 2031: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2032: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2033: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2034: 		    if (exists($seenparts{$partid})) { next; }
                   2035: 		    $seenparts{$partid}=1;
1.207     albertel 2036: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2037: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2038: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2039: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2040: 			'\');" target="_self">'.
1.257     albertel 2041: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2042: 		    $request->print($submitby);
                   2043: 		    next;
                   2044: 		}
                   2045: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2046: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2047: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2048: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2049: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2050: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2051: 		    next;
                   2052: 		}
1.468     albertel 2053: 		foreach my $submission (@$string) {
                   2054: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2055: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2056: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2057: 		    # Similarity check
                   2058: 		    my $similar='';
1.257     albertel 2059: 		    if($env{'form.checkPlag'}){
1.151     albertel 2060: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2061: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2062: 			if ($osim) {
                   2063: 			    $osim=int($osim*100.0);
1.426     albertel 2064: 			    my %old_course_desc = 
                   2065: 				&Apache::lonnet::coursedescription($ocrsid,
                   2066: 								   {'one_time' => 1});
                   2067: 
                   2068: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2069: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2070: 				    $osim,
                   2071: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2072: 				    $oname,$odom,
1.426     albertel 2073: 				    $old_course_desc{'description'},
1.427     albertel 2074: 				    $old_course_desc{'num'},
1.426     albertel 2075: 				    $old_course_desc{'domain'}).
1.398     albertel 2076: 				'</span></h3><blockquote><i>'.
1.151     albertel 2077: 				&keywords_highlight($oessay).
                   2078: 				'</i></blockquote><hr />';
                   2079: 			}
1.150     albertel 2080: 		    }
1.151     albertel 2081: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2082: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2083: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2084: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2085: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2086: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2087: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2088: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2089: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2090: 			if (@$files) {
1.468     albertel 2091: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2092: 			    my $file_counter = 0;
1.313     banghart 2093: 			    foreach my $file (@$files) {
1.468     albertel 2094: 			        $file_counter++;
1.232     albertel 2095: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2096: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2097: 			    }
1.236     albertel 2098: 			    $lastsubonly.='<br />';
1.41      ng       2099: 			}
1.468     albertel 2100: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2101: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2102: 					 $respid,\%record,$order);
                   2103: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2104: 			$lastsubonly.='</div>';
1.41      ng       2105: 		    }
                   2106: 		}
                   2107: 	    }
1.468     albertel 2108: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2109: 	}
                   2110: 	$request->print($lastsubonly);
1.468     albertel 2111:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2112: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2113: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2114:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2115: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2116: 								 $env{'request.course.id'},
1.44      ng       2117: 								 $last,'.submission',
                   2118: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2119:     }
1.120     ng       2120: 
1.121     ng       2121:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2122: 	.$udom.'" />'."\n");
1.44      ng       2123:     # return if view submission with no grading option
1.257     albertel 2124:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2125: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2126: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2127: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2128: 	$toGrade.='</div>'."\n";
1.257     albertel 2129: 	if (($env{'form.command'} eq 'submission') || 
                   2130: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2131: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2132: 	}
1.180     albertel 2133: 	$request->print($toGrade);
1.41      ng       2134: 	return;
1.180     albertel 2135:     } else {
1.468     albertel 2136: 	$request->print('</div>'."\n");
1.41      ng       2137:     }
1.33      ng       2138: 
1.121     ng       2139:     # essay grading message center
1.257     albertel 2140:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2141: 	my $result='<div class="LC_grade_message_center">';
                   2142:     
                   2143: 	$result.='<div class="LC_grade_message_center_header">'.
                   2144: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2145: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2146: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2147: 	if (scalar(@$col_fullnames) > 0) {
                   2148: 	    my $lastone = pop(@$col_fullnames);
                   2149: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2150: 	}
                   2151: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2152: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2153: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2154: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2155: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2156: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2157: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2158: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2159: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2160: 	    '<br />&nbsp;('.
1.468     albertel 2161: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2162: 	$result.='</div></div>';
1.121     ng       2163: 	$request->print($result);
1.118     ng       2164:     }
1.41      ng       2165: 
                   2166:     my %seen = ();
                   2167:     my @partlist;
1.129     ng       2168:     my @gradePartRespid;
1.375     albertel 2169:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2170:     $request->print('<div class="LC_grade_assign">'.
                   2171: 		    
                   2172: 		    '<div class="LC_grade_assign_header">'.
                   2173: 		    &mt('Assign Grades').'</div>'.
                   2174: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2175:     foreach my $part_response_id (@part_response_id) {
                   2176:     	my ($partid,$respid) = @{ $part_response_id };
                   2177: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2178: 	next if ($seen{$partid} > 0);
1.41      ng       2179: 	$seen{$partid}++;
1.393     albertel 2180: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2181: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2182: 	push @partlist,$partid;
1.129     ng       2183: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2184: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2185:     }
1.468     albertel 2186:     $request->print('</div></div>');
                   2187: 
                   2188:     $request->print('<div class="LC_grade_info_links">');
                   2189:     if ($perm{'vgr'}) {
                   2190: 	$request->print(
                   2191: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2192: 						   $uname,$udom,'check'));
                   2193:     }
                   2194:     if ($perm{'opa'}) {
                   2195: 	$request->print(
                   2196: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2197: 					 $uname,$udom,$symb,'check'));
                   2198:     }
                   2199:     $request->print('</div>');
                   2200: 
1.45      ng       2201:     $result='<input type="hidden" name="partlist'.$counter.
                   2202: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2203:     $result.='<input type="hidden" name="gradePartRespid'.
                   2204: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2205:     my $ctr = 0;
                   2206:     while ($ctr < scalar(@partlist)) {
                   2207: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2208: 	    $partlist[$ctr].'" />'."\n";
                   2209: 	$ctr++;
                   2210:     }
1.468     albertel 2211:     $request->print($result.''."\n");
1.41      ng       2212: 
1.441     www      2213: # Done with printing info for one student
                   2214: 
1.468     albertel 2215:     $request->print('</div>');#LC_grade_show_user_body
                   2216:     $request->print('</div>');#LC_grade_show_user
1.441     www      2217: 
                   2218: 
1.41      ng       2219:     # print end of form
                   2220:     if ($counter == $total) {
1.297     www      2221: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2222: 	$endform.='<input type="button" value="Save & Next" '.
                   2223: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2224: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2225: 	my $ntstu ='<select name="NTSTU">'.
                   2226: 	    '<option>1</option><option>2</option>'.
                   2227: 	    '<option>3</option><option>5</option>'.
                   2228: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2229: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2230: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2231: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2232: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2233: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2234: 	    '<input type="button" value="Next" '.
1.417     albertel 2235: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2236: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2237:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2238:             "' name='increment' />";
1.45      ng       2239: 	$endform.='</td><tr></table></form>';
1.324     albertel 2240: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2241: 	$request->print($endform);
                   2242:     }
                   2243:     return '';
1.38      ng       2244: }
                   2245: 
1.464     albertel 2246: sub check_collaborators {
                   2247:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2248:     my ($result,@col_fullnames);
                   2249:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2250:     foreach my $part (keys(%$handgrade)) {
                   2251: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2252: 					'.maxcollaborators',
                   2253: 					$symb,$udom,$uname);
                   2254: 	next if ($ncol <= 0);
                   2255: 	$part =~ s/\_/\./g;
                   2256: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2257: 	my (@good_collaborators, @bad_collaborators);
                   2258: 	foreach my $possible_collaborator
                   2259: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2260: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2261: 	    next if ($possible_collaborator eq '');
                   2262: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2263: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2264: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2265: 	    # Doing this grep allows 'fuzzy' specification
                   2266: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2267: 			       keys(%$classlist));
                   2268: 	    if (! scalar(@matches)) {
                   2269: 		push(@bad_collaborators, $possible_collaborator);
                   2270: 	    } else {
                   2271: 		push(@good_collaborators, @matches);
                   2272: 	    }
                   2273: 	}
                   2274: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2275: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2276: 	    foreach my $name (@good_collaborators) {
                   2277: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2278: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2279: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2280: 	    }
                   2281: 	    $result.='<br />'."\n";
1.466     albertel 2282: 	    my ($part)=split(/\./,$part);
1.464     albertel 2283: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2284: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2285: 		"\n";
                   2286: 	}
                   2287: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2288: 	    $result.='<div class="LC_warning">';
1.464     albertel 2289: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2290: 	    $result .= '</div>';
                   2291: 	}         
                   2292: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2293: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2294: 	    $result .= &mt('This student has submitted too many '.
                   2295: 		'collaborators.  Maximum is [_1].',$ncol);
                   2296: 	    $result .= '</div>';
                   2297: 	}
                   2298:     }
                   2299:     return ($result,$fullname,\@col_fullnames);
                   2300: }
                   2301: 
1.44      ng       2302: #--- Retrieve the last submission for all the parts
1.38      ng       2303: sub get_last_submission {
1.119     ng       2304:     my ($returnhash)=@_;
1.46      ng       2305:     my (@string,$timestamp);
1.119     ng       2306:     if ($$returnhash{'version'}) {
1.46      ng       2307: 	my %lasthash=();
                   2308: 	my ($version);
1.119     ng       2309: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2310: 	    foreach my $key (sort(split(/\:/,
                   2311: 					$$returnhash{$version.':keys'}))) {
                   2312: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2313: 		$timestamp = 
                   2314: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2315: 	    }
                   2316: 	}
1.397     albertel 2317: 	foreach my $key (keys(%lasthash)) {
                   2318: 	    next if ($key !~ /\.submission$/);
                   2319: 
                   2320: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2321: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2322: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2323: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2324: 	}
                   2325:     }
1.397     albertel 2326:     if (!@string) {
                   2327: 	$string[0] =
1.398     albertel 2328: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2329:     }
                   2330:     return (\@string,\$timestamp);
1.38      ng       2331: }
1.35      ng       2332: 
1.44      ng       2333: #--- High light keywords, with style choosen by user.
1.38      ng       2334: sub keywords_highlight {
1.44      ng       2335:     my $string    = shift;
1.257     albertel 2336:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2337:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2338:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2339:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2340:     foreach my $keyword (@keylist) {
                   2341: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2342:     }
                   2343:     return $string;
1.38      ng       2344: }
1.36      ng       2345: 
1.44      ng       2346: #--- Called from submission routine
1.38      ng       2347: sub processHandGrade {
1.41      ng       2348:     my ($request) = shift;
1.324     albertel 2349:     my $symb   = &get_symb($request);
                   2350:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2351:     my $button = $env{'form.gradeOpt'};
                   2352:     my $ngrade = $env{'form.NCT'};
                   2353:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2354:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2355:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2356: 
1.44      ng       2357:     if ($button eq 'Save & Next') {
                   2358: 	my $ctr = 0;
                   2359: 	while ($ctr < $ngrade) {
1.257     albertel 2360: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2361: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2362: 	    if ($errorflag eq 'no_score') {
                   2363: 		$ctr++;
                   2364: 		next;
                   2365: 	    }
1.104     albertel 2366: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2367: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2368: 		$ctr++;
                   2369: 		next;
                   2370: 	    }
1.257     albertel 2371: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2372: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2373: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2374:             my ($feedurl,$showsymb) =
                   2375: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2376: 	    my $messagetail;
1.62      albertel 2377: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2378: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2379: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2380: 		$subject.=' ['.$restitle.']';
1.44      ng       2381: 		my (@msgnum) = split(/,/,$includemsg);
                   2382: 		foreach (@msgnum) {
1.257     albertel 2383: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2384: 		}
1.80      ng       2385: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2386: 		if ($env{'form.withgrades'.$ctr}) {
                   2387: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2388: 		    $messagetail = " for <a href=\"".
1.418     albertel 2389: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2390: 		}
                   2391: 		$msgstatus = 
                   2392:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2393: 						     $message.$messagetail,
1.418     albertel 2394:                                                      undef,$feedurl,undef,
1.386     raeburn  2395:                                                      undef,undef,$showsymb,
                   2396:                                                      $restitle);
                   2397: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2398: 				$msgstatus);
1.44      ng       2399: 	    }
1.257     albertel 2400: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2401: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2402: 		foreach my $collabstr (@collabstrs) {
                   2403: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2404: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2405: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2406: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2407: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2408: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2409: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2410: 			    next;
1.418     albertel 2411: 			} elsif ($message ne '') {
                   2412: 			    my ($baseurl,$showsymb) = 
                   2413: 				&get_feedurl_and_symb($symb,$collaborator,
                   2414: 						      $udom);
                   2415: 			    if ($env{'form.withgrades'.$ctr}) {
                   2416: 				$messagetail = " for <a href=\"".
1.386     raeburn  2417:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2418: 			    }
1.418     albertel 2419: 			    $msgstatus = 
                   2420: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2421: 			}
1.44      ng       2422: 		    }
                   2423: 		}
                   2424: 	    }
                   2425: 	    $ctr++;
                   2426: 	}
                   2427:     }
                   2428: 
1.257     albertel 2429:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2430: 	# Keywords sorted in alphabatical order
1.257     albertel 2431: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2432: 	my %keyhash = ();
1.257     albertel 2433: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2434: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2435: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2436: 	$env{'form.keywords'} = join(' ',@keywords);
                   2437: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2438: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2439: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2440: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2441: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2442: 
                   2443: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2444: 	# New messages are saved in env for the next student.
1.119     ng       2445: 	# All messages are saved in nohist_handgrade.db
                   2446: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2447: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2448: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2449: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2450: 		$idx++;
                   2451: 	    }
                   2452: 	    $ctr++;
1.41      ng       2453: 	}
1.119     ng       2454: 	$ctr = 0;
                   2455: 	while ($ctr < $ngrade) {
1.257     albertel 2456: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2457: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2458: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2459: 		$idx++;
                   2460: 	    }
                   2461: 	    $ctr++;
1.41      ng       2462: 	}
1.257     albertel 2463: 	$env{'form.savemsgN'} = --$idx;
                   2464: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2465: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2466: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2467:     }
1.44      ng       2468:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2469:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2470:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2471: 	my ($ctr,$total) = (0,0);
                   2472: 	while ($ctr < $ngrade) {
1.257     albertel 2473: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2474: 	    $ctr++;
                   2475: 	}
1.257     albertel 2476: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2477: 	$ctr = 0;
                   2478: 	while ($ctr < $total) {
1.257     albertel 2479: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2480: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2481: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2482: 	    &submission($request,$ctr,$total-1);
1.41      ng       2483: 	    $ctr++;
                   2484: 	}
                   2485: 	return '';
                   2486:     }
1.36      ng       2487: 
1.121     ng       2488: # Go directly to grade student - from submission or link from chart page
1.120     ng       2489:     if ($button eq 'Grade Student') {
1.324     albertel 2490: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2491: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2492: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2493: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2494: 	&submission($request,0,0);
                   2495: 	return '';
                   2496:     }
                   2497: 
1.44      ng       2498:     # Get the next/previous one or group of students
1.257     albertel 2499:     my $firststu = $env{'form.unamedom0'};
                   2500:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2501:     my $ctr = 2;
1.41      ng       2502:     while ($laststu eq '') {
1.257     albertel 2503: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2504: 	$ctr++;
                   2505: 	$laststu = $firststu if ($ctr > $ngrade);
                   2506:     }
1.44      ng       2507: 
1.41      ng       2508:     my (@parsedlist,@nextlist);
                   2509:     my ($nextflg) = 0;
1.294     albertel 2510:     foreach (sort 
                   2511: 	     {
                   2512: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2513: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2514: 		 }
                   2515: 		 return $a cmp $b;
                   2516: 	     } (keys(%$fullname))) {
1.41      ng       2517: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2518: 	    push @parsedlist,$_;
                   2519: 	}
                   2520: 	$nextflg = 1 if ($_ eq $laststu);
                   2521: 	if ($button eq 'Previous') {
                   2522: 	    last if ($_ eq $firststu);
                   2523: 	    push @parsedlist,$_;
                   2524: 	}
                   2525:     }
                   2526:     $ctr = 0;
                   2527:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2528:     my ($partlist) = &response_type($symb);
1.41      ng       2529:     foreach my $student (@parsedlist) {
1.257     albertel 2530: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2531: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2532: 	
                   2533: 	if ($submitonly eq 'queued') {
                   2534: 	    my %queue_status = 
                   2535: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2536: 							$udom,$uname);
                   2537: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2538: 	}
                   2539: 
1.156     albertel 2540: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2541: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2542: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2543: 	    my $submitted = 0;
1.248     albertel 2544: 	    my $ungraded = 0;
                   2545: 	    my $incorrect = 0;
1.145     albertel 2546: 	    foreach (keys(%status)) {
                   2547: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2548: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2549: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2550: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2551: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2552: 		    $submitted = 0;
                   2553: 		}
1.41      ng       2554: 	    }
1.156     albertel 2555: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2556: 				     $submitonly eq 'incorrect' ||
                   2557: 				     $submitonly eq 'graded'));
1.248     albertel 2558: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2559: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2560: 	}
                   2561: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2562: 	last if ($ctr == $ntstu);
1.41      ng       2563: 	$ctr++;
                   2564:     }
1.36      ng       2565: 
1.41      ng       2566:     $ctr = 0;
                   2567:     my $total = scalar(@nextlist)-1;
1.39      ng       2568: 
1.41      ng       2569:     foreach (sort @nextlist) {
                   2570: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2571: 	$env{'form.student'}  = $uname;
                   2572: 	$env{'form.userdom'}  = $udom;
                   2573: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2574: 	&submission($request,$ctr,$total);
                   2575: 	$ctr++;
                   2576:     }
                   2577:     if ($total < 0) {
1.398     albertel 2578: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2579: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2580: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2581: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2582: 	$request->print($the_end);
                   2583:     }
                   2584:     return '';
1.38      ng       2585: }
1.36      ng       2586: 
1.44      ng       2587: #---- Save the score and award for each student, if changed
1.38      ng       2588: sub saveHandGrade {
1.324     albertel 2589:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2590:     my @version_parts;
1.104     albertel 2591:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2592: 					   $env{'request.course.id'});
1.104     albertel 2593:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2594:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2595:     my @parts_graded;
1.77      ng       2596:     my %newrecord  = ();
                   2597:     my ($pts,$wgt) = ('','');
1.269     raeburn  2598:     my %aggregate = ();
                   2599:     my $aggregateflag = 0;
1.301     albertel 2600:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2601:     foreach my $new_part (@parts) {
1.337     banghart 2602: 	#collaborator ($submi may vary for different parts
1.259     banghart 2603: 	if ($submitter && $new_part ne $part) { next; }
                   2604: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2605: 	if ($dropMenu eq 'excused') {
1.259     banghart 2606: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2607: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2608: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2609: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2610: 		}
1.364     banghart 2611: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2612: 	    }
1.125     ng       2613: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2614: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2615: 	    foreach my $key (keys (%record)) {
1.259     banghart 2616: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2617: 	    }
1.259     banghart 2618: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2619: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2620:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2621: 
                   2622:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2623: 					       [$new_part]);
                   2624:             my $aggtries =$totaltries;
1.269     raeburn  2625:             if ($last_resets{$new_part}) {
1.270     albertel 2626:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2627: 					   $new_part);
1.269     raeburn  2628:             }
1.270     albertel 2629: 
                   2630:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2631:             if ($aggtries > 0) {
1.327     albertel 2632:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2633:                 $aggregateflag = 1;
                   2634:             }
1.125     ng       2635: 	} elsif ($dropMenu eq '') {
1.259     banghart 2636: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2637: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2638: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2639: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2640: 		next;
                   2641: 	    }
1.259     banghart 2642: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2643: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2644: 	    my $partial= $pts/$wgt;
1.259     banghart 2645: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2646: 		#do not update score for part if not changed.
1.346     banghart 2647:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2648: 		next;
1.251     banghart 2649: 	    } else {
1.259     banghart 2650: 	        push @parts_graded, $new_part;
1.153     albertel 2651: 	    }
1.259     banghart 2652: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2653: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2654: 	    }
1.259     banghart 2655: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2656: 	    if ($partial == 0) {
1.153     albertel 2657: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2658: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2659: 		}
1.41      ng       2660: 	    } else {
1.153     albertel 2661: 		if ($record{$reckey} ne 'correct_by_override') {
                   2662: 		    $newrecord{$reckey} = 'correct_by_override';
                   2663: 		}
                   2664: 	    }	    
                   2665: 	    if ($submitter && 
1.259     banghart 2666: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2667: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2668: 	    }
1.259     banghart 2669: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2670: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2671: 	}
1.259     banghart 2672: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2673: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2674: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2675: 	        $dropMenu eq 'reset status')
                   2676: 	   {
1.342     banghart 2677: 	    push (@version_parts,$new_part);
1.259     banghart 2678: 	}
1.41      ng       2679:     }
1.301     albertel 2680:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2681:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2682: 
1.344     albertel 2683:     if (%newrecord) {
                   2684:         if (@version_parts) {
1.364     banghart 2685:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2686:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2687: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2688: 	    foreach my $new_part (@version_parts) {
                   2689: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2690: 				$new_part,\%newrecord);
                   2691: 	    }
1.259     banghart 2692:         }
1.44      ng       2693: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2694: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2695: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2696: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2697:     }
1.269     raeburn  2698:     if ($aggregateflag) {
                   2699:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2700: 			      $cdom,$cnum);
1.269     raeburn  2701:     }
1.301     albertel 2702:     return ('',$pts,$wgt);
1.36      ng       2703: }
1.322     albertel 2704: 
1.380     albertel 2705: sub check_and_remove_from_queue {
                   2706:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2707:     my @ungraded_parts;
                   2708:     foreach my $part (@{$parts}) {
                   2709: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2710: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2711: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2712: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2713: 		) {
                   2714: 	    push(@ungraded_parts, $part);
                   2715: 	}
                   2716:     }
                   2717:     if ( !@ungraded_parts ) {
                   2718: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2719: 					       $cnum,$domain,$stuname);
                   2720:     }
                   2721: }
                   2722: 
1.337     banghart 2723: sub handback_files {
                   2724:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2725:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2726:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2727: 
                   2728:     my @part_response_id = &flatten_responseType($responseType);
                   2729:     foreach my $part_response_id (@part_response_id) {
                   2730:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2731: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2732:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2733:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2734:                 my $file_counter = 1;
1.367     albertel 2735: 		my $file_msg;
1.337     banghart 2736:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2737:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2738:                     my ($directory,$answer_file) = 
                   2739:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2740:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2741: 		        &file_name_version_ext($answer_file);
1.355     banghart 2742: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2743: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2744: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2745:                     # fix file name
                   2746:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2747:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2748:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2749:             	                                $save_file_name);
1.337     banghart 2750:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2751:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2752:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2753:                     } else {
1.360     banghart 2754:                         # mark the file as read only
                   2755:                         my @files = ($save_file_name);
1.372     albertel 2756:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2757:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2758: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2759: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2760: 			}
                   2761:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2762: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2763: 
1.337     banghart 2764:                     }
                   2765:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2766:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2767:                     $file_counter++;
                   2768:                 }
1.367     albertel 2769: 		my $subject = "File Handed Back by Instructor ";
                   2770: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2771: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2772: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2773: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2774: 		my ($feedurl,$showsymb) = 
                   2775: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2776:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2777: 		my $msgstatus = 
                   2778:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2779: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2780:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2781:             }
                   2782:         }
1.338     banghart 2783:     return;
1.337     banghart 2784: }
                   2785: 
1.418     albertel 2786: sub get_feedurl_and_symb {
                   2787:     my ($symb,$uname,$udom) = @_;
                   2788:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2789:     $url = &Apache::lonnet::clutter($url);
                   2790:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2791: 					$symb,$udom,$uname);
                   2792:     if ($encrypturl =~ /^yes$/i) {
                   2793: 	&Apache::lonenc::encrypted(\$url,1);
                   2794: 	&Apache::lonenc::encrypted(\$symb,1);
                   2795:     }
                   2796:     return ($url,$symb);
                   2797: }
                   2798: 
1.313     banghart 2799: sub get_submitted_files {
                   2800:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2801:     my @files;
                   2802:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2803:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2804:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2805:     	    push(@files,$file_url.$file);
                   2806:         }
                   2807:     }
                   2808:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2809:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2810:     }
                   2811:     return (\@files);
                   2812: }
1.322     albertel 2813: 
1.269     raeburn  2814: # ----------- Provides number of tries since last reset.
                   2815: sub get_num_tries {
                   2816:     my ($record,$last_reset,$part) = @_;
                   2817:     my $timestamp = '';
                   2818:     my $num_tries = 0;
                   2819:     if ($$record{'version'}) {
                   2820:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2821:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2822:                 $timestamp = $$record{$version.':timestamp'};
                   2823:                 if ($timestamp > $last_reset) {
                   2824:                     $num_tries ++;
                   2825:                 } else {
                   2826:                     last;
                   2827:                 }
                   2828:             }
                   2829:         }
                   2830:     }
                   2831:     return $num_tries;
                   2832: }
                   2833: 
                   2834: # ----------- Determine decrements required in aggregate totals 
                   2835: sub decrement_aggs {
                   2836:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2837:     my %decrement = (
                   2838:                         attempts => 0,
                   2839:                         users => 0,
                   2840:                         correct => 0
                   2841:                     );
                   2842:     $decrement{'attempts'} = $aggtries;
                   2843:     if ($solvedstatus =~ /^correct/) {
                   2844:         $decrement{'correct'} = 1;
                   2845:     }
                   2846:     if ($aggtries == $totaltries) {
                   2847:         $decrement{'users'} = 1;
                   2848:     }
                   2849:     foreach my $type (keys (%decrement)) {
                   2850:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2851:     }
                   2852:     return;
                   2853: }
                   2854: 
                   2855: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2856: sub get_last_resets {
1.270     albertel 2857:     my ($symb,$courseid,$partids) =@_;
                   2858:     my %last_resets;
1.269     raeburn  2859:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2860:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2861:     my @keys;
                   2862:     foreach my $part (@{$partids}) {
                   2863: 	push(@keys,"$symb\0$part\0resettime");
                   2864:     }
                   2865:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2866: 				     $cdom,$cname);
                   2867:     foreach my $part (@{$partids}) {
                   2868: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2869:     }
1.270     albertel 2870:     return %last_resets;
1.269     raeburn  2871: }
                   2872: 
1.251     banghart 2873: # ----------- Handles creating versions for portfolio files as answers
                   2874: sub version_portfiles {
1.343     banghart 2875:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2876:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2877:     my @returned_keys;
1.255     banghart 2878:     my $parts = join('|', @$parts_graded);
1.359     www      2879:     my $portfolio_root = &propath($domain,$stu_name).
                   2880: 	'/userfiles/portfolio';
1.277     albertel 2881:     foreach my $key (keys(%$record)) {
1.259     banghart 2882:         my $new_portfiles;
1.263     banghart 2883:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2884:             my @versioned_portfiles;
1.367     albertel 2885:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2886:             foreach my $file (@portfiles) {
1.306     banghart 2887:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2888:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2889: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2890: 		    &file_name_version_ext($answer_file);
1.306     banghart 2891:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2892:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2893:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2894:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2895:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2896:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2897:                         [$directory.$new_answer],
1.306     banghart 2898:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2899:                 }
1.252     banghart 2900:             }
1.343     banghart 2901:             $$record{$key} = join(',',@versioned_portfiles);
                   2902:             push(@returned_keys,$key);
1.251     banghart 2903:         }
                   2904:     } 
1.343     banghart 2905:     return (@returned_keys);   
1.305     banghart 2906: }
                   2907: 
1.307     banghart 2908: sub get_next_version {
1.341     banghart 2909:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2910:     my $version;
                   2911:     foreach my $row (@$dir_list) {
                   2912:         my ($file) = split(/\&/,$row,2);
                   2913:         my ($file_name,$file_version,$file_ext) =
                   2914: 	    &file_name_version_ext($file);
                   2915:         if (($file_name eq $answer_name) && 
                   2916: 	    ($file_ext eq $answer_ext)) {
                   2917:                 # gets here if filename and extension match, regardless of version
                   2918:                 if ($file_version ne '') {
                   2919:                 # a versioned file is found  so save it for later
                   2920:                 if ($file_version > $version) {
                   2921: 		    $version = $file_version;
                   2922: 	        }
                   2923:             }
                   2924:         }
                   2925:     } 
                   2926:     $version ++;
                   2927:     return($version);
                   2928: }
                   2929: 
1.305     banghart 2930: sub version_selected_portfile {
1.306     banghart 2931:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2932:     my ($answer_name,$answer_ver,$answer_ext) =
                   2933:         &file_name_version_ext($file_name);
                   2934:     my $new_answer;
                   2935:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2936:     if($env{'form.copy'} eq '-1') {
                   2937:         $new_answer = 'problem getting file';
                   2938:     } else {
                   2939:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2940:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2941:                             $stu_name,$domain,'copy',
                   2942: 		        '/portfolio'.$directory.$new_answer);
                   2943:     }    
                   2944:     return ($new_answer);
1.251     banghart 2945: }
                   2946: 
1.304     albertel 2947: sub file_name_version_ext {
                   2948:     my ($file)=@_;
                   2949:     my @file_parts = split(/\./, $file);
                   2950:     my ($name,$version,$ext);
                   2951:     if (@file_parts > 1) {
                   2952: 	$ext=pop(@file_parts);
                   2953: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2954: 	    $version=pop(@file_parts);
                   2955: 	}
                   2956: 	$name=join('.',@file_parts);
                   2957:     } else {
                   2958: 	$name=join('.',@file_parts);
                   2959:     }
                   2960:     return($name,$version,$ext);
                   2961: }
                   2962: 
1.44      ng       2963: #--------------------------------------------------------------------------------------
                   2964: #
                   2965: #-------------------------- Next few routines handles grading by section or whole class
                   2966: #
                   2967: #--- Javascript to handle grading by section or whole class
1.42      ng       2968: sub viewgrades_js {
                   2969:     my ($request) = shift;
                   2970: 
1.41      ng       2971:     $request->print(<<VIEWJAVASCRIPT);
                   2972: <script type="text/javascript" language="javascript">
1.45      ng       2973:    function writePoint(partid,weight,point) {
1.125     ng       2974: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2975: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2976: 	if (point == "textval") {
1.125     ng       2977: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2978: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2979: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2980: 		var resetbox = false;
                   2981: 		for (var i=0; i<radioButton.length; i++) {
                   2982: 		    if (radioButton[i].checked) {
                   2983: 			textbox.value = i;
                   2984: 			resetbox = true;
                   2985: 		    }
                   2986: 		}
                   2987: 		if (!resetbox) {
                   2988: 		    textbox.value = "";
                   2989: 		}
                   2990: 		return;
                   2991: 	    }
1.109     matthew  2992: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2993: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2994: 				   ") greater than the weight for the part. Accept?");
                   2995: 		if (resp == false) {
                   2996: 		    textbox.value = "";
                   2997: 		    return;
                   2998: 		}
                   2999: 	    }
1.42      ng       3000: 	    for (var i=0; i<radioButton.length; i++) {
                   3001: 		radioButton[i].checked=false;
1.109     matthew  3002: 		if (parseFloat(point) == i) {
1.42      ng       3003: 		    radioButton[i].checked=true;
                   3004: 		}
                   3005: 	    }
1.41      ng       3006: 
1.42      ng       3007: 	} else {
1.125     ng       3008: 	    textbox.value = parseFloat(point);
1.42      ng       3009: 	}
1.41      ng       3010: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3011: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3012: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3013: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3014: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3015: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3016: 	    if (saveval != "correct") {
                   3017: 		scorename.value = point;
1.43      ng       3018: 		if (selname[0].selected != true) {
                   3019: 		    selname[0].selected = true;
                   3020: 		}
1.42      ng       3021: 	    }
                   3022: 	}
1.125     ng       3023: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3024:     }
                   3025: 
                   3026:     function writeRadText(partid,weight) {
1.125     ng       3027: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3028: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3029:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3030: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3031: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3032: 	    for (var i=0; i<radioButton.length; i++) {
                   3033: 		radioButton[i].checked=false;
                   3034: 
                   3035: 	    }
                   3036: 	    textbox.value = "";
                   3037: 
                   3038: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3039: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3040: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3041: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3042: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3043: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3044: 		if ((saveval != "correct") || override) {
1.42      ng       3045: 		    scorename.value = "";
1.125     ng       3046: 		    if (selval[1].selected) {
                   3047: 			selname[1].selected = true;
                   3048: 		    } else {
                   3049: 			selname[2].selected = true;
                   3050: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3051: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3052: 		    }
1.42      ng       3053: 		}
                   3054: 	    }
1.43      ng       3055: 	} else {
                   3056: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3057: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3058: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3059: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3060: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3061: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3062: 		if ((saveval != "correct") || override) {
1.125     ng       3063: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3064: 		    selname[0].selected = true;
                   3065: 		}
                   3066: 	    }
                   3067: 	}	    
1.42      ng       3068:     }
                   3069: 
                   3070:     function changeSelect(partid,user) {
1.125     ng       3071: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3072: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3073: 	var point  = textbox.value;
1.125     ng       3074: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3075: 
1.109     matthew  3076: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3077: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3078: 	    textbox.value = "";
                   3079: 	    return;
                   3080: 	}
1.109     matthew  3081: 	if (parseFloat(point) > parseFloat(weight)) {
                   3082: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3083: 			       ") greater than the weight of the part. Accept?");
                   3084: 	    if (resp == false) {
                   3085: 		textbox.value = "";
                   3086: 		return;
                   3087: 	    }
                   3088: 	}
1.42      ng       3089: 	selval[0].selected = true;
                   3090:     }
                   3091: 
                   3092:     function changeOneScore(partid,user) {
1.125     ng       3093: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3094: 	if (selval[1].selected || selval[2].selected) {
                   3095: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3096: 	    if (selval[2].selected) {
                   3097: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3098: 	    }
1.269     raeburn  3099:         }
1.42      ng       3100:     }
                   3101: 
                   3102:     function resetEntry(numpart) {
                   3103: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3104: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3105: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3106: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3107: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3108: 	    for (var i=0; i<radioButton.length; i++) {
                   3109: 		radioButton[i].checked=false;
                   3110: 
                   3111: 	    }
                   3112: 	    textbox.value = "";
                   3113: 	    selval[0].selected = true;
                   3114: 
                   3115: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3116: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3117: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3118: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3119: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3120: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3121: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3122: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3123: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3124: 		if (saveselval == "excused") {
1.43      ng       3125: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3126: 		} else {
1.43      ng       3127: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3128: 		}
                   3129: 	    }
1.41      ng       3130: 	}
1.42      ng       3131:     }
                   3132: 
1.41      ng       3133: </script>
                   3134: VIEWJAVASCRIPT
1.42      ng       3135: }
                   3136: 
1.44      ng       3137: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3138: sub viewgrades {
                   3139:     my ($request) = shift;
                   3140:     &viewgrades_js($request);
1.41      ng       3141: 
1.324     albertel 3142:     my ($symb) = &get_symb($request);
1.168     albertel 3143:     #need to make sure we have the correct data for later EXT calls, 
                   3144:     #thus invalidate the cache
                   3145:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3146:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3147:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3148:     &Apache::lonnet::clear_EXT_cache_status();
                   3149: 
1.398     albertel 3150:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3151:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3152: 
                   3153:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3154:     $result.=&jscriptNform($symb);
1.41      ng       3155: 
1.44      ng       3156:     #beginning of class grading form
1.442     banghart 3157:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3158:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3159: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3160: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3161: 	&build_section_inputs().
1.257     albertel 3162: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3163: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3164: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3165: 
1.126     ng       3166:     my $sectionClass;
1.430     banghart 3167:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3168:     if ($env{'form.section'} eq 'all') {
1.126     ng       3169: 	$sectionClass='Class </h3>';
1.257     albertel 3170:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3171: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3172:     } else {
1.431     banghart 3173: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3174:     }
1.431     banghart 3175:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.474     albertel 3176:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3177:     #radio buttons/text box for assigning points for a section or class.
                   3178:     #handles different parts of a problem
1.375     albertel 3179:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3180:     my %weight = ();
                   3181:     my $ctsparts = 0;
1.45      ng       3182:     my %seen = ();
1.375     albertel 3183:     my @part_response_id = &flatten_responseType($responseType);
                   3184:     foreach my $part_response_id (@part_response_id) {
                   3185:     	my ($partid,$respid) = @{ $part_response_id };
                   3186: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3187: 	next if $seen{$partid};
                   3188: 	$seen{$partid}++;
1.375     albertel 3189: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3190: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3191: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3192: 
1.474     albertel 3193: 	$result.=&Apache::loncommon::start_data_table_row().'<td>';
1.44      ng       3194: 	$result.='<input type="hidden" name="partid_'.
                   3195: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3196: 	$result.='<input type="hidden" name="weight_'.
                   3197: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3198: 	my $display_part=&get_display_part($partid,$symb);
1.474     albertel 3199: 	$result.=
                   3200: 	    '<b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3201: 	$result.='<table border="0"><tr>';  
1.41      ng       3202: 	my $ctr = 0;
1.42      ng       3203: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3204: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3205: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3206: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3207: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3208: 	    $ctr++;
                   3209: 	}
                   3210: 	$result.='</tr></table>';
1.44      ng       3211: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3212: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3213: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3214: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.474     albertel 3215: 	$result.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3216: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3217: 		$weight{$partid}.')"> '.
1.401     albertel 3218: 	    '<option selected="selected"> </option>'.
1.125     ng       3219: 	    '<option>excused</option>'.
1.265     www      3220: 	    '<option>reset status</option></select></td>'.
1.474     albertel 3221:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td>'.&Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3222: 	$ctsparts++;
1.41      ng       3223:     }
1.474     albertel 3224:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3225: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3226:     $result.='<input type="button" value="Revert to Default" '.
1.474     albertel 3227: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3228: 
1.44      ng       3229:     #table listing all the students in a section/class
                   3230:     #header of table
1.126     ng       3231:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.474     albertel 3232:     $result.= &Apache::loncommon::start_data_table().
                   3233: 	&Apache::loncommon::start_data_table_header_row().
                   3234: 	'<th>No.</th>'.
                   3235: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3236:     my (@parts) = sort(&getpartlist($symb));
                   3237:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3238:     my @partids = ();
1.41      ng       3239:     foreach my $part (@parts) {
                   3240: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3241: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3242: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3243: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3244:         push(@partids, $partid);
1.324     albertel 3245: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3246: 	if ($display =~ /^Partial Credit Factor/) {
1.474     albertel 3247: 	    $result.='<th>Score Part: '.$display_part.
                   3248: 		' <br />(weight = '.$weight{$partid}.')</th>'."\n";
1.41      ng       3249: 	    next;
1.207     albertel 3250: 	} else {
                   3251: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3252: 	}
1.53      albertel 3253: 	$display =~ s|Problem Status|Grade Status<br />|;
1.474     albertel 3254: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3255:     }
1.474     albertel 3256:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3257: 
1.270     albertel 3258:     my %last_resets = 
                   3259: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3260: 
1.41      ng       3261:     #get info for each student
1.44      ng       3262:     #list all the students - with points and grade status
1.257     albertel 3263:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3264:     my $ctr = 0;
1.294     albertel 3265:     foreach (sort 
                   3266: 	     {
                   3267: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3268: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3269: 		 }
                   3270: 		 return $a cmp $b;
                   3271: 	     } (keys(%$fullname))) {
1.126     ng       3272: 	$ctr++;
1.324     albertel 3273: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3274: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3275:     }
1.474     albertel 3276:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3277:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3278:     $result.='<input type="button" value="Save" '.
1.417     albertel 3279: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3280:     if (scalar(%$fullname) eq 0) {
                   3281: 	my $colspan=3+scalar(@parts);
1.433     banghart 3282: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3283:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3284: 	$result='<span class="LC_warning">'.
                   3285: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3286: 	        $section_display, $stu_status).
1.433     banghart 3287: 	    '</span>';
1.96      albertel 3288:     }
1.324     albertel 3289:     $result.=&show_grading_menu_form($symb);
1.41      ng       3290:     return $result;
                   3291: }
                   3292: 
1.44      ng       3293: #--- call by previous routine to display each student
1.41      ng       3294: sub viewstudentgrade {
1.324     albertel 3295:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3296:     my ($uname,$udom) = split(/:/,$student);
                   3297:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3298:     my %aggregates = (); 
1.474     albertel 3299:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3300: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3301: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3302: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3303: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3304: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3305:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3306:     foreach my $apart (@$parts) {
                   3307: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3308: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3309:         $result.='<td align="center">';
1.269     raeburn  3310:         my ($aggtries,$totaltries);
                   3311:         unless (exists($aggregates{$part})) {
1.270     albertel 3312: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3313: 
                   3314: 	    $aggtries = $totaltries;
1.269     raeburn  3315:             if ($$last_resets{$part}) {  
1.270     albertel 3316:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3317: 					   $part);
                   3318:             }
1.269     raeburn  3319:             $result.='<input type="hidden" name="'.
                   3320:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3321:             $result.='<input type="hidden" name="'.
                   3322:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3323:             $aggregates{$part} = 1;
                   3324:         }
1.41      ng       3325: 	if ($type eq 'awarded') {
1.320     albertel 3326: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3327: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3328: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3329: 	    $result.='<input type="text" name="'.
1.89      albertel 3330: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3331: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3332: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3333: 	} elsif ($type eq 'solved') {
                   3334: 	    my ($status,$foo)=split(/_/,$score,2);
                   3335: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3336: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3337: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3338: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3339: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3340: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3341: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3342: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3343: 	    $result.='<option>reset status</option>';
1.126     ng       3344: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3345: 	} else {
                   3346: 	    $result.='<input type="hidden" name="'.
                   3347: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3348: 		    "\n";
1.233     albertel 3349: 	    $result.='<input type="text" name="'.
1.122     ng       3350: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3351: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3352: 	}
                   3353:     }
1.474     albertel 3354:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3355:     return $result;
1.38      ng       3356: }
                   3357: 
1.44      ng       3358: #--- change scores for all the students in a section/class
                   3359: #    record does not get update if unchanged
1.38      ng       3360: sub editgrades {
1.41      ng       3361:     my ($request) = @_;
                   3362: 
1.324     albertel 3363:     my $symb=&get_symb($request);
1.433     banghart 3364:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3365:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3366:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3367:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3368: 
1.44      ng       3369:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3370:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3371: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3372: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3373: 
                   3374:     my %scoreptr = (
                   3375: 		    'correct'  =>'correct_by_override',
                   3376: 		    'incorrect'=>'incorrect_by_override',
                   3377: 		    'excused'  =>'excused',
                   3378: 		    'ungraded' =>'ungraded_attempted',
                   3379: 		    'nothing'  => '',
                   3380: 		    );
1.257     albertel 3381:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3382: 
1.44      ng       3383:     my (@partid);
                   3384:     my %weight = ();
1.54      albertel 3385:     my %columns = ();
1.44      ng       3386:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3387: 
1.324     albertel 3388:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3389:     my $header;
1.257     albertel 3390:     while ($ctr < $env{'form.totalparts'}) {
                   3391: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3392: 	push @partid,$partid;
1.257     albertel 3393: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3394: 	$ctr++;
1.54      albertel 3395:     }
1.324     albertel 3396:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3397:     foreach my $partid (@partid) {
                   3398: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3399: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3400: 	$columns{$partid}=2;
                   3401: 	foreach my $stores (@parts) {
                   3402: 	    my ($part,$type) = &split_part_type($stores);
                   3403: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3404: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3405: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3406: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3407: 	    $display =~ s/Number of Attempts/Tries/;
                   3408: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3409: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3410: 	    $columns{$partid}+=2;
                   3411: 	}
                   3412:     }
                   3413:     foreach my $partid (@partid) {
1.324     albertel 3414: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3415: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3416: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3417: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3418: 
1.44      ng       3419:     }
                   3420:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3421:     $result .= $header;
1.44      ng       3422:     $result .= '</tr>'."\n";
1.93      albertel 3423:     my $noupdate;
1.126     ng       3424:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3425:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3426: 	my $line;
1.257     albertel 3427: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3428: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3429: 	my %newrecord;
                   3430: 	my $updateflag = 0;
1.281     albertel 3431: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3432: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3433: 	if (!&canmodify($usec)) {
1.126     ng       3434: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3435: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3436: 	    next;
                   3437: 	}
1.269     raeburn  3438:         my %aggregate = ();
                   3439:         my $aggregateflag = 0;
1.281     albertel 3440: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3441: 	foreach (@partid) {
1.257     albertel 3442: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3443: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3444: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3445: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3446: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3447: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3448: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3449: 	    my $score;
                   3450: 	    if ($partial eq '') {
1.257     albertel 3451: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3452: 	    } elsif ($partial > 0) {
                   3453: 		$score = 'correct_by_override';
                   3454: 	    } elsif ($partial == 0) {
                   3455: 		$score = 'incorrect_by_override';
                   3456: 	    }
1.257     albertel 3457: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3458: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3459: 
1.292     albertel 3460: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3461: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3462: 	    if ($dropMenu eq 'reset status' &&
                   3463: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3464: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3465: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3466: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3467: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3468: 		$updateflag = 1;
1.269     raeburn  3469:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3470:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3471:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3472:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3473:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3474:                     $aggregateflag = 1;
                   3475:                 }
1.139     albertel 3476: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3477: 		$updateflag = 1;
                   3478: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3479: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3480: 		$rec_update++;
1.125     ng       3481: 	    }
                   3482: 
1.93      albertel 3483: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3484: 		'<td align="center">'.$awarded.
                   3485: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3486: 
1.54      albertel 3487: 
                   3488: 	    my $partid=$_;
                   3489: 	    foreach my $stores (@parts) {
                   3490: 		my ($part,$type) = &split_part_type($stores);
                   3491: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3492: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3493: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3494: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3495: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3496: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3497: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3498: 		    $updateflag=1;
                   3499: 		}
1.93      albertel 3500: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3501: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3502: 	    }
1.44      ng       3503: 	}
1.93      albertel 3504: 	$line.='</tr>'."\n";
1.301     albertel 3505: 
                   3506: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3507: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3508: 
1.44      ng       3509: 	if ($updateflag) {
                   3510: 	    $count++;
1.257     albertel 3511: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3512: 				    $udom,$uname);
1.301     albertel 3513: 
                   3514: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3515: 					      $cnum,$udom,$uname)) {
                   3516: 		# need to figure out if should be in queue.
                   3517: 		my %record =  
                   3518: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3519: 					     $udom,$uname);
                   3520: 		my $all_graded = 1;
                   3521: 		my $none_graded = 1;
                   3522: 		foreach my $part (@parts) {
                   3523: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3524: 			$all_graded = 0;
                   3525: 		    } else {
                   3526: 			$none_graded = 0;
                   3527: 		    }
                   3528: 		}
                   3529: 
                   3530: 		if ($all_graded || $none_graded) {
                   3531: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3532: 							   $symb,$cdom,$cnum,
                   3533: 							   $udom,$uname);
                   3534: 		}
                   3535: 	    }
                   3536: 
1.126     ng       3537: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3538: 	    $updateCtr++;
1.93      albertel 3539: 	} else {
1.126     ng       3540: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3541: 	    $noupdateCtr++;
1.44      ng       3542: 	}
1.269     raeburn  3543:         if ($aggregateflag) {
                   3544:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3545: 				  $cdom,$cnum);
1.269     raeburn  3546:         }
1.93      albertel 3547:     }
                   3548:     if ($noupdate) {
1.126     ng       3549: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3550: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3551: 	$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       3552:     }
1.72      ng       3553:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3554: 	&show_grading_menu_form ($symb);
1.125     ng       3555:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3556: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3557: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3558:     return $title.$msg.$result;
1.5       albertel 3559: }
1.54      albertel 3560: 
                   3561: sub split_part_type {
                   3562:     my ($partstr) = @_;
                   3563:     my ($temp,@allparts)=split(/_/,$partstr);
                   3564:     my $type=pop(@allparts);
1.439     albertel 3565:     my $part=join('_',@allparts);
1.54      albertel 3566:     return ($part,$type);
                   3567: }
                   3568: 
1.44      ng       3569: #------------- end of section for handling grading by section/class ---------
                   3570: #
                   3571: #----------------------------------------------------------------------------
                   3572: 
1.5       albertel 3573: 
1.44      ng       3574: #----------------------------------------------------------------------------
                   3575: #
                   3576: #-------------------------- Next few routines handles grading by csv upload
                   3577: #
                   3578: #--- Javascript to handle csv upload
1.27      albertel 3579: sub csvupload_javascript_reverse_associate {
1.246     albertel 3580:     my $error1=&mt('You need to specify the username or ID');
                   3581:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3582:   return(<<ENDPICK);
                   3583:   function verify(vf) {
                   3584:     var foundsomething=0;
                   3585:     var founduname=0;
1.243     albertel 3586:     var foundID=0;
1.27      albertel 3587:     for (i=0;i<=vf.nfields.value;i++) {
                   3588:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3589:       if (i==0 && tw!=0) { foundID=1; }
                   3590:       if (i==1 && tw!=0) { founduname=1; }
                   3591:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3592:     }
1.246     albertel 3593:     if (founduname==0 && foundID==0) {
                   3594: 	alert('$error1');
                   3595: 	return;
1.27      albertel 3596:     }
                   3597:     if (foundsomething==0) {
1.246     albertel 3598: 	alert('$error2');
                   3599: 	return;
1.27      albertel 3600:     }
                   3601:     vf.submit();
                   3602:   }
                   3603:   function flip(vf,tf) {
                   3604:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3605:     var i;
                   3606:     for (i=0;i<=vf.nfields.value;i++) {
                   3607:       //can not pick the same destination field for both name and domain
                   3608:       if (((i ==0)||(i ==1)) && 
                   3609:           ((tf==0)||(tf==1)) && 
                   3610:           (i!=tf) &&
                   3611:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3612:         eval('vf.f'+i+'.selectedIndex=0;')
                   3613:       }
                   3614:     }
                   3615:   }
                   3616: ENDPICK
                   3617: }
                   3618: 
                   3619: sub csvupload_javascript_forward_associate {
1.246     albertel 3620:     my $error1=&mt('You need to specify the username or ID');
                   3621:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3622:   return(<<ENDPICK);
                   3623:   function verify(vf) {
                   3624:     var foundsomething=0;
                   3625:     var founduname=0;
1.243     albertel 3626:     var foundID=0;
1.27      albertel 3627:     for (i=0;i<=vf.nfields.value;i++) {
                   3628:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3629:       if (tw==1) { foundID=1; }
                   3630:       if (tw==2) { founduname=1; }
                   3631:       if (tw>3) { foundsomething=1; }
1.27      albertel 3632:     }
1.246     albertel 3633:     if (founduname==0 && foundID==0) {
                   3634: 	alert('$error1');
                   3635: 	return;
1.27      albertel 3636:     }
                   3637:     if (foundsomething==0) {
1.246     albertel 3638: 	alert('$error2');
                   3639: 	return;
1.27      albertel 3640:     }
                   3641:     vf.submit();
                   3642:   }
                   3643:   function flip(vf,tf) {
                   3644:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3645:     var i;
                   3646:     //can not pick the same destination field twice
                   3647:     for (i=0;i<=vf.nfields.value;i++) {
                   3648:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3649:         eval('vf.f'+i+'.selectedIndex=0;')
                   3650:       }
                   3651:     }
                   3652:   }
                   3653: ENDPICK
                   3654: }
                   3655: 
1.26      albertel 3656: sub csvuploadmap_header {
1.324     albertel 3657:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3658:     my $javascript;
1.257     albertel 3659:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3660: 	$javascript=&csvupload_javascript_reverse_associate();
                   3661:     } else {
                   3662: 	$javascript=&csvupload_javascript_forward_associate();
                   3663:     }
1.45      ng       3664: 
1.324     albertel 3665:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3666:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3667:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3668:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3669:     $request->print(<<ENDPICK);
1.26      albertel 3670: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3671: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3672: $result
1.326     albertel 3673: <hr />
1.26      albertel 3674: <h3>Identify fields</h3>
                   3675: Total number of records found in file: $distotal <hr />
                   3676: Enter as many fields as you can. The system will inform you and bring you back
                   3677: to this page if the data selected is insufficient to run your class.<hr />
                   3678: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3679: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3680: <input type="hidden" name="associate"  value="" />
                   3681: <input type="hidden" name="phase"      value="three" />
                   3682: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3683: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3684: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3685: <input type="hidden" name="upfile_associate" 
1.257     albertel 3686:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3687: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3688: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3689: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3690: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3691: <hr />
                   3692: <script type="text/javascript" language="Javascript">
                   3693: $javascript
                   3694: </script>
                   3695: ENDPICK
1.118     ng       3696:     return '';
1.26      albertel 3697: 
                   3698: }
                   3699: 
                   3700: sub csvupload_fields {
1.324     albertel 3701:     my ($symb) = @_;
                   3702:     my (@parts) = &getpartlist($symb);
1.243     albertel 3703:     my @fields=(['ID','Student ID'],
                   3704: 		['username','Student Username'],
                   3705: 		['domain','Student Domain']);
1.324     albertel 3706:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3707:     foreach my $part (sort(@parts)) {
                   3708: 	my @datum;
                   3709: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3710: 	my $name=$part;
                   3711: 	if  (!$display) { $display = $name; }
                   3712: 	@datum=($name,$display);
1.244     albertel 3713: 	if ($name=~/^stores_(.*)_awarded/) {
                   3714: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3715: 	}
1.41      ng       3716: 	push(@fields,\@datum);
                   3717:     }
                   3718:     return (@fields);
1.26      albertel 3719: }
                   3720: 
                   3721: sub csvuploadmap_footer {
1.41      ng       3722:     my ($request,$i,$keyfields) =@_;
                   3723:     $request->print(<<ENDPICK);
1.26      albertel 3724: </table>
                   3725: <input type="hidden" name="nfields" value="$i" />
                   3726: <input type="hidden" name="keyfields" value="$keyfields" />
                   3727: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3728: </form>
                   3729: ENDPICK
                   3730: }
                   3731: 
1.283     albertel 3732: sub checkforfile_js {
1.86      ng       3733:     my $result =<<CSVFORMJS;
                   3734: <script type="text/javascript" language="javascript">
                   3735:     function checkUpload(formname) {
                   3736: 	if (formname.upfile.value == "") {
                   3737: 	    alert("Please use the browse button to select a file from your local directory.");
                   3738: 	    return false;
                   3739: 	}
                   3740: 	formname.submit();
                   3741:     }
                   3742:     </script>
                   3743: CSVFORMJS
1.283     albertel 3744:     return $result;
                   3745: }
                   3746: 
                   3747: sub upcsvScores_form {
                   3748:     my ($request) = shift;
1.324     albertel 3749:     my ($symb)=&get_symb($request);
1.283     albertel 3750:     if (!$symb) {return '';}
                   3751:     my $result=&checkforfile_js();
1.257     albertel 3752:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3753:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3754:     $result.=$table;
1.326     albertel 3755:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3756:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3757:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3758: 	'.</b></td></tr>'."\n";
                   3759:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3760:     my $upload=&mt("Upload Scores");
1.86      ng       3761:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3762:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3763:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3764:     $result.=<<ENDUPFORM;
1.106     albertel 3765: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3766: <input type="hidden" name="symb" value="$symb" />
                   3767: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3768: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3769: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3770: $upfile_select
1.370     www      3771: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3772: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3773: </form>
                   3774: ENDUPFORM
1.370     www      3775:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3776:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3777:     .'</td></tr></table>'."\n";
1.86      ng       3778:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3779:     $result.=&show_grading_menu_form($symb);
1.86      ng       3780:     return $result;
                   3781: }
                   3782: 
                   3783: 
1.26      albertel 3784: sub csvuploadmap {
1.41      ng       3785:     my ($request)= @_;
1.324     albertel 3786:     my ($symb)=&get_symb($request);
1.41      ng       3787:     if (!$symb) {return '';}
1.72      ng       3788: 
1.41      ng       3789:     my $datatoken;
1.257     albertel 3790:     if (!$env{'form.datatoken'}) {
1.41      ng       3791: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3792:     } else {
1.257     albertel 3793: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3794: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3795:     }
1.41      ng       3796:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3797:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3798:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3799:     my ($i,$keyfields);
                   3800:     if (@records) {
1.324     albertel 3801: 	my @fields=&csvupload_fields($symb);
1.45      ng       3802: 
1.257     albertel 3803: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3804: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3805: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3806: 							  \@fields);
                   3807: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3808: 	    chop($keyfields);
                   3809: 	} else {
                   3810: 	    unshift(@fields,['none','']);
                   3811: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3812: 							    \@fields);
1.311     banghart 3813:             foreach my $rec (@records) {
                   3814:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3815:                 if (%temp) {
                   3816:                     $keyfields=join(',',sort(keys(%temp)));
                   3817:                     last;
                   3818:                 }
                   3819:             }
1.41      ng       3820: 	}
                   3821:     }
                   3822:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3823:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3824: 
1.41      ng       3825:     return '';
1.27      albertel 3826: }
                   3827: 
1.246     albertel 3828: sub csvuploadoptions {
1.41      ng       3829:     my ($request)= @_;
1.324     albertel 3830:     my ($symb)=&get_symb($request);
1.257     albertel 3831:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3832:     my $ignore=&mt('Ignore First Line');
                   3833:     $request->print(<<ENDPICK);
                   3834: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3835: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3836: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3837: <!--
1.246     albertel 3838: <p>
                   3839: <label>
                   3840:    <input type="checkbox" name="show_full_results" />
                   3841:    Show a table of all changes
                   3842: </label>
                   3843: </p>
1.302     albertel 3844: -->
1.246     albertel 3845: <p>
                   3846: <label>
                   3847:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3848:    Overwrite any existing score
                   3849: </label>
                   3850: </p>
                   3851: ENDPICK
                   3852:     my %fields=&get_fields();
                   3853:     if (!defined($fields{'domain'})) {
1.257     albertel 3854: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3855: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3856:     }
1.257     albertel 3857:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3858: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3859: 	my $cleankey=$1;
                   3860: 	if ($cleankey eq 'command') { next; }
                   3861: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3862: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3863:     }
                   3864:     # FIXME do a check for any duplicated user ids...
                   3865:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3866:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3867: <hr /></form>'."\n");
1.324     albertel 3868:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3869:     return '';
                   3870: }
                   3871: 
                   3872: sub get_fields {
                   3873:     my %fields;
1.257     albertel 3874:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3875:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3876: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3877: 	    if ($env{'form.f'.$i} ne 'none') {
                   3878: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3879: 	    }
                   3880: 	} else {
1.257     albertel 3881: 	    if ($env{'form.f'.$i} ne 'none') {
                   3882: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3883: 	    }
                   3884: 	}
1.27      albertel 3885:     }
1.246     albertel 3886:     return %fields;
                   3887: }
                   3888: 
                   3889: sub csvuploadassign {
                   3890:     my ($request)= @_;
1.324     albertel 3891:     my ($symb)=&get_symb($request);
1.246     albertel 3892:     if (!$symb) {return '';}
1.345     bowersj2 3893:     my $error_msg = '';
1.246     albertel 3894:     &Apache::loncommon::load_tmp_file($request);
                   3895:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3896:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3897:     my %fields=&get_fields();
1.41      ng       3898:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3899:     my $courseid=$env{'request.course.id'};
1.97      albertel 3900:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3901:     my @notallowed;
1.41      ng       3902:     my @skipped;
                   3903:     my $countdone=0;
                   3904:     foreach my $grade (@gradedata) {
                   3905: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3906: 	my $domain;
                   3907: 	if ($entries{$fields{'domain'}}) {
                   3908: 	    $domain=$entries{$fields{'domain'}};
                   3909: 	} else {
1.257     albertel 3910: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3911: 	}
1.243     albertel 3912: 	$domain=~s/\s//g;
1.41      ng       3913: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3914: 	$username=~s/\s//g;
1.243     albertel 3915: 	if (!$username) {
                   3916: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3917: 	    $id=~s/\s//g;
1.243     albertel 3918: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3919: 	    $username=$ids{$id};
                   3920: 	}
1.41      ng       3921: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3922: 	    my $id=$entries{$fields{'ID'}};
                   3923: 	    $id=~s/\s//g;
                   3924: 	    if ($id) {
                   3925: 		push(@skipped,"$id:$domain");
                   3926: 	    } else {
                   3927: 		push(@skipped,"$username:$domain");
                   3928: 	    }
1.41      ng       3929: 	    next;
                   3930: 	}
1.108     albertel 3931: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3932: 	if (!&canmodify($usec)) {
                   3933: 	    push(@notallowed,"$username:$domain");
                   3934: 	    next;
                   3935: 	}
1.244     albertel 3936: 	my %points;
1.41      ng       3937: 	my %grades;
                   3938: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3939: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3940: 		$dest eq 'domain') { next; }
                   3941: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3942: 	    if ($dest=~/stores_(.*)_points/) {
                   3943: 		my $part=$1;
                   3944: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3945: 					      $symb,$domain,$username);
1.345     bowersj2 3946:                 if ($wgt) {
                   3947:                     $entries{$fields{$dest}}=~s/\s//g;
                   3948:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 3949:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   3950:                                           : 'correct_by_override';
1.345     bowersj2 3951:                     $grades{"resource.$part.awarded"}=$pcr;
                   3952:                     $grades{"resource.$part.solved"}=$award;
                   3953:                     $points{$part}=1;
                   3954:                 } else {
                   3955:                     $error_msg = "<br />" .
                   3956:                         &mt("Some point values were assigned"
                   3957:                             ." for problems with a weight "
                   3958:                             ."of zero. These values were "
                   3959:                             ."ignored.");
                   3960:                 }
1.244     albertel 3961: 	    } else {
                   3962: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3963: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3964: 		my $store_key=$dest;
                   3965: 		$store_key=~s/^stores/resource/;
                   3966: 		$store_key=~s/_/\./g;
                   3967: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3968: 	    }
1.41      ng       3969: 	}
1.398     albertel 3970: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3971: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3972: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3973: 					   $env{'request.course.id'},
                   3974: 					   $domain,$username);
                   3975: 	if ($result eq 'ok') {
                   3976: 	    $request->print('.');
                   3977: 	} else {
                   3978: 	    $request->print("<p>
1.398     albertel 3979:                               <span class=\"LC_error\">
                   3980:                                  Failed to save student $username:$domain.
                   3981:                                  Message when trying to save was ($result)
                   3982:                               </span>
1.302     albertel 3983:                              </p>" );
                   3984: 	}
1.41      ng       3985: 	$request->rflush();
                   3986: 	$countdone++;
                   3987:     }
1.398     albertel 3988:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3989:     if (@skipped) {
1.398     albertel 3990: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3991: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3992:     }
                   3993:     if (@notallowed) {
1.398     albertel 3994: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3995: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3996:     }
1.106     albertel 3997:     $request->print("<br />\n");
1.324     albertel 3998:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3999:     return $error_msg;
1.26      albertel 4000: }
1.44      ng       4001: #------------- end of section for handling csv file upload ---------
                   4002: #
                   4003: #-------------------------------------------------------------------
                   4004: #
1.122     ng       4005: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4006: #
                   4007: #--- Select a page/sequence and a student to grade
1.68      ng       4008: sub pickStudentPage {
                   4009:     my ($request) = shift;
                   4010: 
                   4011:     $request->print(<<LISTJAVASCRIPT);
                   4012: <script type="text/javascript" language="javascript">
                   4013: 
                   4014: function checkPickOne(formname) {
1.76      ng       4015:     if (radioSelection(formname.student) == null) {
1.68      ng       4016: 	alert("Please select the student you wish to grade.");
                   4017: 	return;
                   4018:     }
1.125     ng       4019:     ptr = pullDownSelection(formname.selectpage);
                   4020:     formname.page.value = formname["page"+ptr].value;
                   4021:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4022:     formname.submit();
                   4023: }
                   4024: 
                   4025: </script>
                   4026: LISTJAVASCRIPT
1.118     ng       4027:     &commonJSfunctions($request);
1.324     albertel 4028:     my ($symb) = &get_symb($request);
1.257     albertel 4029:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4030:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4031:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4032: 
1.398     albertel 4033:     my $result='<h3><span class="LC_info">&nbsp;'.
                   4034: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       4035: 
1.80      ng       4036:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       4037:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 4038:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4039:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4040: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4041: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4042:     my $ctr=0;
1.68      ng       4043:     foreach (@$titles) {
                   4044: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4045: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4046: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4047: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4048: 	$ctr++;
1.68      ng       4049:     }
1.326     albertel 4050:     $result.= '</select>'."<br />\n";
1.70      ng       4051:     $ctr=0;
                   4052:     foreach (@$titles) {
                   4053: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4054: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4055: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4056: 	$ctr++;
                   4057:     }
1.72      ng       4058:     $result.='<input type="hidden" name="page" />'."\n".
                   4059: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4060: 
1.401     albertel 4061:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4062: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4063: 
1.71      ng       4064:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4065: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4066: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4067: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4068:     
                   4069:     $result.=&build_section_inputs();
1.442     banghart 4070:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4071:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4072: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4073: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4074: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4075: 
1.382     albertel 4076:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4077: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4078: 
1.80      ng       4079:     $result.='&nbsp;<input type="button" '.
1.126     ng       4080: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4081: 
1.68      ng       4082:     $request->print($result);
                   4083: 
1.326     albertel 4084:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4085: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4086: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4087: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4088: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4089: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4090: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4091:  
1.76      ng       4092:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4093:     my $ptr = 1;
1.294     albertel 4094:     foreach my $student (sort 
                   4095: 			 {
                   4096: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4097: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4098: 			     }
                   4099: 			     return $a cmp $b;
                   4100: 			 } (keys(%$fullname))) {
1.68      ng       4101: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4102: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4103: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4104: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4105: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4106: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4107: 	$ptr++;
                   4108:     }
1.381     albertel 4109:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4110:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4111:     $studentTable.='<input type="button" '.
                   4112: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4113: 
1.324     albertel 4114:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4115:     $request->print($studentTable);
                   4116: 
                   4117:     return '';
                   4118: }
                   4119: 
                   4120: sub getSymbMap {
1.132     bowersj2 4121:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4122: 
                   4123:     my %symbx = ();
                   4124:     my @titles = ();
1.117     bowersj2 4125:     my $minder = 0;
                   4126: 
                   4127:     # Gather every sequence that has problems.
1.240     albertel 4128:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4129: 					       1,0,1);
1.117     bowersj2 4130:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4131: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4132: 	    my $title = $minder.'.'.
                   4133: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4134: 	    push(@titles, $title); # minder in case two titles are identical
                   4135: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4136: 	    $minder++;
1.241     albertel 4137: 	}
1.68      ng       4138:     }
                   4139:     return \@titles,\%symbx;
                   4140: }
                   4141: 
1.72      ng       4142: #
                   4143: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4144: sub displayPage {
                   4145:     my ($request) = shift;
                   4146: 
1.324     albertel 4147:     my ($symb) = &get_symb($request);
1.257     albertel 4148:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4149:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4150:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4151:     my $pageTitle = $env{'form.page'};
1.103     albertel 4152:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4153:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4154:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4155: 
                   4156:     #need to make sure we have the correct data for later EXT calls, 
                   4157:     #thus invalidate the cache
                   4158:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4159:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4160:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4161:     &Apache::lonnet::clear_EXT_cache_status();
                   4162: 
1.103     albertel 4163:     if (!&canview($usec)) {
1.398     albertel 4164: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4165: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4166: 	return;
                   4167:     }
1.398     albertel 4168:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4169:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4170: 	'</h3>'."\n";
1.382     albertel 4171:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4172: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4173:     } else {
                   4174: 	delete($env{'form.CODE'});
                   4175:     }
1.71      ng       4176:     &sub_page_js($request);
                   4177:     $request->print($result);
                   4178: 
1.132     bowersj2 4179:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4180:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4181:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4182:     if (!$map) {
1.398     albertel 4183: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4184: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4185: 	return; 
                   4186:     }
1.68      ng       4187:     my $iterator = $navmap->getIterator($map->map_start(),
                   4188: 					$map->map_finish());
                   4189: 
1.71      ng       4190:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4191: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4192: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4193: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4194: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4195: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4196: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4197: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4198: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4199: 
1.382     albertel 4200:     if (defined($env{'form.CODE'})) {
                   4201: 	$studentTable.=
                   4202: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4203:     }
1.381     albertel 4204:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4205: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4206: 	'/check.gif" height="16" border="0" />';
                   4207: 
1.118     ng       4208:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4209: 	' symbol.'."\n".
1.71      ng       4210: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4211: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4212: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4213: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4214: 
1.329     albertel 4215:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4216:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4217:     $iterator->next(); # skip the first BEGIN_MAP
                   4218:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4219:     while ($depth > 0) {
1.68      ng       4220:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4221:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4222: 
1.385     albertel 4223:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4224: 	    my $parts = $curRes->parts();
1.68      ng       4225:             my $title = $curRes->compTitle();
1.71      ng       4226: 	    my $symbx = $curRes->symb();
1.196     albertel 4227: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4228: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4229: 	    $studentTable.='<td valign="top">';
1.382     albertel 4230: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4231: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4232: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4233: 					     undef,'both',\%form);
1.71      ng       4234: 	    } else {
1.382     albertel 4235: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4236: 		$companswer =~ s|<form(.*?)>||g;
                   4237: 		$companswer =~ s|</form>||g;
1.71      ng       4238: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4239: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4240: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4241: #		}
1.116     ng       4242: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4243: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4244: 	    }
                   4245: 
1.257     albertel 4246: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4247: 
1.257     albertel 4248: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4249: 		if ($record{'version'} eq '') {
1.398     albertel 4250: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4251: 		} else {
1.116     ng       4252: 		    my %responseType = ();
                   4253: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4254: 			my @responseIds =$curRes->responseIds($partid);
                   4255: 			my @responseType =$curRes->responseType($partid);
                   4256: 			my %responseIds;
                   4257: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4258: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4259: 			}
                   4260: 			$responseType{$partid} = \%responseIds;
1.116     ng       4261: 		    }
1.148     albertel 4262: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4263: 
1.71      ng       4264: 		}
1.257     albertel 4265: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4266: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4267: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4268: 									$env{'request.course.id'},
1.71      ng       4269: 									'','.submission');
                   4270:  
                   4271: 	    }
1.103     albertel 4272: 	    if (&canmodify($usec)) {
                   4273: 		foreach my $partid (@{$parts}) {
                   4274: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4275: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4276: 		    $question++;
                   4277: 		}
1.196     albertel 4278: 		$prob++;
1.71      ng       4279: 	    }
                   4280: 	    $studentTable.='</td></tr>';
1.68      ng       4281: 
1.103     albertel 4282: 	}
1.68      ng       4283:         $curRes = $iterator->next();
                   4284:     }
                   4285: 
1.381     albertel 4286:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4287: 	'<input type="button" value="Save" '.
1.381     albertel 4288: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4289: 	'</form>'."\n";
1.324     albertel 4290:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4291:     $request->print($studentTable);
                   4292: 
                   4293:     return '';
1.119     ng       4294: }
                   4295: 
                   4296: sub displaySubByDates {
1.148     albertel 4297:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4298:     my $isCODE=0;
1.335     albertel 4299:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4300:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4301:     my $studentTable=&Apache::loncommon::start_data_table().
                   4302: 	&Apache::loncommon::start_data_table_header_row().
                   4303: 	'<th>'.&mt('Date/Time').'</th>'.
                   4304: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4305: 	'<th>'.&mt('Submission').'</th>'.
                   4306: 	'<th>'.&mt('Status').'</th>'.
                   4307: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4308:     my ($version);
                   4309:     my %mark;
1.148     albertel 4310:     my %orders;
1.119     ng       4311:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4312:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4313: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4314:     }
1.335     albertel 4315: 
                   4316:     my $interaction;
1.119     ng       4317:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4318: 	my $timestamp = 
                   4319: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4320: 	if (exists($$record{$version.':resource.0.version'})) {
                   4321: 	    $interaction = $$record{$version.':resource.0.version'};
                   4322: 	}
                   4323: 
                   4324: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4325: 		             : "$version:resource");
1.467     albertel 4326: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4327: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4328: 	if ($isCODE) {
                   4329: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4330: 	}
1.119     ng       4331: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4332: 	my @displaySub = ();
                   4333: 	foreach my $partid (@{$parts}) {
1.335     albertel 4334: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4335: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4336: 	    
                   4337: 
1.122     ng       4338: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4339: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4340: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4341: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4342: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4343: 
                   4344: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4345: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4346: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4347: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4348: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4349: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4350: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4351: 		    } else {
1.467     albertel 4352: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4353: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4354: 		    }
1.335     albertel 4355: 		    my $responseType=($isTask ? 'Task'
                   4356:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4357: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4358: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4359: 			$orders{$partid}->{$responseId}=
                   4360: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4361: 		    }
1.147     albertel 4362: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4363: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4364: 		}
                   4365: 	    }
1.335     albertel 4366: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4367: 		$displaySub[1].='Checked in by '.
                   4368: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4369: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4370: 		    '<br />';
                   4371: 	    }
                   4372: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4373: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4374: 		    lc($$record{"$where.$partid.award"}).' '.
                   4375: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4376: 		    '<br />';
                   4377: 	    }
1.335     albertel 4378: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4379: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4380: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4381: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4382: 		$displaySub[2].=
                   4383: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4384: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4385: 	    }
                   4386: 	}
                   4387: 	# needed because old essay regrader has not parts info
                   4388: 	if (exists $$record{"$version:resource.regrader"}) {
                   4389: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4390: 	}
                   4391: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4392: 	if ($displaySub[2]) {
1.467     albertel 4393: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4394: 	}
1.467     albertel 4395: 	$studentTable.='&nbsp;</td>'.
                   4396: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4397:     }
1.467     albertel 4398:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4399:     return $studentTable;
1.71      ng       4400: }
                   4401: 
                   4402: sub updateGradeByPage {
                   4403:     my ($request) = shift;
                   4404: 
1.257     albertel 4405:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4406:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4407:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4408:     my $pageTitle = $env{'form.page'};
1.103     albertel 4409:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4410:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4411:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4412:     if (!&canmodify($usec)) {
1.398     albertel 4413: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4414: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4415: 	return;
                   4416:     }
1.398     albertel 4417:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4418:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4419: 	'</h3>'."\n";
1.70      ng       4420: 
1.68      ng       4421:     $request->print($result);
                   4422: 
1.132     bowersj2 4423:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4424:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4425:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4426:     if (!$map) {
1.398     albertel 4427: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4428: 	my ($symb)=&get_symb($request);
                   4429: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4430: 	return; 
                   4431:     }
1.71      ng       4432:     my $iterator = $navmap->getIterator($map->map_start(),
                   4433: 					$map->map_finish());
1.70      ng       4434: 
1.71      ng       4435:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4436: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4437: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4438: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4439: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4440: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4441: 
                   4442:     $iterator->next(); # skip the first BEGIN_MAP
                   4443:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4444:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4445:     while ($depth > 0) {
1.71      ng       4446:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4447:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4448: 
1.385     albertel 4449:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4450: 	    my $parts = $curRes->parts();
1.71      ng       4451:             my $title = $curRes->compTitle();
                   4452: 	    my $symbx = $curRes->symb();
1.196     albertel 4453: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4454: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4455: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4456: 
                   4457: 	    my %newrecord=();
                   4458: 	    my @displayPts=();
1.269     raeburn  4459:             my %aggregate = ();
                   4460:             my $aggregateflag = 0;
1.71      ng       4461: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4462: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4463: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4464: 
1.257     albertel 4465: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4466: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4467: 		my $partial = $newpts/$wgt;
                   4468: 		my $score;
                   4469: 		if ($partial > 0) {
                   4470: 		    $score = 'correct_by_override';
1.125     ng       4471: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4472: 		    $score = 'incorrect_by_override';
                   4473: 		}
1.257     albertel 4474: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4475: 		if ($dropMenu eq 'excused') {
1.71      ng       4476: 		    $partial = '';
                   4477: 		    $score = 'excused';
1.125     ng       4478: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4479: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4480: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4481: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4482: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4483: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4484: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4485: 		    $changeflag++;
                   4486: 		    $newpts = '';
1.269     raeburn  4487:                     
                   4488:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4489:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4490:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4491:                     if ($aggtries > 0) {
                   4492:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4493:                         $aggregateflag = 1;
                   4494:                     }
1.71      ng       4495: 		}
1.324     albertel 4496: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4497: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4498: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4499: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4500: 		    '&nbsp;<br />';
1.207     albertel 4501: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4502: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4503: 		    '&nbsp;<br />';
1.71      ng       4504: 		$question++;
1.380     albertel 4505: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4506: 
1.71      ng       4507: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4508: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4509: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4510: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4511: 
                   4512: 		$changeflag++;
                   4513: 	    }
                   4514: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4515: 		my %record = 
                   4516: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4517: 					     $udom,$uname);
                   4518: 
                   4519: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4520: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4521: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4522: 		    $newrecord{'resource.CODE'} = '';
                   4523: 		}
1.257     albertel 4524: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4525: 					$udom,$uname);
1.382     albertel 4526: 		%record = &Apache::lonnet::restore($symbx,
                   4527: 						   $env{'request.course.id'},
                   4528: 						   $udom,$uname);
1.380     albertel 4529: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4530: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4531: 	    }
1.380     albertel 4532: 	    
1.269     raeburn  4533:             if ($aggregateflag) {
                   4534:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4535:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4536:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4537:             }
1.125     ng       4538: 
1.71      ng       4539: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4540: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4541: 		'</tr>';
1.68      ng       4542: 
1.196     albertel 4543: 	    $prob++;
1.68      ng       4544: 	}
1.71      ng       4545:         $curRes = $iterator->next();
1.68      ng       4546:     }
1.98      albertel 4547: 
1.71      ng       4548:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4549:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4550:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4551: 		  'The scores were changed for '.
                   4552: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4553:     $request->print($grademsg.$studentTable);
1.68      ng       4554: 
1.70      ng       4555:     return '';
                   4556: }
                   4557: 
1.72      ng       4558: #-------- end of section for handling grading by page/sequence ---------
                   4559: #
                   4560: #-------------------------------------------------------------------
                   4561: 
1.75      albertel 4562: #--------------------Scantron Grading-----------------------------------
                   4563: #
                   4564: #------ start of section for handling grading by page/sequence ---------
                   4565: 
1.423     albertel 4566: =pod
                   4567: 
                   4568: =head1 Bubble sheet grading routines
                   4569: 
1.424     albertel 4570:   For this documentation:
                   4571: 
                   4572:    'scanline' refers to the full line of characters
                   4573:    from the file that we are parsing that represents one entire sheet
                   4574: 
                   4575:    'bubble line' refers to the data
                   4576:    representing the line of bubbles that are on the physical bubble sheet
                   4577: 
                   4578: 
                   4579: The overall process is that a scanned in bubble sheet data is uploaded
                   4580: into a course. When a user wants to grade, they select a
                   4581: sequence/folder of resources, a file of bubble sheet info, and pick
                   4582: one of the predefined configurations for what each scanline looks
                   4583: like.
                   4584: 
                   4585: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4586: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4587: because too light bubbling), 'double bubble' (each bubble line should
                   4588: have no more that one letter picked), invalid or duplicated CODE,
                   4589: invalid student ID
                   4590: 
                   4591: If the CODE option is used that determines the randomization of the
                   4592: homework problems, either way the student ID is looked up into a
                   4593: username:domain.
                   4594: 
                   4595: During the validation phase the instructor can choose to skip scanlines. 
                   4596: 
1.435     foxr     4597: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4598: 
                   4599:   scantron_original_filename (unmodified original file)
                   4600:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4601:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4602: 
                   4603: Also there is a separate hash nohist_scantrondata that contains extra
                   4604: correction information that isn't representable in the bubble sheet
                   4605: file (see &scantron_getfile() for more information)
                   4606: 
                   4607: After all scanlines are either valid, marked as valid or skipped, then
                   4608: foreach line foreach problem in the picked sequence, an ssi request is
                   4609: made that simulates a user submitting their selected letter(s) against
                   4610: the homework problem.
1.423     albertel 4611: 
                   4612: =over 4
                   4613: 
                   4614: 
                   4615: 
                   4616: =item defaultFormData
                   4617: 
                   4618:   Returns html hidden inputs used to hold context/default values.
                   4619: 
                   4620:  Arguments:
                   4621:   $symb - $symb of the current resource 
                   4622: 
                   4623: =cut
1.422     foxr     4624: 
1.81      albertel 4625: sub defaultFormData {
1.324     albertel 4626:     my ($symb)=@_;
1.447     foxr     4627:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4628:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4629:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4630: }
                   4631: 
1.447     foxr     4632: 
1.423     albertel 4633: =pod 
                   4634: 
                   4635: =item getSequenceDropDown
                   4636: 
                   4637:    Return html dropdown of possible sequences to grade
                   4638:  
                   4639:  Arguments:
                   4640:    $symb - $symb of the current resource 
                   4641: 
                   4642: =cut
1.422     foxr     4643: 
1.75      albertel 4644: sub getSequenceDropDown {
1.423     albertel 4645:     my ($symb)=@_;
1.75      albertel 4646:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4647:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4648:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4649:     my $ctr=0;
                   4650:     foreach (@$titles) {
                   4651: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4652: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4653: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4654: 	    '>'.$showtitle.'</option>'."\n";
                   4655: 	$ctr++;
                   4656:     }
                   4657:     $result.= '</select>';
                   4658:     return $result;
                   4659: }
                   4660: 
1.423     albertel 4661: 
                   4662: =pod 
                   4663: 
                   4664: =item scantron_filenames
                   4665: 
                   4666:    Returns a list of the scantron files in the current course 
                   4667: 
                   4668: =cut
1.422     foxr     4669: 
1.202     albertel 4670: sub scantron_filenames {
1.257     albertel 4671:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4672:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4673:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4674: 				    &propath($cdom,$cname));
1.202     albertel 4675:     my @possiblenames;
1.201     albertel 4676:     foreach my $filename (sort(@files)) {
1.157     albertel 4677: 	($filename)=split(/&/,$filename);
                   4678: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4679: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4680: 	push(@possiblenames,$filename);
                   4681:     }
                   4682:     return @possiblenames;
                   4683: }
                   4684: 
1.423     albertel 4685: =pod 
                   4686: 
                   4687: =item scantron_uploads
                   4688: 
                   4689:    Returns  html drop-down list of scantron files in current course.
                   4690: 
                   4691:  Arguments:
                   4692:    $file2grade - filename to set as selected in the dropdown
                   4693: 
                   4694: =cut
1.422     foxr     4695: 
1.202     albertel 4696: sub scantron_uploads {
1.209     ng       4697:     my ($file2grade) = @_;
1.202     albertel 4698:     my $result=	'<select name="scantron_selectfile">';
                   4699:     $result.="<option></option>";
                   4700:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4701: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4702:     }
                   4703:     $result.="</select>";
                   4704:     return $result;
                   4705: }
                   4706: 
1.423     albertel 4707: =pod 
                   4708: 
                   4709: =item scantron_scantab
                   4710: 
                   4711:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4712:   file.
                   4713: 
                   4714: =cut
1.422     foxr     4715: 
1.82      albertel 4716: sub scantron_scantab {
                   4717:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4718:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4719:     $result.='<option></option>'."\n";
1.82      albertel 4720:     foreach my $line (<$fh>) {
                   4721: 	my ($name,$descrip)=split(/:/,$line);
                   4722: 	if ($name =~ /^\#/) { next; }
                   4723: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4724:     }
                   4725:     $result.='</select>'."\n";
                   4726: 
                   4727:     return $result;
                   4728: }
                   4729: 
1.423     albertel 4730: =pod 
                   4731: 
                   4732: =item scantron_CODElist
                   4733: 
                   4734:   Returns html drop down of the saved CODE lists from current course,
                   4735:   generated from earlier printings.
                   4736: 
                   4737: =cut
1.422     foxr     4738: 
1.186     albertel 4739: sub scantron_CODElist {
1.257     albertel 4740:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4741:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4742:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4743:     my $namechoice='<option></option>';
1.225     albertel 4744:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4745: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4746: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4747: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4748:     }
                   4749:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4750:     return $namechoice;
                   4751: }
                   4752: 
1.423     albertel 4753: =pod 
                   4754: 
                   4755: =item scantron_CODEunique
                   4756: 
                   4757:   Returns the html for "Each CODE to be used once" radio.
                   4758: 
                   4759: =cut
1.422     foxr     4760: 
1.186     albertel 4761: sub scantron_CODEunique {
1.381     albertel 4762:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4763:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4764:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4765:                 </span>
                   4766:                 <span style="white-space: nowrap;">
1.272     albertel 4767:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4768:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4769:                 </span>';
1.186     albertel 4770:     return $result;
                   4771: }
1.423     albertel 4772: 
                   4773: =pod 
                   4774: 
                   4775: =item scantron_selectphase
                   4776: 
                   4777:   Generates the initial screen to start the bubble sheet process.
                   4778:   Allows for - starting a grading run.
1.424     albertel 4779:              - downloading existing scan data (original, corrected
1.423     albertel 4780:                                                 or skipped info)
                   4781: 
                   4782:              - uploading new scan data
                   4783: 
                   4784:  Arguments:
                   4785:   $r          - The Apache request object
                   4786:   $file2grade - name of the file that contain the scanned data to score
                   4787: 
                   4788: =cut
1.186     albertel 4789: 
1.75      albertel 4790: sub scantron_selectphase {
1.209     ng       4791:     my ($r,$file2grade) = @_;
1.324     albertel 4792:     my ($symb)=&get_symb($r);
1.75      albertel 4793:     if (!$symb) {return '';}
1.423     albertel 4794:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4795:     my $default_form_data=&defaultFormData($symb);
                   4796:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4797:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4798:     my $format_selector=&scantron_scantab();
1.186     albertel 4799:     my $CODE_selector=&scantron_CODElist();
                   4800:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4801:     my $result;
1.422     foxr     4802: 
                   4803:     # Chunk of form to prompt for a file to grade and how:
                   4804: 
1.75      albertel 4805:     $result.= <<SCANTRONFORM;
1.162     albertel 4806:     <table width="100%" border="0">
1.75      albertel 4807:     <tr>
1.226     albertel 4808:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4809:       <td bgcolor="#777777">
1.203     albertel 4810:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4811:         $default_form_data
1.75      albertel 4812:         <table width="100%" border="0">
                   4813:           <tr bgcolor="#e6ffff">
1.174     albertel 4814:             <td colspan="2">
                   4815:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4816:             </td>
                   4817:           </tr>
                   4818:           <tr bgcolor="#ffffe6">
1.174     albertel 4819:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4820:           </tr>
                   4821:           <tr bgcolor="#ffffe6">
1.174     albertel 4822:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4823:           </tr>
1.82      albertel 4824:           <tr bgcolor="#ffffe6">
1.174     albertel 4825:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4826:           </tr>
1.157     albertel 4827:           <tr bgcolor="#ffffe6">
1.186     albertel 4828:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4829:           </tr>
                   4830:           <tr bgcolor="#ffffe6">
                   4831:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4832:           </tr>
                   4833:           <tr bgcolor="#ffffe6">
1.187     albertel 4834: 	    <td> Options: </td>
                   4835:             <td>
1.272     albertel 4836: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4837:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4838:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4839: 	    </td>
                   4840:           </tr>
                   4841:           <tr bgcolor="#ffffe6">
1.174     albertel 4842:             <td colspan="2">
1.265     www      4843:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4844:             </td>
                   4845:           </tr>
                   4846:         </table>
1.226     albertel 4847:        </td>
                   4848:      </form>
1.162     albertel 4849:     </tr>
                   4850: SCANTRONFORM
                   4851:    
                   4852:     $r->print($result);
                   4853: 
1.257     albertel 4854:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4855:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4856: 
1.422     foxr     4857: 	# Chunk of form to prompt for a scantron file upload.
                   4858: 
1.162     albertel 4859:         $r->print(<<SCANTRONFORM);
                   4860:     <tr>
                   4861:       <td bgcolor="#777777">
                   4862:         <table width="100%" border="0">
                   4863:           <tr bgcolor="#e6ffff">
                   4864:             <td>
1.174     albertel 4865:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4866:             </td>
                   4867:           </tr>
                   4868:           <tr bgcolor="#ffffe6">
                   4869:             <td>
                   4870: SCANTRONFORM
1.324     albertel 4871:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4872:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4873:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4874:     $r->print(<<UPLOAD);
                   4875:               <script type="text/javascript" language="javascript">
                   4876:     function checkUpload(formname) {
                   4877: 	if (formname.upfile.value == "") {
                   4878: 	    alert("Please use the browse button to select a file from your local directory.");
                   4879: 	    return false;
                   4880: 	}
                   4881: 	formname.submit();
                   4882:     }
                   4883:               </script>
                   4884: 
                   4885:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4886:                 $default_form_data
                   4887:                 <input name='courseid' type='hidden' value='$cnum' />
                   4888:                 <input name='domainid' type='hidden' value='$cdom' />
                   4889:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4890:                 File to upload:<input type="file" name="upfile" size="50" />
                   4891:                 <br />
                   4892:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4893:               </form>
                   4894: UPLOAD
1.162     albertel 4895: 
                   4896:         $r->print(<<SCANTRONFORM);
                   4897:             </td>
                   4898:           </tr>
1.75      albertel 4899:         </table>
                   4900:       </td>
                   4901:     </tr>
1.162     albertel 4902: SCANTRONFORM
                   4903:     }
1.422     foxr     4904: 
                   4905:     # Chunk of the form that prompts to view a scoring office file,
                   4906:     # corrected file, skipped records in a file.
                   4907: 
1.187     albertel 4908:     $r->print(<<SCANTRONFORM);
                   4909:     <tr>
1.226     albertel 4910:       <form action='/adm/grades' name='scantron_download'>
                   4911:         <td bgcolor="#777777">
1.379     albertel 4912: 	  $default_form_data
1.187     albertel 4913:           <input type="hidden" name="command" value="scantron_download" />
                   4914:           <table width="100%" border="0">
                   4915:             <tr bgcolor="#e6ffff">
                   4916:               <td colspan="2">
                   4917:                 &nbsp;<b>Download a scoring office file</b>
                   4918:               </td>
                   4919:             </tr>
                   4920:             <tr bgcolor="#ffffe6">
                   4921:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4922:             </tr>
                   4923:             <tr bgcolor="#ffffe6">
                   4924:               <td colspan="2">
1.293     www      4925:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4926:               </td>
                   4927:             </tr>
                   4928:           </table>
1.226     albertel 4929:         </td>
                   4930:       </form>
1.187     albertel 4931:     </tr>
                   4932: SCANTRONFORM
1.162     albertel 4933: 
1.457     banghart 4934:     $r->print('<tr><td bgcolor="#777777">');
                   4935:     &Apache::lonpickcode::code_list($r,2);
                   4936:     $r->print('</td></tr></table>');
                   4937:     $r->print($grading_menu_button);
1.162     albertel 4938:     return
1.75      albertel 4939: }
                   4940: 
1.423     albertel 4941: =pod
                   4942: 
                   4943: =item get_scantron_config
                   4944: 
                   4945:    Parse and return the scantron configuration line selected as a
                   4946:    hash of configuration file fields.
                   4947: 
                   4948:  Arguments:
                   4949:     which - the name of the configuration to parse from the file.
                   4950: 
                   4951: 
                   4952:  Returns:
                   4953:             If the named configuration is not in the file, an empty
                   4954:             hash is returned.
                   4955:     a hash with the fields
                   4956:       name         - internal name for the this configuration setup
                   4957:       description  - text to display to operator that describes this config
                   4958:       CODElocation - if 0 or the string 'none'
                   4959:                           - no CODE exists for this config
                   4960:                      if -1 || the string 'letter'
                   4961:                           - a CODE exists for this config and is
                   4962:                             a string of letters
                   4963:                      Unsupported value (but planned for future support)
                   4964:                           if a positive integer
                   4965:                                - The CODE exists as the first n items from
                   4966:                                  the question section of the form
                   4967:                           if the string 'number'
                   4968:                                - The CODE exists for this config and is
                   4969:                                  a string of numbers
                   4970:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4971:                      the CODE starts
                   4972:       CODElength  - length of the CODE
                   4973:       IDstart     - column where the student ID number starts
                   4974:       IDlength    - length of the student ID info
                   4975:       Qstart      - column where the information from the bubbled
                   4976:                     'questions' start
                   4977:       Qlength     - number of columns comprising a single bubble line from
                   4978:                     the sheet. (usually either 1 or 10)
1.424     albertel 4979:       Qon         - either a single character representing the character used
1.423     albertel 4980:                     to signal a bubble was chosen in the positional setup, or
                   4981:                     the string 'letter' if the letter of the chosen bubble is
                   4982:                     in the final, or 'number' if a number representing the
                   4983:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4984:       Qoff        - the character used to represent that a bubble was
                   4985:                     left blank
1.423     albertel 4986:       PaperID     - if the scanning process generates a unique number for each
                   4987:                     sheet scanned the column that this ID number starts in
                   4988:       PaperIDlength - number of columns that comprise the unique ID number
                   4989:                       for the sheet of paper
1.424     albertel 4990:       FirstName   - column that the first name starts in
1.423     albertel 4991:       FirstNameLength - number of columns that the first name spans
                   4992:  
                   4993:       LastName    - column that the last name starts in
                   4994:       LastNameLength - number of columns that the last name spans
                   4995: 
                   4996: =cut
1.422     foxr     4997: 
1.82      albertel 4998: sub get_scantron_config {
                   4999:     my ($which) = @_;
                   5000:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5001:     my %config;
1.157     albertel 5002:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5003:     foreach my $line (<$fh>) {
                   5004: 	my ($name,$descrip)=split(/:/,$line);
                   5005: 	if ($name ne $which ) { next; }
                   5006: 	chomp($line);
                   5007: 	my @config=split(/:/,$line);
                   5008: 	$config{'name'}=$config[0];
                   5009: 	$config{'description'}=$config[1];
                   5010: 	$config{'CODElocation'}=$config[2];
                   5011: 	$config{'CODEstart'}=$config[3];
                   5012: 	$config{'CODElength'}=$config[4];
                   5013: 	$config{'IDstart'}=$config[5];
                   5014: 	$config{'IDlength'}=$config[6];
                   5015: 	$config{'Qstart'}=$config[7];
                   5016: 	$config{'Qlength'}=$config[8];
                   5017: 	$config{'Qoff'}=$config[9];
                   5018: 	$config{'Qon'}=$config[10];
1.157     albertel 5019: 	$config{'PaperID'}=$config[11];
                   5020: 	$config{'PaperIDlength'}=$config[12];
                   5021: 	$config{'FirstName'}=$config[13];
                   5022: 	$config{'FirstNamelength'}=$config[14];
                   5023: 	$config{'LastName'}=$config[15];
                   5024: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5025: 	last;
                   5026:     }
                   5027:     return %config;
                   5028: }
                   5029: 
1.423     albertel 5030: =pod 
                   5031: 
                   5032: =item username_to_idmap
                   5033: 
                   5034:     creates a hash keyed by student id with values of the corresponding
                   5035:     student username:domain.
                   5036: 
                   5037:   Arguments:
                   5038: 
                   5039:     $classlist - reference to the class list hash. This is a hash
                   5040:                  keyed by student name:domain  whose elements are references
1.424     albertel 5041:                  to arrays containing various chunks of information
1.423     albertel 5042:                  about the student. (See loncoursedata for more info).
                   5043: 
                   5044:   Returns
                   5045:     %idmap - the constructed hash
                   5046: 
                   5047: =cut
                   5048: 
1.82      albertel 5049: sub username_to_idmap {
                   5050:     my ($classlist)= @_;
                   5051:     my %idmap;
                   5052:     foreach my $student (keys(%$classlist)) {
                   5053: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5054: 	    $student;
                   5055:     }
                   5056:     return %idmap;
                   5057: }
1.423     albertel 5058: 
                   5059: =pod
                   5060: 
1.424     albertel 5061: =item scantron_fixup_scanline
1.423     albertel 5062: 
                   5063:    Process a requested correction to a scanline.
                   5064: 
                   5065:   Arguments:
                   5066:     $scantron_config   - hash from &get_scantron_config()
                   5067:     $scan_data         - hash of correction information 
                   5068:                           (see &scantron_getfile())
                   5069:     $line              - existing scanline
                   5070:     $whichline         - line number of the passed in scanline
                   5071:     $field             - type of change to process 
                   5072:                          (either 
                   5073:                           'ID'     -> correct the student ID number
                   5074:                           'CODE'   -> correct the CODE
                   5075:                           'answer' -> fixup the submitted answers)
                   5076:     
                   5077:    $args               - hash of additional info,
                   5078:                           - 'ID' 
                   5079:                                'newid' -> studentID to use in replacement
1.424     albertel 5080:                                           of existing one
1.423     albertel 5081:                           - 'CODE' 
                   5082:                                'CODE_ignore_dup' - set to true if duplicates
                   5083:                                                    should be ignored.
                   5084: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5085:                                         if the existing unfound code should
1.423     albertel 5086:                                         be used as is
                   5087:                           - 'answer'
                   5088:                                'response' - new answer or 'none' if blank
                   5089:                                'question' - the bubble line to change
                   5090: 
                   5091:   Returns:
                   5092:     $line - the modified scanline
                   5093: 
                   5094:   Side effects: 
                   5095:     $scan_data - may be updated
                   5096: 
                   5097: =cut
                   5098: 
1.82      albertel 5099: 
1.157     albertel 5100: sub scantron_fixup_scanline {
                   5101:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5102: 
1.157     albertel 5103:     if ($field eq 'ID') {
                   5104: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5105: 	    return ($line,1,'New value too large');
1.157     albertel 5106: 	}
                   5107: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5108: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5109: 				     $args->{'newid'});
                   5110: 	}
                   5111: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5112: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5113: 	if ($args->{'newid'}=~/^\s*$/) {
                   5114: 	    &scan_data($scan_data,"$whichline.user",
                   5115: 		       $args->{'username'}.':'.$args->{'domain'});
                   5116: 	}
1.186     albertel 5117:     } elsif ($field eq 'CODE') {
1.192     albertel 5118: 	if ($args->{'CODE_ignore_dup'}) {
                   5119: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5120: 	}
                   5121: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5122: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5123: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5124: 		return ($line,1,'New CODE value too large');
                   5125: 	    }
                   5126: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5127: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5128: 	    }
                   5129: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5130: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5131: 	}
1.157     albertel 5132:     } elsif ($field eq 'answer') {
                   5133: 	my $length=$scantron_config->{'Qlength'};
                   5134: 	my $off=$scantron_config->{'Qoff'};
                   5135: 	my $on=$scantron_config->{'Qon'};
                   5136: 	my $answer=${off}x$length;
                   5137: 	if ($args->{'response'} eq 'none') {
                   5138: 	    &scan_data($scan_data,
                   5139: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5140: 	} else {
1.274     albertel 5141: 	    if ($on eq 'letter') {
                   5142: 		my @alphabet=('A'..'Z');
                   5143: 		$answer=$alphabet[$args->{'response'}];
                   5144: 	    } elsif ($on eq 'number') {
                   5145: 		$answer=$args->{'response'}+1;
1.389     albertel 5146: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5147: 	    } else {
                   5148: 		substr($answer,$args->{'response'},1)=$on;
                   5149: 	    }
1.157     albertel 5150: 	    &scan_data($scan_data,
                   5151: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5152: 	}
                   5153: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5154: 	substr($line,$where-1,$length)=$answer;
                   5155:     }
                   5156:     return $line;
                   5157: }
1.423     albertel 5158: 
                   5159: =pod
                   5160: 
                   5161: =item scan_data
                   5162: 
                   5163:     Edit or look up  an item in the scan_data hash.
                   5164: 
                   5165:   Arguments:
                   5166:     $scan_data  - The hash (see scantron_getfile)
                   5167:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5168:                   scantronfilename_key).
1.423     albertel 5169:     $data        - New value of the hash entry.
                   5170:     $delete      - If true, the entry is removed from the hash.
                   5171: 
                   5172:   Returns:
                   5173:     The new value of the hash table field (undefined if deleted).
                   5174: 
                   5175: =cut
                   5176: 
                   5177: 
1.157     albertel 5178: sub scan_data {
                   5179:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5180:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5181:     if (defined($value)) {
                   5182: 	$scan_data->{$filename.'_'.$key} = $value;
                   5183:     }
                   5184:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5185:     return $scan_data->{$filename.'_'.$key};
                   5186: }
1.423     albertel 5187: 
                   5188: =pod 
                   5189: 
                   5190: =item scantron_parse_scanline
                   5191: 
                   5192:   Decodes a scanline from the selected scantron file
                   5193: 
                   5194:  Arguments:
                   5195:     line             - The text of the scantron file line to process
                   5196:     whichline        - Line number
                   5197:     scantron_config  - Hash describing the format of the scantron lines.
                   5198:     scan_data        - Hash of extra information about the scanline
                   5199:                        (see scantron_getfile for more information)
                   5200:     just_header      - True if should not process question answers but only
                   5201:                        the stuff to the left of the answers.
                   5202:  Returns:
                   5203:    Hash containing the result of parsing the scanline
                   5204: 
                   5205:    Keys are all proceeded by the string 'scantron.'
                   5206: 
                   5207:        CODE    - the CODE in use for this scanline
                   5208:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5209:                  by the operator
                   5210:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5211:                             CODEs were selected, but the usage has been
                   5212:                             forced by the operator
                   5213:        ID  - student ID
                   5214:        PaperID - if used, the ID number printed on the sheet when the 
                   5215:                  paper was scanned
                   5216:        FirstName - first name from the sheet
                   5217:        LastName  - last name from the sheet
                   5218: 
                   5219:      if just_header was not true these key may also exist
                   5220: 
1.447     foxr     5221:        missingerror - a list of bubble ranges that are considered to be answers
                   5222:                       to a single question that don't have any bubbles filled in.
                   5223:                       Of the form questionnumber:firstbubblenumber:count.
                   5224:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5225:                       to a single question that have more than one bubble filled in.
                   5226:                       Of the form questionnumber::firstbubblenumber:count
                   5227:    
                   5228:                 In the above, count is the number of bubble responses in the
                   5229:                 input line needed to represent the possible answers to the question.
                   5230:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5231:                 per line would have count = 2.
                   5232: 
1.423     albertel 5233:        maxquest     - the number of the last bubble line that was parsed
                   5234: 
                   5235:        (<number> starts at 1)
                   5236:        <number>.answer - zero or more letters representing the selected
                   5237:                          letters from the scanline for the bubble line 
                   5238:                          <number>.
                   5239:                          if blank there was either no bubble or there where
                   5240:                          multiple bubbles, (consult the keys missingerror and
                   5241:                          doubleerror if this is an error condition)
                   5242: 
                   5243: =cut
                   5244: 
1.82      albertel 5245: sub scantron_parse_scanline {
1.423     albertel 5246:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5247: 
1.82      albertel 5248:     my %record;
1.422     foxr     5249:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5250:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5251:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5252: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5253: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5254: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5255: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5256: 	    $record{'scantron.CODE'}=substr($data,
                   5257: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5258: 					    $$scantron_config{'CODElength'});
1.191     albertel 5259: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5260: 		$record{'scantron.useCODE'}=1;
                   5261: 	    }
1.192     albertel 5262: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5263: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5264: 	    }
1.82      albertel 5265: 	} else {
                   5266: 	    #FIXME interpret first N questions
                   5267: 	}
                   5268:     }
1.83      albertel 5269:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5270: 				  $$scantron_config{'IDlength'});
1.157     albertel 5271:     $record{'scantron.PaperID'}=
                   5272: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5273: 	       $$scantron_config{'PaperIDlength'});
                   5274:     $record{'scantron.FirstName'}=
                   5275: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5276: 	       $$scantron_config{'FirstNamelength'});
                   5277:     $record{'scantron.LastName'}=
                   5278: 	substr($data,$$scantron_config{'LastName'}-1,
                   5279: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5280:     if ($just_header) { return \%record; }
1.194     albertel 5281: 
1.82      albertel 5282:     my @alphabet=('A'..'Z');
                   5283:     my $questnum=0;
1.447     foxr     5284:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5285: 
1.470     foxr     5286:     chomp($questions);		# Get rid of any trailing \n.
                   5287:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5288:     while (length($questions)) {
1.447     foxr     5289: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5290: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5291: 
                   5292: 
                   5293: 
1.82      albertel 5294: 	$questnum++;
1.447     foxr     5295: 	my $currentquest = substr($questions,0,$answer_length);
                   5296: 	$questions       = substr($questions,0,$answer_length)='';
                   5297: 	if (length($currentquest) < $answer_length) { next; }
                   5298: 
                   5299: 	# Qon letter implies for each slot in currentquest we have:
                   5300: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5301:         #    about anything else (esp. a value of Qoff for missing
                   5302: 	#    bubbles.
                   5303: 
                   5304: 
1.239     albertel 5305: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5306: 
                   5307: 	    if ($currentquest =~ /\?/
                   5308: 		|| $currentquest =~ /\*/
                   5309: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5310: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5311: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5312: 		    my $bubble = substr($currentquest, $ans, 1);
                   5313: 		    if ($bubble =~ /[A-Z]/ ) {
                   5314: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5315: 		    } else {
                   5316: 			$record{"scantron.$ansnum.answer"}='';
                   5317: 		    }
1.447     foxr     5318: 		    $ansnum++;
                   5319: 		}
                   5320: 
1.389     albertel 5321: 	    } elsif (!defined($currentquest)
1.447     foxr     5322: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5323: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5324: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5325: 		    $record{"scantron.$ansnum.answer"}='';
                   5326: 		    $ansnum++;
                   5327: 
                   5328: 		}
1.239     albertel 5329: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5330: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5331: 		   #  $ansnum += $answers_needed;
1.239     albertel 5332: 		}
                   5333: 	    } else {
1.447     foxr     5334: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5335: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5336: 		    $ansnum++;
                   5337: 		}
1.239     albertel 5338: 	    }
1.447     foxr     5339: 
                   5340: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5341: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5342:         #    and *? for double bubbles on a line.
                   5343: 	#    these answers are also stored as letters.
                   5344: 
1.239     albertel 5345: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5346: 	    if ($currentquest =~ /\?/
                   5347: 		|| $currentquest =~ /\*/
                   5348: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5349: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5350: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5351: 		    my $bubble = substr($currentquest, $ans, 1);
                   5352: 		    if ($bubble =~ /\d/) {
                   5353: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5354: 		    } else {
1.461     foxr     5355: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5356: 		    }
1.447     foxr     5357: 		    $ansnum++;
                   5358: 		}
                   5359: 
1.389     albertel 5360: 	    } elsif (!defined($currentquest)
1.447     foxr     5361: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5362: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5363: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5364: 		    $record{"scantron.$ansnum.answer"}='';
                   5365: 		    $ansnum++;
                   5366: 
                   5367: 		}
1.239     albertel 5368: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5369: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5370: 		    $ansnum += $answers_needed;
1.239     albertel 5371: 		}
1.447     foxr     5372: 
1.239     albertel 5373: 	    } else {
1.447     foxr     5374: 		$currentquest = &digits_to_letters($currentquest);
                   5375: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5376: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5377: 		    $ansnum++;
1.371     albertel 5378: 		}
1.239     albertel 5379: 	    }
1.82      albertel 5380: 	} else {
1.447     foxr     5381: 
                   5382: 	    # Otherwise there's a positional notation;
                   5383: 	    # each bubble line requires Qlength items, and there are filled in
                   5384: 	    # bubbles for each case where there 'Qon' characters.
                   5385: 	    #
                   5386: 
1.239     albertel 5387: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5388: 
                   5389: 	    # If the split only  giveas us one element.. the full length of the
                   5390: 	    # answser string, no bubbles are filled in:
                   5391: 
                   5392: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5393: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5394: 		    $record{"scantron.$ansnum.answer"}='';
                   5395: 		    $ansnum++;
                   5396: 
                   5397: 		}
1.239     albertel 5398: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5399: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5400: 		}
1.447     foxr     5401: 	    } elsif (scalar(@array) lt 2) {
                   5402: 
1.459     foxr     5403: 		my $location      = length($array[0]);
1.447     foxr     5404: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5405: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5406: 
                   5407: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5408: 		    if ($ans eq $line_num) {
                   5409: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5410: 		    } else {
                   5411: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5412: 		    }
                   5413: 		    $ansnum++;
                   5414: 		}
1.239     albertel 5415: 	    }
1.447     foxr     5416: 	    #  If there's more than one instance of a bubble character
                   5417: 	    #  That's a double bubble; with positional notation we can
                   5418: 	    #  record all the bubbles filled in as well as the 
                   5419: 	    #  fact this response consists of multiple bubbles.
                   5420: 	    #
                   5421: 	    else {
1.239     albertel 5422: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5423: 
                   5424: 		my $first_answer = $ansnum;
                   5425: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5426: 		    my $item = $first_answer+$ans;
                   5427: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5428: 		}
                   5429: 
1.239     albertel 5430: 		my @ans=@array;
1.462     foxr     5431: 		my $i=0;
                   5432: 		my $increment = 0;
1.239     albertel 5433: 		while ($#ans) {
1.462     foxr     5434: 		    $i+=length($ans[0]) + $increment;
                   5435: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5436: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5437: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5438: 		    shift(@ans);
1.462     foxr     5439: 		    $increment = 1;
1.239     albertel 5440: 		}
1.462     foxr     5441: 		$ansnum += $answers_needed;
1.239     albertel 5442: 	    }
1.82      albertel 5443: 	}
                   5444:     }
1.83      albertel 5445:     $record{'scantron.maxquest'}=$questnum;
                   5446:     return \%record;
1.82      albertel 5447: }
                   5448: 
1.423     albertel 5449: =pod
                   5450: 
                   5451: =item scantron_add_delay
                   5452: 
                   5453:    Adds an error message that occurred during the grading phase to a
                   5454:    queue of messages to be shown after grading pass is complete
                   5455: 
                   5456:  Arguments:
1.424     albertel 5457:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5458:    $scanline    - the scanline that caused the error
                   5459:    $errormesage - the error message
                   5460:    $errorcode   - a numeric code for the error
                   5461: 
                   5462:  Side Effects:
1.424     albertel 5463:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5464: 
                   5465: =cut
                   5466: 
1.82      albertel 5467: sub scantron_add_delay {
1.140     albertel 5468:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5469:     push(@$delayqueue,
                   5470: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5471: 	  'ecode' => $errorcode }
                   5472: 	 );
1.82      albertel 5473: }
                   5474: 
1.423     albertel 5475: =pod
                   5476: 
                   5477: =item scantron_find_student
                   5478: 
1.424     albertel 5479:    Finds the username for the current scanline
                   5480: 
                   5481:   Arguments:
                   5482:    $scantron_record - hash result from scantron_parse_scanline
                   5483:    $scan_data       - hash of correction information 
                   5484:                       (see &scantron_getfile() form more information)
                   5485:    $idmap           - hash from &username_to_idmap()
                   5486:    $line            - number of current scanline
                   5487:  
                   5488:   Returns:
                   5489:    Either 'username:domain' or undef if unknown
                   5490: 
1.423     albertel 5491: =cut
                   5492: 
1.82      albertel 5493: sub scantron_find_student {
1.157     albertel 5494:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5495:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5496:     if ($scanID =~ /^\s*$/) {
                   5497:  	return &scan_data($scan_data,"$line.user");
                   5498:     }
1.83      albertel 5499:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5500:  	if (lc($id) eq lc($scanID)) {
                   5501:  	    return $$idmap{$id};
                   5502:  	}
1.83      albertel 5503:     }
                   5504:     return undef;
                   5505: }
                   5506: 
1.423     albertel 5507: =pod
                   5508: 
                   5509: =item scantron_filter
                   5510: 
1.424     albertel 5511:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5512:    hidden resources was selected
                   5513: 
1.423     albertel 5514: =cut
                   5515: 
1.83      albertel 5516: sub scantron_filter {
                   5517:     my ($curres)=@_;
1.331     albertel 5518: 
                   5519:     if (ref($curres) && $curres->is_problem()) {
                   5520: 	# if the user has asked to not have either hidden
                   5521: 	# or 'randomout' controlled resources to be graded
                   5522: 	# don't include them
                   5523: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5524: 	    && $curres->randomout) {
                   5525: 	    return 0;
                   5526: 	}
1.83      albertel 5527: 	return 1;
                   5528:     }
                   5529:     return 0;
1.82      albertel 5530: }
                   5531: 
1.423     albertel 5532: =pod
                   5533: 
                   5534: =item scantron_process_corrections
                   5535: 
1.424     albertel 5536:    Gets correction information out of submitted form data and corrects
                   5537:    the scanline
                   5538: 
1.423     albertel 5539: =cut
                   5540: 
1.157     albertel 5541: sub scantron_process_corrections {
                   5542:     my ($r) = @_;
1.257     albertel 5543:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5544:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5545:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5546:     my $which=$env{'form.scantron_line'};
1.200     albertel 5547:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5548:     my ($skip,$err,$errmsg);
1.257     albertel 5549:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5550: 	$skip=1;
1.257     albertel 5551:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5552: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5553: 	    $env{'form.scantron_domain'};
1.157     albertel 5554: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5555: 	($line,$err,$errmsg)=
                   5556: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5557: 				     'ID',{'newid'=>$newid,
1.257     albertel 5558: 				    'username'=>$env{'form.scantron_username'},
                   5559: 				    'domain'=>$env{'form.scantron_domain'}});
                   5560:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5561: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5562: 	my $newCODE;
1.192     albertel 5563: 	my %args;
1.190     albertel 5564: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5565: 	    $newCODE='use_unfound';
1.190     albertel 5566: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5567: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5568: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5569: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5570: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5571: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5572: 	}
1.257     albertel 5573: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5574: 	    $args{'CODE_ignore_dup'}=1;
                   5575: 	}
                   5576: 	$args{'CODE'}=$newCODE;
1.186     albertel 5577: 	($line,$err,$errmsg)=
                   5578: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5579: 				     'CODE',\%args);
1.257     albertel 5580:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5581: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5582: 	    ($line,$err,$errmsg)=
                   5583: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5584: 					 $which,'answer',
                   5585: 					 { 'question'=>$question,
1.257     albertel 5586: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5587: 	    if ($err) { last; }
                   5588: 	}
                   5589:     }
                   5590:     if ($err) {
1.398     albertel 5591: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5592:     } else {
1.200     albertel 5593: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5594: 	&scantron_putfile($scanlines,$scan_data);
                   5595:     }
                   5596: }
                   5597: 
1.423     albertel 5598: =pod
                   5599: 
                   5600: =item reset_skipping_status
                   5601: 
1.424     albertel 5602:    Forgets the current set of remember skipped scanlines (and thus
                   5603:    reverts back to considering all lines in the
                   5604:    scantron_skipped_<filename> file)
                   5605: 
1.423     albertel 5606: =cut
                   5607: 
1.200     albertel 5608: sub reset_skipping_status {
                   5609:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5610:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5611:     &scantron_putfile(undef,$scan_data);
                   5612: }
                   5613: 
1.423     albertel 5614: =pod
                   5615: 
                   5616: =item start_skipping
                   5617: 
1.424     albertel 5618:    Marks a scanline to be skipped. 
                   5619: 
1.423     albertel 5620: =cut
                   5621: 
1.376     albertel 5622: sub start_skipping {
1.200     albertel 5623:     my ($scan_data,$i)=@_;
                   5624:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5625:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5626: 	$remembered{$i}=2;
                   5627:     } else {
                   5628: 	$remembered{$i}=1;
                   5629:     }
1.200     albertel 5630:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5631: }
                   5632: 
1.423     albertel 5633: =pod
                   5634: 
                   5635: =item should_be_skipped
                   5636: 
1.424     albertel 5637:    Checks whether a scanline should be skipped.
                   5638: 
1.423     albertel 5639: =cut
                   5640: 
1.200     albertel 5641: sub should_be_skipped {
1.376     albertel 5642:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5643:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5644: 	# not redoing old skips
1.376     albertel 5645: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5646: 	return 0;
                   5647:     }
                   5648:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5649: 
                   5650:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5651: 	return 0;
                   5652:     }
1.200     albertel 5653:     return 1;
                   5654: }
                   5655: 
1.423     albertel 5656: =pod
                   5657: 
                   5658: =item remember_current_skipped
                   5659: 
1.424     albertel 5660:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5661:    file and remembers them into scan_data for later use.
                   5662: 
1.423     albertel 5663: =cut
                   5664: 
1.200     albertel 5665: sub remember_current_skipped {
                   5666:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5667:     my %to_remember;
                   5668:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5669: 	if ($scanlines->{'skipped'}[$i]) {
                   5670: 	    $to_remember{$i}=1;
                   5671: 	}
                   5672:     }
1.376     albertel 5673: 
1.200     albertel 5674:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5675:     &scantron_putfile(undef,$scan_data);
                   5676: }
                   5677: 
1.423     albertel 5678: =pod
                   5679: 
                   5680: =item check_for_error
                   5681: 
1.424     albertel 5682:     Checks if there was an error when attempting to remove a specific
                   5683:     scantron_.. bubble sheet data file. Prints out an error if
                   5684:     something went wrong.
                   5685: 
1.423     albertel 5686: =cut
                   5687: 
1.200     albertel 5688: sub check_for_error {
                   5689:     my ($r,$result)=@_;
                   5690:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5691: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5692:     }
                   5693: }
1.157     albertel 5694: 
1.423     albertel 5695: =pod
                   5696: 
                   5697: =item scantron_warning_screen
                   5698: 
1.424     albertel 5699:    Interstitial screen to make sure the operator has selected the
                   5700:    correct options before we start the validation phase.
                   5701: 
1.423     albertel 5702: =cut
                   5703: 
1.203     albertel 5704: sub scantron_warning_screen {
                   5705:     my ($button_text)=@_;
1.257     albertel 5706:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5707:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5708:     my $CODElist;
1.284     albertel 5709:     if ($scantron_config{'CODElocation'} &&
                   5710: 	$scantron_config{'CODEstart'} &&
                   5711: 	$scantron_config{'CODElength'}) {
                   5712: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5713: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5714: 	$CODElist=
                   5715: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5716: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5717:     }
1.203     albertel 5718:     return (<<STUFF);
                   5719: <p>
1.398     albertel 5720: <span class="LC_warning">Please double check the information
                   5721:                  below before clicking on '$button_text'</span>
1.203     albertel 5722: </p>
                   5723: <table>
1.284     albertel 5724: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5725: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5726: $CODElist
1.203     albertel 5727: </table>
                   5728: <br />
                   5729: <p> If this information is correct, please click on '$button_text'.</p>
                   5730: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5731: 
                   5732: <br />
                   5733: STUFF
                   5734: }
                   5735: 
1.423     albertel 5736: =pod
                   5737: 
                   5738: =item scantron_do_warning
                   5739: 
1.424     albertel 5740:    Check if the operator has picked something for all required
                   5741:    fields. Error out if something is missing.
                   5742: 
1.423     albertel 5743: =cut
                   5744: 
1.203     albertel 5745: sub scantron_do_warning {
                   5746:     my ($r)=@_;
1.324     albertel 5747:     my ($symb)=&get_symb($r);
1.203     albertel 5748:     if (!$symb) {return '';}
1.324     albertel 5749:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5750:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5751:     if ( $env{'form.selectpage'} eq '' ||
                   5752: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5753: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5754: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5755: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5756: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5757: 	} 
1.257     albertel 5758: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5759: 	    $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 5760: 	} 
1.257     albertel 5761: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5762: 	    $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 5763: 	} 
                   5764:     } else {
1.265     www      5765: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5766: 	$r->print(<<STUFF);
1.203     albertel 5767: $warning
1.265     www      5768: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5769: <input type="hidden" name="command" value="scantron_validate" />
                   5770: STUFF
1.237     albertel 5771:     }
1.352     albertel 5772:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5773:     return '';
                   5774: }
                   5775: 
1.423     albertel 5776: =pod
                   5777: 
                   5778: =item scantron_form_start
                   5779: 
1.424     albertel 5780:     html hidden input for remembering all selected grading options
                   5781: 
1.423     albertel 5782: =cut
                   5783: 
1.203     albertel 5784: sub scantron_form_start {
                   5785:     my ($max_bubble)=@_;
                   5786:     my $result= <<SCANTRONFORM;
                   5787: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5788:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5789:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5790:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5791:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5792:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5793:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5794:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5795:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5796:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5797: SCANTRONFORM
1.447     foxr     5798: 
                   5799:   my $line = 0;
                   5800:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5801:        my $chunk =
                   5802: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5803:        $chunk .=
                   5804: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5805:        $result .= $chunk;
                   5806:        $line++;
                   5807:    }
1.203     albertel 5808:     return $result;
                   5809: }
                   5810: 
1.423     albertel 5811: =pod
                   5812: 
                   5813: =item scantron_validate_file
                   5814: 
1.424     albertel 5815:     Dispatch routine for doing validation of a bubble sheet data file.
                   5816: 
                   5817:     Also processes any necessary information resets that need to
                   5818:     occur before validation begins (ignore previous corrections,
                   5819:     restarting the skipped records processing)
                   5820: 
1.423     albertel 5821: =cut
                   5822: 
1.157     albertel 5823: sub scantron_validate_file {
                   5824:     my ($r) = @_;
1.324     albertel 5825:     my ($symb)=&get_symb($r);
1.157     albertel 5826:     if (!$symb) {return '';}
1.324     albertel 5827:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5828:     
                   5829:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5830:     # them when doing the corrections reset
1.257     albertel 5831:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5832: 	&reset_skipping_status();
                   5833:     }
1.257     albertel 5834:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5835: 	&remember_current_skipped();
1.257     albertel 5836: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5837:     }
                   5838: 
1.257     albertel 5839:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5840: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5841: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5842: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5843: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5844:     }
1.200     albertel 5845: 
1.257     albertel 5846:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5847: 	&scantron_process_corrections($r);
                   5848:     }
1.424     albertel 5849:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5850:     #get the student pick code ready
                   5851:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5852:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5853:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5854:     $r->print($result);
                   5855:     
1.334     albertel 5856:     my @validate_phases=( 'sequence',
                   5857: 			  'ID',
1.157     albertel 5858: 			  'CODE',
                   5859: 			  'doublebubble',
                   5860: 			  'missingbubbles');
1.257     albertel 5861:     if (!$env{'form.validatepass'}) {
                   5862: 	$env{'form.validatepass'} = 0;
1.157     albertel 5863:     }
1.257     albertel 5864:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5865: 
1.448     foxr     5866: 
1.157     albertel 5867:     my $stop=0;
                   5868:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5869: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5870: 	$r->rflush();
                   5871: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5872: 	{
                   5873: 	    no strict 'refs';
                   5874: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5875: 	}
                   5876:     }
                   5877:     if (!$stop) {
1.203     albertel 5878: 	my $warning=&scantron_warning_screen('Start Grading');
                   5879: 	$r->print(<<STUFF);
                   5880: Validation process complete.<br />
                   5881: $warning
                   5882: <input type="submit" name="submit" value="Start Grading" />
                   5883: <input type="hidden" name="command" value="scantron_process" />
                   5884: STUFF
                   5885: 
1.157     albertel 5886:     } else {
                   5887: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5888: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5889:     }
                   5890:     if ($stop) {
1.334     albertel 5891: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5892: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5893: 	    $r->print(' this error <br />');
                   5894: 
                   5895: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5896: 	} else {
                   5897: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5898: 	    $r->print(' using corrected info <br />');
                   5899: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5900: 	    $r->print(" this scanline saving it for later.");
                   5901: 	}
1.157     albertel 5902:     }
1.352     albertel 5903:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5904:     return '';
                   5905: }
                   5906: 
1.423     albertel 5907: 
                   5908: =pod
                   5909: 
                   5910: =item scantron_remove_file
                   5911: 
1.424     albertel 5912:    Removes the requested bubble sheet data file, makes sure that
                   5913:    scantron_original_<filename> is never removed
                   5914: 
                   5915: 
1.423     albertel 5916: =cut
                   5917: 
1.200     albertel 5918: sub scantron_remove_file {
1.192     albertel 5919:     my ($which)=@_;
1.257     albertel 5920:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5921:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5922:     my $file='scantron_';
1.200     albertel 5923:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5924: 	$file.=$which.'_';
1.192     albertel 5925:     } else {
                   5926: 	return 'refused';
                   5927:     }
1.257     albertel 5928:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5929:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5930: }
                   5931: 
1.423     albertel 5932: 
                   5933: =pod
                   5934: 
                   5935: =item scantron_remove_scan_data
                   5936: 
1.424     albertel 5937:    Removes all scan_data correction for the requested bubble sheet
                   5938:    data file.  (In the case that both the are doing skipped records we need
                   5939:    to remember the old skipped lines for the time being so that element
                   5940:    persists for a while.)
                   5941: 
1.423     albertel 5942: =cut
                   5943: 
1.200     albertel 5944: sub scantron_remove_scan_data {
1.257     albertel 5945:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5946:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5947:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5948:     my @todelete;
1.257     albertel 5949:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5950:     foreach my $key (@keys) {
                   5951: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5952: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5953: 		$key=~/remember_skipping/) {
                   5954: 		next;
                   5955: 	    }
1.192     albertel 5956: 	    push(@todelete,$key);
                   5957: 	}
                   5958:     }
1.200     albertel 5959:     my $result;
1.192     albertel 5960:     if (@todelete) {
1.200     albertel 5961: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5962:     }
                   5963:     return $result;
                   5964: }
                   5965: 
1.423     albertel 5966: 
                   5967: =pod
                   5968: 
                   5969: =item scantron_getfile
                   5970: 
1.424     albertel 5971:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5972:     the scan_data hash
                   5973:   
                   5974:   Arguments:
                   5975:     None
                   5976: 
                   5977:   Returns:
                   5978:     2 hash references
                   5979: 
                   5980:      - first one has 
                   5981:          orig      -
                   5982:          corrected -
                   5983:          skipped   -  each of which points to an array ref of the specified
                   5984:                       file broken up into individual lines
                   5985:          count     - number of scanlines
                   5986:  
                   5987:      - second is the scan_data hash possible keys are
1.425     albertel 5988:        ($number refers to scanline numbered $number and thus the key affects
                   5989:         only that scanline
                   5990:         $bubline refers to the specific bubble line element and the aspects
                   5991:         refers to that specific bubble line element)
                   5992: 
                   5993:        $number.user - username:domain to use
                   5994:        $number.CODE_ignore_dup 
                   5995:                     - ignore the duplicate CODE error 
                   5996:        $number.useCODE
                   5997:                     - use the CODE in the scanline as is
                   5998:        $number.no_bubble.$bubline
                   5999:                     - it is valid that there is no bubbled in bubble
                   6000:                       at $number $bubline
                   6001:        remember_skipping
                   6002:                     - a frozen hash containing keys of $number and values
                   6003:                       of either 
                   6004:                         1 - we are on a 'do skipped records pass' and plan
                   6005:                             on processing this line
                   6006:                         2 - we are on a 'do skipped records pass' and this
                   6007:                             scanline has been marked to skip yet again
1.424     albertel 6008: 
1.423     albertel 6009: =cut
                   6010: 
1.157     albertel 6011: sub scantron_getfile {
1.200     albertel 6012:     #FIXME really would prefer a scantron directory
1.257     albertel 6013:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6014:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6015:     my $lines;
                   6016:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6017: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6018:     my %scanlines;
                   6019:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6020:     my $temp=$scanlines{'orig'};
                   6021:     $scanlines{'count'}=$#$temp;
                   6022: 
                   6023:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6024: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6025:     if ($lines eq '-1') {
                   6026: 	$scanlines{'corrected'}=[];
                   6027:     } else {
                   6028: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6029:     }
                   6030:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6031: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6032:     if ($lines eq '-1') {
                   6033: 	$scanlines{'skipped'}=[];
                   6034:     } else {
                   6035: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6036:     }
1.175     albertel 6037:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6038:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6039:     my %scan_data = @tmp;
                   6040:     return (\%scanlines,\%scan_data);
                   6041: }
                   6042: 
1.423     albertel 6043: =pod
                   6044: 
                   6045: =item lonnet_putfile
                   6046: 
1.424     albertel 6047:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6048: 
                   6049:  Arguments:
                   6050:    $contents - data to store
                   6051:    $filename - filename to store $contents into
                   6052: 
                   6053:  Returns:
                   6054:    result value from &Apache::lonnet::finishuserfileupload
                   6055: 
1.423     albertel 6056: =cut
                   6057: 
1.157     albertel 6058: sub lonnet_putfile {
                   6059:     my ($contents,$filename)=@_;
1.257     albertel 6060:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6061:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6062:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6063:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6064: 
                   6065: }
                   6066: 
1.423     albertel 6067: =pod
                   6068: 
                   6069: =item scantron_putfile
                   6070: 
1.424     albertel 6071:     Stores the current version of the bubble sheet data files, and the
                   6072:     scan_data hash. (Does not modify the original version only the
                   6073:     corrected and skipped versions.
                   6074: 
                   6075:  Arguments:
                   6076:     $scanlines - hash ref that looks like the first return value from
                   6077:                  &scantron_getfile()
                   6078:     $scan_data - hash ref that looks like the second return value from
                   6079:                  &scantron_getfile()
                   6080: 
1.423     albertel 6081: =cut
                   6082: 
1.157     albertel 6083: sub scantron_putfile {
                   6084:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6085:     #FIXME really would prefer a scantron directory
1.257     albertel 6086:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6087:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6088:     if ($scanlines) {
                   6089: 	my $prefix='scantron_';
1.157     albertel 6090: # no need to update orig, shouldn't change
                   6091: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6092: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6093: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6094: 			$prefix.'corrected_'.
1.257     albertel 6095: 			$env{'form.scantron_selectfile'});
1.200     albertel 6096: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6097: 			$prefix.'skipped_'.
1.257     albertel 6098: 			$env{'form.scantron_selectfile'});
1.200     albertel 6099:     }
1.175     albertel 6100:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6101: }
                   6102: 
1.423     albertel 6103: =pod
                   6104: 
                   6105: =item scantron_get_line
                   6106: 
1.424     albertel 6107:    Returns the correct version of the scanline
                   6108: 
                   6109:  Arguments:
                   6110:     $scanlines - hash ref that looks like the first return value from
                   6111:                  &scantron_getfile()
                   6112:     $scan_data - hash ref that looks like the second return value from
                   6113:                  &scantron_getfile()
                   6114:     $i         - number of the requested line (starts at 0)
                   6115: 
                   6116:  Returns:
                   6117:    A scanline, (either the original or the corrected one if it
                   6118:    exists), or undef if the requested scanline should be
                   6119:    skipped. (Either because it's an skipped scanline, or it's an
                   6120:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6121:    pass.
                   6122: 
1.423     albertel 6123: =cut
                   6124: 
1.157     albertel 6125: sub scantron_get_line {
1.200     albertel 6126:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6127:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6128:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6129:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6130:     return $scanlines->{'orig'}[$i]; 
                   6131: }
                   6132: 
1.423     albertel 6133: =pod
                   6134: 
                   6135: =item scantron_todo_count
                   6136: 
1.424     albertel 6137:     Counts the number of scanlines that need processing.
                   6138: 
                   6139:  Arguments:
                   6140:     $scanlines - hash ref that looks like the first return value from
                   6141:                  &scantron_getfile()
                   6142:     $scan_data - hash ref that looks like the second return value from
                   6143:                  &scantron_getfile()
                   6144: 
                   6145:  Returns:
                   6146:     $count - number of scanlines to process
                   6147: 
1.423     albertel 6148: =cut
                   6149: 
1.200     albertel 6150: sub get_todo_count {
                   6151:     my ($scanlines,$scan_data)=@_;
                   6152:     my $count=0;
                   6153:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6154: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6155: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6156: 	$count++;
                   6157:     }
                   6158:     return $count;
                   6159: }
                   6160: 
1.423     albertel 6161: =pod
                   6162: 
                   6163: =item scantron_put_line
                   6164: 
1.424     albertel 6165:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6166:     data file.
                   6167: 
                   6168:  Arguments:
                   6169:     $scanlines - hash ref that looks like the first return value from
                   6170:                  &scantron_getfile()
                   6171:     $scan_data - hash ref that looks like the second return value from
                   6172:                  &scantron_getfile()
                   6173:     $i         - line number to update
                   6174:     $newline   - contents of the updated scanline
                   6175:     $skip      - if true make the line for skipping and update the
                   6176:                  'skipped' file
                   6177: 
1.423     albertel 6178: =cut
                   6179: 
1.157     albertel 6180: sub scantron_put_line {
1.200     albertel 6181:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6182:     if ($skip) {
                   6183: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6184: 	&start_skipping($scan_data,$i);
1.157     albertel 6185: 	return;
                   6186:     }
                   6187:     $scanlines->{'corrected'}[$i]=$newline;
                   6188: }
                   6189: 
1.423     albertel 6190: =pod
                   6191: 
                   6192: =item scantron_clear_skip
                   6193: 
1.424     albertel 6194:    Remove a line from the 'skipped' file
                   6195: 
                   6196:  Arguments:
                   6197:     $scanlines - hash ref that looks like the first return value from
                   6198:                  &scantron_getfile()
                   6199:     $scan_data - hash ref that looks like the second return value from
                   6200:                  &scantron_getfile()
                   6201:     $i         - line number to update
                   6202: 
1.423     albertel 6203: =cut
                   6204: 
1.376     albertel 6205: sub scantron_clear_skip {
                   6206:     my ($scanlines,$scan_data,$i)=@_;
                   6207:     if (exists($scanlines->{'skipped'}[$i])) {
                   6208: 	undef($scanlines->{'skipped'}[$i]);
                   6209: 	return 1;
                   6210:     }
                   6211:     return 0;
                   6212: }
                   6213: 
1.423     albertel 6214: =pod
                   6215: 
                   6216: =item scantron_filter_not_exam
                   6217: 
1.424     albertel 6218:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6219:    filter out resources that are not marked as 'exam' mode
                   6220: 
1.423     albertel 6221: =cut
                   6222: 
1.334     albertel 6223: sub scantron_filter_not_exam {
                   6224:     my ($curres)=@_;
                   6225:     
                   6226:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6227: 	# if the user has asked to not have either hidden
                   6228: 	# or 'randomout' controlled resources to be graded
                   6229: 	# don't include them
                   6230: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6231: 	    && $curres->randomout) {
                   6232: 	    return 0;
                   6233: 	}
                   6234: 	return 1;
                   6235:     }
                   6236:     return 0;
                   6237: }
                   6238: 
1.423     albertel 6239: =pod
                   6240: 
                   6241: =item scantron_validate_sequence
                   6242: 
1.424     albertel 6243:     Validates the selected sequence, checking for resource that are
                   6244:     not set to exam mode.
                   6245: 
1.423     albertel 6246: =cut
                   6247: 
1.334     albertel 6248: sub scantron_validate_sequence {
                   6249:     my ($r,$currentphase) = @_;
                   6250: 
                   6251:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6252:     my (undef,undef,$sequence)=
                   6253: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6254: 
                   6255:     my $map=$navmap->getResourceByUrl($sequence);
                   6256: 
                   6257:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6258:                                     value="ignore" />');
                   6259:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6260: 	my @resources=
                   6261: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6262: 	if (@resources) {
1.357     banghart 6263: 	    $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 6264: 	    return (1,$currentphase);
                   6265: 	}
                   6266:     }
                   6267: 
                   6268:     return (0,$currentphase+1);
                   6269: }
                   6270: 
1.423     albertel 6271: =pod
                   6272: 
                   6273: =item scantron_validate_ID
                   6274: 
1.424     albertel 6275:    Validates all scanlines in the selected file to not have any
                   6276:    invalid or underspecified student IDs
                   6277: 
1.423     albertel 6278: =cut
                   6279: 
1.157     albertel 6280: sub scantron_validate_ID {
                   6281:     my ($r,$currentphase) = @_;
                   6282:     
                   6283:     #get student info
                   6284:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6285:     my %idmap=&username_to_idmap($classlist);
                   6286: 
                   6287:     #get scantron line setup
1.257     albertel 6288:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6289:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6290:     
                   6291:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6292: 
                   6293:     my %found=('ids'=>{},'usernames'=>{});
                   6294:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6295: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6296: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6297: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6298: 						 $scan_data);
                   6299: 	my $id=$$scan_record{'scantron.ID'};
                   6300: 	my $found;
                   6301: 	foreach my $checkid (keys(%idmap)) {
                   6302: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6303: 	}
                   6304: 	if ($found) {
                   6305: 	    my $username=$idmap{$found};
                   6306: 	    if ($found{'ids'}{$found}) {
                   6307: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6308: 					 $line,'duplicateID',$found);
1.194     albertel 6309: 		return(1,$currentphase);
1.157     albertel 6310: 	    } elsif ($found{'usernames'}{$username}) {
                   6311: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6312: 					 $line,'duplicateID',$username);
1.194     albertel 6313: 		return(1,$currentphase);
1.157     albertel 6314: 	    }
1.186     albertel 6315: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6316: 	    $found{'ids'}{$found}++;
                   6317: 	    $found{'usernames'}{$username}++;
                   6318: 	} else {
                   6319: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6320: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6321: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6322: 		    &scantron_get_correction($r,$i,$scan_record,
                   6323: 					     \%scantron_config,
                   6324: 					     $line,'duplicateID',$username);
1.194     albertel 6325: 		    return(1,$currentphase);
1.157     albertel 6326: 		} elsif (!defined($username)) {
                   6327: 		    &scantron_get_correction($r,$i,$scan_record,
                   6328: 					     \%scantron_config,
                   6329: 					     $line,'incorrectID');
1.194     albertel 6330: 		    return(1,$currentphase);
1.157     albertel 6331: 		}
                   6332: 		$found{'usernames'}{$username}++;
                   6333: 	    } else {
                   6334: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6335: 					 $line,'incorrectID');
1.194     albertel 6336: 		return(1,$currentphase);
1.157     albertel 6337: 	    }
                   6338: 	}
                   6339:     }
                   6340: 
                   6341:     return (0,$currentphase+1);
                   6342: }
                   6343: 
1.423     albertel 6344: =pod
                   6345: 
                   6346: =item scantron_get_correction
                   6347: 
1.424     albertel 6348:    Builds the interface screen to interact with the operator to fix a
                   6349:    specific error condition in a specific scanline
                   6350: 
                   6351:  Arguments:
                   6352:     $r           - Apache request object
                   6353:     $i           - number of the current scanline
                   6354:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6355:     $scan_config - hash ref as returned from &get_scantron_config()
                   6356:     $line        - full contents of the current scanline
                   6357:     $error       - error condition, valid values are
                   6358:                    'incorrectCODE', 'duplicateCODE',
                   6359:                    'doublebubble', 'missingbubble',
                   6360:                    'duplicateID', 'incorrectID'
                   6361:     $arg         - extra information needed
                   6362:        For errors:
                   6363:          - duplicateID   - paper number that this studentID was seen before on
                   6364:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6365:                            seen on before
                   6366:          - incorrectCODE - current incorrect CODE 
                   6367:          - doublebubble  - array ref of the bubble lines that have double
                   6368:                            bubble errors
                   6369:          - missingbubble - array ref of the bubble lines that have missing
                   6370:                            bubble errors
                   6371: 
1.423     albertel 6372: =cut
                   6373: 
1.157     albertel 6374: sub scantron_get_correction {
                   6375:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6376: 
1.454     banghart 6377: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6378: #to show both the current line and the previous one and allow skipping
                   6379: #the previous one or the current one
                   6380: 
1.161     albertel 6381:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6382:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6383: 	$r->print(" for PaperID <tt>".
                   6384: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6385:     } else {
                   6386: 	$r->print(" in scanline $i <pre>".
                   6387: 		  $line."</pre> \n");
                   6388:     }
1.242     albertel 6389:     my $message="<p>The ID on the form is  <tt>".
                   6390: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6391: 	"The name on the paper is ".
                   6392: 	$$scan_record{'scantron.LastName'}.",".
                   6393: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6394: 
1.157     albertel 6395:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6396:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6397:     if ($error =~ /ID$/) {
1.186     albertel 6398: 	if ($error eq 'incorrectID') {
1.157     albertel 6399: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6400: 	} elsif ($error eq 'duplicateID') {
                   6401: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6402: 	}
1.242     albertel 6403: 	$r->print($message);
1.157     albertel 6404: 	$r->print("<p>How should I handle this? <br /> \n");
                   6405: 	$r->print("\n<ul><li> ");
                   6406: 	#FIXME it would be nice if this sent back the user ID and
                   6407: 	#could do partial userID matches
                   6408: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6409: 				       'scantron_username','scantron_domain'));
                   6410: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6411: 	$r->print("\n@".
1.257     albertel 6412: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6413: 
                   6414: 	$r->print('</li>');
1.186     albertel 6415:     } elsif ($error =~ /CODE$/) {
                   6416: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6417: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6418: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6419: 	    $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 6420: 	}
1.224     albertel 6421: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6422: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6423: 	$r->print($message);
1.186     albertel 6424: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6425: 	$r->print("\n<br /> ");
1.194     albertel 6426: 	my $i=0;
1.273     albertel 6427: 	if ($error eq 'incorrectCODE' 
                   6428: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6429: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6430: 	    if ($closest > 0) {
                   6431: 		foreach my $testcode (@{$closest}) {
                   6432: 		    my $checked='';
1.401     albertel 6433: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6434: 		    $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' />");
                   6435: 		    $r->print("\n<br />");
                   6436: 		    $i++;
                   6437: 		}
1.194     albertel 6438: 	    }
                   6439: 	}
1.273     albertel 6440: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6441: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6442: 	    $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>");
                   6443: 	    $r->print("\n<br />");
                   6444: 	}
1.194     albertel 6445: 
1.188     albertel 6446: 	$r->print(<<ENDSCRIPT);
                   6447: <script type="text/javascript">
                   6448: function change_radio(field) {
1.190     albertel 6449:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6450:     var i;
                   6451:     for (i=0;i<slct.length;i++) {
                   6452:         if (slct[i].value==field) { slct[i].checked=true; }
                   6453:     }
                   6454: }
                   6455: </script>
                   6456: ENDSCRIPT
1.187     albertel 6457: 	my $href="/adm/pickcode?".
1.359     www      6458: 	   "form=".&escape("scantronupload").
                   6459: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6460: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6461: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6462: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6463: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6464: 	    $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')\" />");
                   6465: 	    $r->print("\n<br />");
                   6466: 	}
1.272     albertel 6467: 	$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 6468: 	$r->print("\n<br /><br />");
1.157     albertel 6469:     } elsif ($error eq 'doublebubble') {
                   6470: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6471: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6472: 		  join(',',@{$arg}).'" />');
1.242     albertel 6473: 	$r->print($message);
1.157     albertel 6474: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6475: 	foreach my $question (@{$arg}) {
1.447     foxr     6476: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6477: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6478: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6479: 				      @select_array);
1.157     albertel 6480: 	}
                   6481:     } elsif ($error eq 'missingbubble') {
                   6482: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6483: 	$r->print($message);
1.157     albertel 6484: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6485: 	$r->print("Some questions have no scanned bubbles\n");
                   6486: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6487: 		  join(',',@{$arg}).'" />');
                   6488: 	foreach my $question (@{$arg}) {
1.448     foxr     6489: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6490: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6491: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6492: 	}
                   6493:     } else {
                   6494: 	$r->print("\n<ul>");
                   6495:     }
                   6496:     $r->print("\n</li></ul>");
                   6497: 
                   6498: }
1.423     albertel 6499: 
                   6500: =pod
                   6501: 
                   6502: =item scantron_bubble_selector
                   6503:   
                   6504:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6505:    possibly showing the existing the selected bubbles if known
1.423     albertel 6506: 
                   6507:  Arguments:
                   6508:     $r           - Apache request object
                   6509:     $scan_config - hash from &get_scantron_config()
                   6510:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6511:     @lines       - array of answer lines.
1.423     albertel 6512: 
                   6513: =cut
                   6514: 
1.157     albertel 6515: sub scantron_bubble_selector {
1.461     foxr     6516:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6517:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6518: 
1.461     foxr     6519: 
1.274     albertel 6520:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6521: 
1.461     foxr     6522:     my $bubble_length = scalar(@lines);
1.460     foxr     6523: 
1.447     foxr     6524: 
1.274     albertel 6525:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6526: 
1.448     foxr     6527:     my $response = $quest-1;
                   6528:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6529: 
1.422     foxr     6530:     my $total_lines = $lines*2;
1.157     albertel 6531:     my @alphabet=('A'..'Z');
1.422     foxr     6532:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6533: 
                   6534:     for (my $l = 0; $l < $lines; $l++) {
                   6535: 	if ($l != 0) {
                   6536: 	    $r->print('<tr>');
                   6537: 	}
1.462     foxr     6538: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6539: 	for (my $i=0;$i<$max;$i++) {
                   6540: 	    $r->print("\n".'<td align="center">');
                   6541: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6542: 		$r->print('X'); 
                   6543: 		shift(@selected) ;
                   6544: 	    } else { 
                   6545: 		$r->print('&nbsp;'); 
                   6546: 	    }
                   6547: 	    $r->print('</td>');
                   6548: 	    
                   6549: 	}
                   6550: 
                   6551: 	if ($l == 0) {
                   6552: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6553: 
                   6554: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6555: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6556: 	
                   6557: 	}
                   6558: 
                   6559: 	$r->print('</tr><tr>');
                   6560: 
                   6561: 	# FIXME: This may have to be a bit more clever for
                   6562: 	#        multiline questions (different values e.g..).
                   6563: 
                   6564: 	for (my $i=0;$i<$max;$i++) {
                   6565: 	    $r->print("\n".
                   6566: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6567: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6568: 	}
                   6569: 	$r->print('</tr>');
                   6570: 
                   6571: 	    
1.157     albertel 6572:     }
1.422     foxr     6573:     $r->print('</table>');
1.157     albertel 6574: }
                   6575: 
1.423     albertel 6576: =pod
                   6577: 
                   6578: =item num_matches
                   6579: 
1.424     albertel 6580:    Counts the number of characters that are the same between the two arguments.
                   6581: 
                   6582:  Arguments:
                   6583:    $orig - CODE from the scanline
                   6584:    $code - CODE to match against
                   6585: 
                   6586:  Returns:
                   6587:    $count - integer count of the number of same characters between the
                   6588:             two arguments
                   6589: 
1.423     albertel 6590: =cut
                   6591: 
1.194     albertel 6592: sub num_matches {
                   6593:     my ($orig,$code) = @_;
                   6594:     my @code=split(//,$code);
                   6595:     my @orig=split(//,$orig);
                   6596:     my $same=0;
                   6597:     for (my $i=0;$i<scalar(@code);$i++) {
                   6598: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6599:     }
                   6600:     return $same;
                   6601: }
                   6602: 
1.423     albertel 6603: =pod
                   6604: 
                   6605: =item scantron_get_closely_matching_CODEs
                   6606: 
1.424     albertel 6607:    Cycles through all CODEs and finds the set that has the greatest
                   6608:    number of same characters as the provided CODE
                   6609: 
                   6610:  Arguments:
                   6611:    $allcodes - hash ref returned by &get_codes()
                   6612:    $CODE     - CODE from the current scanline
                   6613: 
                   6614:  Returns:
                   6615:    2 element list
                   6616:     - first elements is number of how closely matching the best fit is 
                   6617:       (5 means best set has 5 matching characters)
                   6618:     - second element is an arrary ref containing the set of valid CODEs
                   6619:       that best fit the passed in CODE
                   6620: 
1.423     albertel 6621: =cut
                   6622: 
1.194     albertel 6623: sub scantron_get_closely_matching_CODEs {
                   6624:     my ($allcodes,$CODE)=@_;
                   6625:     my @CODEs;
                   6626:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6627: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6628:     }
                   6629: 
                   6630:     return ($#CODEs,$CODEs[-1]);
                   6631: }
                   6632: 
1.423     albertel 6633: =pod
                   6634: 
                   6635: =item get_codes
                   6636: 
1.424     albertel 6637:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6638:    set of remembered CODEs.
                   6639: 
                   6640:  Arguments:
                   6641:   $old_name - name of the set of remembered CODEs
                   6642:   $cdom     - domain of the course
                   6643:   $cnum     - internal course name
                   6644: 
                   6645:  Returns:
                   6646:   %allcodes - keys are the valid CODEs, values are all 1
                   6647: 
1.423     albertel 6648: =cut
                   6649: 
1.194     albertel 6650: sub get_codes {
1.280     foxr     6651:     my ($old_name, $cdom, $cnum) = @_;
                   6652:     if (!$old_name) {
                   6653: 	$old_name=$env{'form.scantron_CODElist'};
                   6654:     }
                   6655:     if (!$cdom) {
                   6656: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6657:     }
                   6658:     if (!$cnum) {
                   6659: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6660:     }
1.278     albertel 6661:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6662: 				    $cdom,$cnum);
                   6663:     my %allcodes;
                   6664:     if ($result{"type\0$old_name"} eq 'number') {
                   6665: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6666:     } else {
                   6667: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6668:     }
1.194     albertel 6669:     return %allcodes;
                   6670: }
                   6671: 
1.423     albertel 6672: =pod
                   6673: 
                   6674: =item scantron_validate_CODE
                   6675: 
1.424     albertel 6676:    Validates all scanlines in the selected file to not have any
                   6677:    invalid or underspecified CODEs and that none of the codes are
                   6678:    duplicated if this was requested.
                   6679: 
1.423     albertel 6680: =cut
                   6681: 
1.157     albertel 6682: sub scantron_validate_CODE {
                   6683:     my ($r,$currentphase) = @_;
1.257     albertel 6684:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6685:     if ($scantron_config{'CODElocation'} &&
                   6686: 	$scantron_config{'CODEstart'} &&
                   6687: 	$scantron_config{'CODElength'}) {
1.257     albertel 6688: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6689: 	    &FIXME_blow_up()
                   6690: 	}
                   6691:     } else {
                   6692: 	return (0,$currentphase+1);
                   6693:     }
                   6694:     
                   6695:     my %usedCODEs;
                   6696: 
1.194     albertel 6697:     my %allcodes=&get_codes();
1.186     albertel 6698: 
1.447     foxr     6699:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6700: 
1.186     albertel 6701:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6702:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6703: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6704: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6705: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6706: 						 $scan_data);
                   6707: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6708: 	my $error=0;
1.224     albertel 6709: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6710: 	    &scantron_get_correction($r,$i,$scan_record,
                   6711: 				     \%scantron_config,
                   6712: 				     $line,'incorrectCODE',\%allcodes);
                   6713: 	    return(1,$currentphase);
                   6714: 	}
1.221     albertel 6715: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6716: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6717: 	    &scantron_get_correction($r,$i,$scan_record,
                   6718: 				     \%scantron_config,
1.194     albertel 6719: 				     $line,'incorrectCODE',\%allcodes);
                   6720: 	    return(1,$currentphase);
1.186     albertel 6721: 	}
1.214     albertel 6722: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6723: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6724: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6725: 	    &scantron_get_correction($r,$i,$scan_record,
                   6726: 				     \%scantron_config,
1.194     albertel 6727: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6728: 	    return(1,$currentphase);
1.186     albertel 6729: 	}
1.194     albertel 6730: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6731:     }
1.157     albertel 6732:     return (0,$currentphase+1);
                   6733: }
                   6734: 
1.423     albertel 6735: =pod
                   6736: 
                   6737: =item scantron_validate_doublebubble
                   6738: 
1.424     albertel 6739:    Validates all scanlines in the selected file to not have any
                   6740:    bubble lines with multiple bubbles marked.
                   6741: 
1.423     albertel 6742: =cut
                   6743: 
1.157     albertel 6744: sub scantron_validate_doublebubble {
                   6745:     my ($r,$currentphase) = @_;
                   6746:     #get student info
                   6747:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6748:     my %idmap=&username_to_idmap($classlist);
                   6749: 
                   6750:     #get scantron line setup
1.257     albertel 6751:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6752:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6753: 
                   6754:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6755: 
1.157     albertel 6756:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6757: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6758: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6759: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6760: 						 $scan_data);
                   6761: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6762: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6763: 				 'doublebubble',
                   6764: 				 $$scan_record{'scantron.doubleerror'});
                   6765:     	return (1,$currentphase);
                   6766:     }
                   6767:     return (0,$currentphase+1);
                   6768: }
                   6769: 
1.423     albertel 6770: =pod
                   6771: 
                   6772: =item scantron_get_maxbubble
                   6773: 
1.424     albertel 6774:    Returns the maximum number of bubble lines that are expected to
                   6775:    occur. Does this by walking the selected sequence rendering the
                   6776:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6777:    for what the current value of the problem counter is.
                   6778: 
1.447     foxr     6779:    Caches the results to $env{'form.scantron_maxbubble'},
                   6780:    $env{'form.scantron.bubble_lines.n'} and 
                   6781:    $env{'form.scantron.first_bubble_line.n'}
                   6782:    which are the total number of bubble, lines, the number of bubble
                   6783:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6784: 
1.423     albertel 6785: =cut
                   6786: 
1.330     albertel 6787: sub scantron_get_maxbubble {    
1.257     albertel 6788:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6789: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6790: 	&restore_bubble_lines();
1.257     albertel 6791: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6792:     }
1.330     albertel 6793: 
1.447     foxr     6794:     my (undef, undef, $sequence) =
1.257     albertel 6795: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6796: 
1.447     foxr     6797:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6798:     my $map=$navmap->getResourceByUrl($sequence);
                   6799:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6800: 
                   6801:     &Apache::lonxml::clear_problem_counter();
                   6802: 
1.435     foxr     6803:     my $uname       = $env{'form.student'};
                   6804:     my $udom        = $env{'form.userdom'};
                   6805:     my $cid         = $env{'request.course.id'};
                   6806:     my $total_lines = 0;
                   6807:     %bubble_lines_per_response = ();
1.447     foxr     6808:     %first_bubble_line         = ();
1.435     foxr     6809: 
1.447     foxr     6810:   
                   6811:     my $response_number = 0;
                   6812:     my $bubble_line     = 0;
1.191     albertel 6813:     foreach my $resource (@resources) {
1.435     foxr     6814: 	my $symb = $resource->symb();
1.447     foxr     6815: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6816: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6817: 					('symb' => $resource->symb()),
                   6818: 					('grade_target' => 'analyze'),
                   6819: 					('grade_courseid' => $cid),
                   6820: 					('grade_domain' => $udom),
                   6821: 					('grade_username' => $uname));
1.436     albertel 6822: 	my (undef, $an) =
1.435     foxr     6823: 	    split(/_HASH_REF__/,$result, 2);
                   6824: 
                   6825: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6826: 
                   6827: 
                   6828: 
                   6829: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6830: 
1.460     foxr     6831: 
                   6832: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
1.447     foxr     6833: 
                   6834: 	    # TODO - make this a persistent hash not an array.
                   6835: 
                   6836: 
                   6837: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6838: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6839: 	    $response_number++;
                   6840: 
                   6841: 	    $bubble_line +=  $lines;
                   6842: 	    $total_lines +=  $lines;
1.435     foxr     6843: 	}
                   6844: 
1.191     albertel 6845:     }
                   6846:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6847: 
                   6848:     &save_bubble_lines();
1.330     albertel 6849:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6850: 	$total_lines;
1.257     albertel 6851:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6852: }
                   6853: 
1.423     albertel 6854: =pod
                   6855: 
                   6856: =item scantron_validate_missingbubbles
                   6857: 
1.424     albertel 6858:    Validates all scanlines in the selected file to not have any
1.447     foxr     6859:     answers that don't have bubbles that have not been verified
                   6860:     to be bubble free.
1.424     albertel 6861: 
1.423     albertel 6862: =cut
                   6863: 
1.157     albertel 6864: sub scantron_validate_missingbubbles {
                   6865:     my ($r,$currentphase) = @_;
                   6866:     #get student info
                   6867:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6868:     my %idmap=&username_to_idmap($classlist);
                   6869: 
                   6870:     #get scantron line setup
1.257     albertel 6871:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6872:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6873:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6874:     if (!$max_bubble) { $max_bubble=2**31; }
                   6875:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6876: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6877: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6878: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6879: 						 $scan_data);
                   6880: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6881: 	my @to_correct;
1.470     foxr     6882: 	
                   6883: 	# Probably here's where the error is...
                   6884: 
1.157     albertel 6885: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6886: 	    if ($missing > $max_bubble) { next; }
                   6887: 	    push(@to_correct,$missing);
                   6888: 	}
                   6889: 	if (@to_correct) {
                   6890: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6891: 				     $line,'missingbubble',\@to_correct);
                   6892: 	    return (1,$currentphase);
                   6893: 	}
                   6894: 
                   6895:     }
                   6896:     return (0,$currentphase+1);
                   6897: }
                   6898: 
1.423     albertel 6899: =pod
                   6900: 
                   6901: =item scantron_process_students
                   6902: 
                   6903:    Routine that does the actual grading of the bubble sheet information.
                   6904: 
                   6905:    The parsed scanline hash is added to %env 
                   6906: 
                   6907:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6908:    foreach resource , with the form data of
                   6909: 
                   6910: 	'submitted'     =>'scantron' 
                   6911: 	'grade_target'  =>'grade',
                   6912: 	'grade_username'=> username of student
                   6913: 	'grade_domain'  => domain of student
                   6914: 	'grade_courseid'=> of course
                   6915: 	'grade_symb'    => symb of resource to grade
                   6916: 
                   6917:     This triggers a grading pass. The problem grading code takes care
                   6918:     of converting the bubbled letter information (now in %env) into a
                   6919:     valid submission.
                   6920: 
                   6921: =cut
                   6922: 
1.82      albertel 6923: sub scantron_process_students {
1.75      albertel 6924:     my ($r) = @_;
1.257     albertel 6925:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6926:     my ($symb)=&get_symb($r);
1.81      albertel 6927:     if (!$symb) {return '';}
1.324     albertel 6928:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6929: 
1.257     albertel 6930:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6931:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6932:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6933:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6934:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6935:     my $map=$navmap->getResourceByUrl($sequence);
                   6936:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6937: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6938:     my $result= <<SCANTRONFORM;
1.81      albertel 6939: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6940:   <input type="hidden" name="command" value="scantron_configphase" />
                   6941:   $default_form_data
                   6942: SCANTRONFORM
1.82      albertel 6943:     $r->print($result);
                   6944: 
                   6945:     my @delayqueue;
1.140     albertel 6946:     my %completedstudents;
                   6947:     
1.200     albertel 6948:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6949:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6950:  				    'Scantron Progress',$count,
1.195     albertel 6951: 				    'inline',undef,'scantronupload');
1.140     albertel 6952:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6953: 					  'Processing first student');
                   6954:     my $start=&Time::HiRes::time();
1.158     albertel 6955:     my $i=-1;
1.200     albertel 6956:     my ($uname,$udom,$started);
1.447     foxr     6957: 
                   6958:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6959: 
1.157     albertel 6960:     while ($i<$scanlines->{'count'}) {
                   6961:  	($uname,$udom)=('','');
                   6962:  	$i++;
1.200     albertel 6963:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6964:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6965: 	if ($started) {
                   6966: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6967: 						     'last student');
                   6968: 	}
                   6969: 	$started=1;
1.157     albertel 6970:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6971:  						 $scan_data);
                   6972:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6973:  					      \%idmap,$i)) {
                   6974:   	    &scantron_add_delay(\@delayqueue,$line,
                   6975:  				'Unable to find a student that matches',1);
                   6976:  	    next;
                   6977:   	}
                   6978:  	if (exists $completedstudents{$uname}) {
                   6979:  	    &scantron_add_delay(\@delayqueue,$line,
                   6980:  				'Student '.$uname.' has multiple sheets',2);
                   6981:  	    next;
                   6982:  	}
                   6983:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6984: 
                   6985: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6986:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6987: 
                   6988: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6989: 	    &scantron_putfile($scanlines,$scan_data);
                   6990: 	}
1.161     albertel 6991: 	
                   6992: 	my $i=0;
1.83      albertel 6993: 	foreach my $resource (@resources) {
1.85      albertel 6994: 	    $i++;
1.193     albertel 6995: 	    my %form=('submitted'     =>'scantron',
                   6996: 		      'grade_target'  =>'grade',
                   6997: 		      'grade_username'=>$uname,
                   6998: 		      'grade_domain'  =>$udom,
1.257     albertel 6999: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7000: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7001: 	    if (exists($scan_record->{'scantron.CODE'})
                   7002: 		&& 
                   7003: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7004: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7005: 	    } else {
                   7006: 		$form{'CODE'}='';
1.193     albertel 7007: 	    }
                   7008: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7009: 	    if ($result ne '') {
                   7010: 	    }
1.213     albertel 7011: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7012: 	}
1.140     albertel 7013: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7014: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7015:     } continue {
1.330     albertel 7016: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7017: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7018:     }
1.140     albertel 7019:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7020: #    my $lasttime = &Time::HiRes::time()-$start;
                   7021: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7022: 
1.200     albertel 7023:     $r->print("</form>");
1.324     albertel 7024:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7025:     return '';
1.75      albertel 7026: }
1.157     albertel 7027: 
1.423     albertel 7028: =pod
                   7029: 
                   7030: =item scantron_upload_scantron_data
                   7031: 
                   7032:     Creates the screen for adding a new bubble sheet data file to a course.
                   7033: 
                   7034: =cut
                   7035: 
1.157     albertel 7036: sub scantron_upload_scantron_data {
                   7037:     my ($r)=@_;
1.257     albertel 7038:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7039:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7040: 							  'domainid',
                   7041: 							  'coursename');
1.257     albertel 7042:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7043: 						   'domainid');
1.324     albertel 7044:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 7045:     $r->print(<<UPLOAD);
                   7046: <script type="text/javascript" language="javascript">
                   7047:     function checkUpload(formname) {
                   7048: 	if (formname.upfile.value == "") {
                   7049: 	    alert("Please use the browse button to select a file from your local directory.");
                   7050: 	    return false;
                   7051: 	}
                   7052: 	formname.submit();
                   7053:     }
                   7054: </script>
                   7055: 
                   7056: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7057: $default_form_data
1.181     albertel 7058: <table>
                   7059: <tr><td>$select_link </td></tr>
                   7060: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7061: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7062: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7063: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7064: </table>
1.157     albertel 7065: <input name='command' value='scantronupload_save' type='hidden' />
                   7066: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7067: </form>
                   7068: UPLOAD
                   7069:     return '';
                   7070: }
                   7071: 
1.423     albertel 7072: =pod
                   7073: 
                   7074: =item scantron_upload_scantron_data_save
                   7075: 
                   7076:    Adds a provided bubble information data file to the course if user
                   7077:    has the correct privileges to do so.  
                   7078: 
                   7079: =cut
                   7080: 
1.157     albertel 7081: sub scantron_upload_scantron_data_save {
                   7082:     my($r)=@_;
1.324     albertel 7083:     my ($symb)=&get_symb($r,1);
1.182     albertel 7084:     my $doanotherupload=
                   7085: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7086: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7087: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7088: 	'</form>'."\n";
1.257     albertel 7089:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7090: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7091: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7092: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7093: 	if ($symb) {
1.324     albertel 7094: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7095: 	} else {
                   7096: 	    $r->print($doanotherupload);
                   7097: 	}
1.162     albertel 7098: 	return '';
                   7099:     }
1.257     albertel 7100:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7101:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7102:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7103:     #FIXME
                   7104:     #copied from lonnet::userfileupload()
                   7105:     #make that function able to target a specified course
                   7106:     # Replace Windows backslashes by forward slashes
                   7107:     $fname=~s/\\/\//g;
                   7108:     # Get rid of everything but the actual filename
                   7109:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7110:     # Replace spaces by underscores
                   7111:     $fname=~s/\s+/\_/g;
                   7112:     # Replace all other weird characters by nothing
                   7113:     $fname=~s/[^\w\.\-]//g;
                   7114:     # See if there is anything left
                   7115:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7116:     my $uploadedfile=$fname;
1.157     albertel 7117:     $fname='scantron_orig_'.$fname;
1.257     albertel 7118:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7119: 	$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 7120:     } else {
1.275     albertel 7121: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7122: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7123: 	    $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 7124: 	} else {
1.398     albertel 7125: 	    $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 7126: 	}
                   7127:     }
1.174     albertel 7128:     if ($symb) {
1.209     ng       7129: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7130:     } else {
1.182     albertel 7131: 	$r->print($doanotherupload);
1.174     albertel 7132:     }
1.157     albertel 7133:     return '';
                   7134: }
                   7135: 
1.423     albertel 7136: =pod
                   7137: 
                   7138: =item valid_file
                   7139: 
1.424     albertel 7140:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7141: 
                   7142: =cut
                   7143: 
1.202     albertel 7144: sub valid_file {
                   7145:     my ($requested_file)=@_;
                   7146:     foreach my $filename (sort(&scantron_filenames())) {
                   7147: 	if ($requested_file eq $filename) { return 1; }
                   7148:     }
                   7149:     return 0;
                   7150: }
                   7151: 
1.423     albertel 7152: =pod
                   7153: 
                   7154: =item scantron_download_scantron_data
                   7155: 
                   7156:    Shows a list of the three internal files (original, corrected,
                   7157:    skipped) for a specific bubble sheet data file that exists in the
                   7158:    course.
                   7159: 
                   7160: =cut
                   7161: 
1.202     albertel 7162: sub scantron_download_scantron_data {
                   7163:     my ($r)=@_;
1.324     albertel 7164:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7165:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7166:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7167:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7168:     if (! &valid_file($file)) {
                   7169: 	$r->print(<<ERROR);
                   7170: 	<p>
                   7171: 	    The requested file name was invalid.
                   7172:         </p>
                   7173: ERROR
1.324     albertel 7174: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7175: 	return;
                   7176:     }
                   7177:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7178:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7179:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7180:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7181:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7182:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7183:     $r->print(<<DOWNLOAD);
                   7184:     <p>
                   7185: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7186:     </p>
                   7187:     <p>
                   7188: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7189:     </p>
                   7190:     <p>
                   7191: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7192:     </p>
                   7193: DOWNLOAD
1.324     albertel 7194:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7195:     return '';
                   7196: }
1.157     albertel 7197: 
1.423     albertel 7198: =pod
                   7199: 
                   7200: =back
                   7201: 
                   7202: =cut
                   7203: 
1.75      albertel 7204: #-------- end of section for handling grading scantron forms -------
                   7205: #
                   7206: #-------------------------------------------------------------------
                   7207: 
1.72      ng       7208: #-------------------------- Menu interface -------------------------
                   7209: #
                   7210: #--- Show a Grading Menu button - Calls the next routine ---
                   7211: sub show_grading_menu_form {
1.324     albertel 7212:     my ($symb)=@_;
1.125     ng       7213:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7214: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7215: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7216: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7217: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7218: 	'</form>'."\n";
                   7219:     return $result;
                   7220: }
                   7221: 
1.77      ng       7222: # -- Retrieve choices for grading form
                   7223: sub savedState {
                   7224:     my %savedState = ();
1.257     albertel 7225:     if ($env{'form.saveState'}) {
                   7226: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7227: 	    my ($key,$value) = split(/=/,$_,2);
                   7228: 	    $savedState{$key} = $value;
                   7229: 	}
                   7230:     }
                   7231:     return \%savedState;
                   7232: }
1.76      ng       7233: 
1.443     banghart 7234: sub grading_menu {
                   7235:     my ($request) = @_;
                   7236:     my ($symb)=&get_symb($request);
                   7237:     if (!$symb) {return '';}
                   7238:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7239:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7240: 
1.444     banghart 7241:     $request->print($table);
1.443     banghart 7242:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7243:                   'handgrade'=>$hdgrade,
                   7244:                   'probTitle'=>$probTitle,
                   7245:                   'command'=>'submit_options',
                   7246:                   'saveState'=>"",
                   7247:                   'gradingMenu'=>1,
                   7248:                   'showgrading'=>"yes");
                   7249:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7250:     my @menu = ({ url => $url,
                   7251:                      name => &mt('Manual Grading/View Submissions'),
                   7252:                      short_description => 
                   7253:     &mt('Start the process of hand grading submissions.'),
                   7254:                  });
                   7255:     $fields{'command'} = 'csvform';
                   7256:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7257:     push (@menu, { url => $url,
                   7258:                    name => &mt('Upload Scores'),
                   7259:                    short_description => 
                   7260:             &mt('Specify a file containing the class scores for current resource.')});
                   7261:     $fields{'command'} = 'processclicker';
                   7262:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7263:     push (@menu, { url => $url,
                   7264:                    name => &mt('Process Clicker'),
                   7265:                    short_description => 
                   7266:             &mt('Specify a file containing the clicker information for this resource.')});
                   7267:     $fields{'command'} = 'scantron_selectphase';
                   7268:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7269:     push (@menu, { url => $url,
1.454     banghart 7270:                    name => &mt('Grade/Manage Scantron Forms'),
                   7271:                    short_description => 
                   7272:             &mt('')});
1.443     banghart 7273:     $fields{'command'} = 'verify';
                   7274:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7275:     push (@menu, { url => "",
1.443     banghart 7276:                    name => &mt('Verify Receipt'),
                   7277:                    short_description => 
                   7278:             &mt('')});
                   7279:     #
                   7280:     # Create the menu
                   7281:     my $Str;
1.444     banghart 7282:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7283:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7284:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7285:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7286: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7287: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7288: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7289: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7290: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7291: 
1.443     banghart 7292:     foreach my $menudata (@menu) {
1.445     banghart 7293:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7294:             $Str .='    <h3><a '.
                   7295:                 $menudata->{'jscript'}.
                   7296:                 ' href="'.
                   7297:                 $menudata->{'url'}.'" >'.
                   7298:                 $menudata->{'name'}."</a></h3>\n";
                   7299:         } else {
1.458     banghart 7300:             $Str .='    <h3><input type="button" value="Verify Receipt" '.
1.445     banghart 7301:                 $menudata->{'jscript'}.
1.458     banghart 7302:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7303:                 ' /></h3>';
1.446     banghart 7304:             $Str .= ('&nbsp;'x8).
                   7305:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7306:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7307:         }
1.443     banghart 7308:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7309:             "\n";
                   7310:     }
                   7311:     $Str .="</dl>\n";
1.444     banghart 7312:     $Str .="</form>\n";
1.443     banghart 7313:     $request->print(<<GRADINGMENUJS);
                   7314: <script type="text/javascript" language="javascript">
                   7315:     function checkChoice(formname,val,cmdx) {
                   7316: 	if (val <= 2) {
                   7317: 	    var cmd = radioSelection(formname.radioChoice);
                   7318: 	    var cmdsave = cmd;
                   7319: 	} else {
                   7320: 	    cmd = cmdx;
                   7321: 	    cmdsave = 'submission';
                   7322: 	}
                   7323: 	formname.command.value = cmd;
                   7324: 	if (val < 5) formname.submit();
                   7325: 	if (val == 5) {
1.458     banghart 7326: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7327: 	        return false;
                   7328: 	    } else {
                   7329: 	        formname.submit();
                   7330: 	    }
1.445     banghart 7331: 	}
                   7332:     }
1.443     banghart 7333: 
                   7334:     function checkReceiptNo(formname,nospace) {
                   7335: 	var receiptNo = formname.receipt.value;
                   7336: 	var checkOpt = false;
                   7337: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7338: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7339: 	if (checkOpt) {
                   7340: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7341: 	    formname.receipt.value = "";
                   7342: 	    formname.receipt.focus();
                   7343: 	    return false;
                   7344: 	}
                   7345: 	return true;
                   7346:     }
                   7347: </script>
                   7348: GRADINGMENUJS
                   7349:     &commonJSfunctions($request);
                   7350:     return $Str;    
                   7351: }
                   7352: 
                   7353: 
                   7354: #--- Displays the submissions first page -------
                   7355: sub submit_options {
1.72      ng       7356:     my ($request) = @_;
1.324     albertel 7357:     my ($symb)=&get_symb($request);
1.72      ng       7358:     if (!$symb) {return '';}
1.76      ng       7359:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7360: 
                   7361:     $request->print(<<GRADINGMENUJS);
                   7362: <script type="text/javascript" language="javascript">
1.116     ng       7363:     function checkChoice(formname,val,cmdx) {
                   7364: 	if (val <= 2) {
                   7365: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7366: 	    var cmdsave = cmd;
1.116     ng       7367: 	} else {
                   7368: 	    cmd = cmdx;
1.118     ng       7369: 	    cmdsave = 'submission';
1.116     ng       7370: 	}
                   7371: 	formname.command.value = cmd;
1.118     ng       7372: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7373: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7374: 	if (val < 5) formname.submit();
                   7375: 	if (val == 5) {
1.72      ng       7376: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7377: 	    formname.submit();
                   7378: 	}
1.238     albertel 7379: 	if (val < 7) formname.submit();
1.72      ng       7380:     }
                   7381: 
                   7382:     function checkReceiptNo(formname,nospace) {
                   7383: 	var receiptNo = formname.receipt.value;
                   7384: 	var checkOpt = false;
                   7385: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7386: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7387: 	if (checkOpt) {
                   7388: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7389: 	    formname.receipt.value = "";
                   7390: 	    formname.receipt.focus();
                   7391: 	    return false;
                   7392: 	}
                   7393: 	return true;
                   7394:     }
                   7395: </script>
                   7396: GRADINGMENUJS
1.118     ng       7397:     &commonJSfunctions($request);
1.324     albertel 7398:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7399:     my $result;
1.76      ng       7400:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7401:     my $savedState = &savedState();
1.118     ng       7402:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7403:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7404:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7405:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7406: 
                   7407:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7408: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7409: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7410: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7411: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7412: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7413: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7414: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7415: 
1.472     albertel 7416:     $result.='
                   7417:     <div class="LC_grade_select_mode">
1.473     albertel 7418:       <div class="LC_grade_select_mode_current">
                   7419:         <h2>
                   7420:           '.&mt('Grade Current Resource').'
                   7421:         </h2>
                   7422:         <div class="LC_grade_select_mode_body">
                   7423:           <div class="LC_grades_resource_info">
                   7424:            '.$table.'
                   7425:           </div>
                   7426:           <div class="LC_grade_select_mode_selector">
                   7427:              <div class="LC_grade_select_mode_selector_header">
                   7428:                 '.&mt('Sections').'
                   7429:              </div>
                   7430:              <div class="LC_grade_select_mode_selector_body">
                   7431: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7432:     if (ref($sections)) {
1.472     albertel 7433: 	foreach my $section (sort (@$sections)) {
                   7434: 	    $result.='<option value="'.$section.'" '.
                   7435: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7436: 	}
1.116     ng       7437:     }
1.401     albertel 7438:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7439:     $result.='
1.473     albertel 7440:              </div>
                   7441:           </div>
                   7442:           <div class="LC_grade_select_mode_selector">
                   7443:              <div class="LC_grade_select_mode_selector_header">
                   7444:                 '.&mt('Groups').'
                   7445:              </div>
                   7446:              <div class="LC_grade_select_mode_selector_body">
                   7447:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7448:              </div>
1.472     albertel 7449:           </div>
1.473     albertel 7450:           <div class="LC_grade_select_mode_selector">
                   7451:              <div class="LC_grade_select_mode_selector_header">
                   7452:                 '.&mt('Access Status').'
                   7453:              </div>
                   7454:              <div class="LC_grade_select_mode_selector_body">
                   7455:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7456:              </div>
1.472     albertel 7457:           </div>
1.473     albertel 7458:           <div class="LC_grade_select_mode_selector">
                   7459:              <div class="LC_grade_select_mode_selector_header">
                   7460:                 '.&mt('Submission Status').'
                   7461:              </div>
                   7462:              <div class="LC_grade_select_mode_selector_body">
                   7463:                <select name="submitonly" size="5">
                   7464: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7465: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7466: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7467: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7468:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7469:                </select>
                   7470:              </div>
1.472     albertel 7471:           </div>
1.473     albertel 7472:           <div class="LC_grade_select_mode_type_body">
                   7473:             <div class="LC_grade_select_mode_type">
                   7474:               <label>
                   7475:                 <input type="radio" name="radioChoice" value="submission" '.
                   7476:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7477:              &mt('Select individual students to grade and view submissions.').'
                   7478: 	      </label> 
                   7479:             </div>
                   7480:             <div class="LC_grade_select_mode_type">
                   7481: 	      <label>
                   7482:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7483:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7484:                     &mt('Grade all selected students in a grading table.').'
                   7485:               </label>
                   7486:             </div>
                   7487:             <div class="LC_grade_select_mode_type">
                   7488: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7489:             </div>
1.472     albertel 7490:           </div>
1.473     albertel 7491:         </div>
                   7492:       </div>
                   7493:       <div class="LC_grade_select_mode_page">
                   7494:         <h2>
                   7495:          '.&mt('Grade Complete Folder for One Student').'
                   7496:         </h2>
                   7497:         <div class="LC_grades_select_mode_body">
                   7498:           <div class="LC_grade_select_mode_type_body">
                   7499:             <div class="LC_grade_select_mode_type">
                   7500:               <label>
                   7501:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7502: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7503:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7504:               </label>
                   7505:             </div>
                   7506:             <div class="LC_grade_select_mode_type">
                   7507: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7508:             </div>
1.472     albertel 7509:           </div>
                   7510:         </div>
                   7511:       </div>
                   7512:     </div>
                   7513:   </form>';
1.44      ng       7514:     return $result;
1.2       albertel 7515: }
                   7516: 
1.285     albertel 7517: sub reset_perm {
                   7518:     undef(%perm);
                   7519: }
                   7520: 
                   7521: sub init_perm {
                   7522:     &reset_perm();
1.300     albertel 7523:     foreach my $test_perm ('vgr','mgr','opa') {
                   7524: 
                   7525: 	my $scope = $env{'request.course.id'};
                   7526: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7527: 
                   7528: 	    $scope .= '/'.$env{'request.course.sec'};
                   7529: 	    if ( $perm{$test_perm}=
                   7530: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7531: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7532: 	    } else {
                   7533: 		delete($perm{$test_perm});
                   7534: 	    }
1.285     albertel 7535: 	}
                   7536:     }
                   7537: }
                   7538: 
1.400     www      7539: sub gather_clicker_ids {
1.408     albertel 7540:     my %clicker_ids;
1.400     www      7541: 
                   7542:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7543: 
                   7544:     # Set up a couple variables.
1.407     albertel 7545:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7546:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7547:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7548: 
1.407     albertel 7549:     foreach my $student (keys(%$classlist)) {
1.438     www      7550:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7551:         my $username = $classlist->{$student}->[$username_idx];
                   7552:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7553:         my $clickers =
1.408     albertel 7554: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7555:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7556:             $id=~s/^[\#0]+//;
1.421     www      7557:             $id=~s/[\-\:]//g;
1.407     albertel 7558:             if (exists($clicker_ids{$id})) {
1.408     albertel 7559: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7560:             } else {
1.408     albertel 7561: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7562:             }
                   7563:         }
                   7564:     }
1.407     albertel 7565:     return %clicker_ids;
1.400     www      7566: }
                   7567: 
1.402     www      7568: sub gather_adv_clicker_ids {
1.408     albertel 7569:     my %clicker_ids;
1.402     www      7570:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7571:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7572:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7573:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7574:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7575:             my ($puname,$pudom)=split(/\:/,$person);
                   7576:             my $clickers =
1.408     albertel 7577: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7578:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7579: 		$id=~s/^[\#0]+//;
1.421     www      7580:                 $id=~s/[\-\:]//g;
1.408     albertel 7581: 		if (exists($clicker_ids{$id})) {
                   7582: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7583: 		} else {
                   7584: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7585: 		}
1.405     www      7586:             }
1.402     www      7587:         }
                   7588:     }
1.407     albertel 7589:     return %clicker_ids;
1.402     www      7590: }
                   7591: 
1.413     www      7592: sub clicker_grading_parameters {
                   7593:     return ('gradingmechanism' => 'scalar',
                   7594:             'upfiletype' => 'scalar',
                   7595:             'specificid' => 'scalar',
                   7596:             'pcorrect' => 'scalar',
                   7597:             'pincorrect' => 'scalar');
                   7598: }
                   7599: 
1.400     www      7600: sub process_clicker {
                   7601:     my ($r)=@_;
                   7602:     my ($symb)=&get_symb($r);
                   7603:     if (!$symb) {return '';}
                   7604:     my $result=&checkforfile_js();
                   7605:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7606:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7607:     $result.=$table;
                   7608:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7609:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7610:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7611:         '.</b></td></tr>'."\n";
                   7612:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7613: # Attempt to restore parameters from last session, set defaults if not present
                   7614:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7615:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7616:                                                  \%Saveable_Parameters);
                   7617:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7618:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7619:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7620:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7621: 
                   7622:     my %checked;
                   7623:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7624:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7625:           $checked{$gradingmechanism}="checked='checked'";
                   7626:        }
                   7627:     }
                   7628: 
1.400     www      7629:     my $upload=&mt("Upload File");
                   7630:     my $type=&mt("Type");
1.402     www      7631:     my $attendance=&mt("Award points just for participation");
                   7632:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7633:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7634:     my $pcorrect=&mt("Percentage points for correct solution");
                   7635:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7636:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7637: 						   ('iclicker' => 'i>clicker',
                   7638:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7639:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7640:     $result.=<<ENDUPFORM;
1.402     www      7641: <script type="text/javascript">
                   7642: function sanitycheck() {
                   7643: // Accept only integer percentages
                   7644:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7645:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7646: // Find out grading choice
                   7647:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7648:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7649:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7650:       }
                   7651:    }
                   7652: // By default, new choice equals user selection
                   7653:    newgradingchoice=gradingchoice;
                   7654: // Not good to give more points for false answers than correct ones
                   7655:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7656:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7657:    }
                   7658: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7659:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7660:       document.forms.gradesupload.pcorrect.value=100;
                   7661:       document.forms.gradesupload.pincorrect.value=100;
                   7662:    }
                   7663: // If the values are different, cannot be attendance only
                   7664:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7665:        (gradingchoice=='attendance')) {
                   7666:        newgradingchoice='personnel';
                   7667:    }
                   7668: // Change grading choice to new one
                   7669:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7670:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7671:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7672:       } else {
                   7673:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7674:       }
                   7675:    }
                   7676: // Remember the old state
                   7677:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7678: }
                   7679: </script>
1.400     www      7680: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7681: <input type="hidden" name="symb" value="$symb" />
                   7682: <input type="hidden" name="command" value="processclickerfile" />
                   7683: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7684: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7685: <input type="file" name="upfile" size="50" />
                   7686: <br /><label>$type: $selectform</label>
1.451     albertel 7687: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7688: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7689: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7690: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7691: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7692: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7693: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7694: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7695: </form>
                   7696: ENDUPFORM
                   7697:     $result.='</td></tr></table>'."\n".
                   7698:              '</td></tr></table><br /><br />'."\n";
                   7699:     $result.=&show_grading_menu_form($symb);
                   7700:     return $result;
                   7701: }
                   7702: 
                   7703: sub process_clicker_file {
                   7704:     my ($r)=@_;
                   7705:     my ($symb)=&get_symb($r);
                   7706:     if (!$symb) {return '';}
1.413     www      7707: 
                   7708:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7709:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7710:                                               \%Saveable_Parameters);
                   7711: 
1.400     www      7712:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7713:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7714: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7715: 	return $result.&show_grading_menu_form($symb);
1.404     www      7716:     }
1.407     albertel 7717:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7718:     my %correct_ids;
1.404     www      7719:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7720: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7721:     }
                   7722:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7723: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7724: 	   $correct_id=~tr/a-z/A-Z/;
                   7725: 	   $correct_id=~s/\s//gs;
                   7726: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7727:            $correct_id=~s/[\-\:]//g;
1.414     www      7728:            if ($correct_id) {
                   7729: 	      $correct_ids{$correct_id}='specified';
                   7730:            }
                   7731:         }
1.400     www      7732:     }
1.404     www      7733:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7734: 	$result.=&mt('Score based on attendance only');
1.404     www      7735:     } else {
1.408     albertel 7736: 	my $number=0;
1.411     www      7737: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7738: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7739: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7740: 	    if ($correct_ids{$id} eq 'specified') {
                   7741: 		$result.=&mt('specified');
                   7742: 	    } else {
                   7743: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7744: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7745: 	    }
                   7746: 	    $number++;
                   7747: 	}
1.411     www      7748:         $result.="</p>\n";
1.408     albertel 7749: 	if ($number==0) {
                   7750: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7751: 	    return $result.&show_grading_menu_form($symb);
                   7752: 	}
1.404     www      7753:     }
1.405     www      7754:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7755:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7756: 		     '<span class="LC_error">',
                   7757: 		     '</span>',
                   7758: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7759:         return $result.&show_grading_menu_form($symb);
                   7760:     }
1.410     www      7761: 
                   7762: # Were able to get all the info needed, now analyze the file
                   7763: 
1.411     www      7764:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7765:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7766:     my $heading=&mt('Scanning clicker file');
                   7767:     $result.=(<<ENDHEADER);
                   7768: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7769: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7770: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7771: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7772: <input type="hidden" name="symb" value="$symb" />
                   7773: <input type="hidden" name="command" value="assignclickergrades" />
                   7774: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7775: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7776: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7777: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7778: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7779: ENDHEADER
1.408     albertel 7780:     my %responses;
                   7781:     my @questiontitles;
1.405     www      7782:     my $errormsg='';
                   7783:     my $number=0;
                   7784:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7785: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7786:     }
1.419     www      7787:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7788:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7789:     }
1.411     www      7790:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7791:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7792:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7793:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7794:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7795:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7796:              '<br />';
1.414     www      7797: # Remember Question Titles
                   7798: # FIXME: Possibly need delimiter other than ":"
                   7799:     for (my $i=0;$i<$number;$i++) {
                   7800:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7801:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7802:     }
1.411     www      7803:     my $correct_count=0;
                   7804:     my $student_count=0;
                   7805:     my $unknown_count=0;
1.414     www      7806: # Match answers with usernames
                   7807: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7808:     foreach my $id (keys(%responses)) {
1.410     www      7809:        if ($correct_ids{$id}) {
1.414     www      7810:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7811:           $correct_count++;
1.410     www      7812:        } elsif ($clicker_ids{$id}) {
1.437     www      7813:           if ($clicker_ids{$id}=~/\,/) {
                   7814: # More than one user with the same clicker!
                   7815:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7816:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7817:                            "<select name='multi".$id."'>";
                   7818:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7819:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7820:              }
                   7821:              $result.='</select>';
                   7822:              $unknown_count++;
                   7823:           } else {
                   7824: # Good: found one and only one user with the right clicker
                   7825:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7826:              $student_count++;
                   7827:           }
1.410     www      7828:        } else {
1.411     www      7829:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7830:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7831:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7832:                    "\n".&mt("Domain").": ".
                   7833:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7834:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7835:           $unknown_count++;
1.410     www      7836:        }
1.405     www      7837:     }
1.412     www      7838:     $result.='<hr />'.
                   7839:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7840:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7841:        if ($correct_count==0) {
                   7842:           $errormsg.="Found no correct answers answers for grading!";
                   7843:        } elsif ($correct_count>1) {
1.414     www      7844:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7845:        }
                   7846:     }
1.428     www      7847:     if ($number<1) {
                   7848:        $errormsg.="Found no questions.";
                   7849:     }
1.412     www      7850:     if ($errormsg) {
                   7851:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7852:     } else {
                   7853:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7854:     }
                   7855:     $result.='</form></td></tr></table>'."\n".
1.410     www      7856:              '</td></tr></table><br /><br />'."\n";
1.404     www      7857:     return $result.&show_grading_menu_form($symb);
1.400     www      7858: }
                   7859: 
1.405     www      7860: sub iclicker_eval {
1.406     www      7861:     my ($questiontitles,$responses)=@_;
1.405     www      7862:     my $number=0;
                   7863:     my $errormsg='';
                   7864:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7865:         my %components=&Apache::loncommon::record_sep($line);
                   7866:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7867: 	if ($entries[0] eq 'Question') {
                   7868: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7869: 		$$questiontitles[$number]=$entries[$i];
                   7870: 		$number++;
                   7871: 	    }
                   7872: 	}
                   7873: 	if ($entries[0]=~/^\#/) {
                   7874: 	    my $id=$entries[0];
                   7875: 	    my @idresponses;
                   7876: 	    $id=~s/^[\#0]+//;
                   7877: 	    for (my $i=0;$i<$number;$i++) {
                   7878: 		my $idx=3+$i*6;
                   7879: 		push(@idresponses,$entries[$idx]);
                   7880: 	    }
                   7881: 	    $$responses{$id}=join(',',@idresponses);
                   7882: 	}
1.405     www      7883:     }
                   7884:     return ($errormsg,$number);
                   7885: }
                   7886: 
1.419     www      7887: sub interwrite_eval {
                   7888:     my ($questiontitles,$responses)=@_;
                   7889:     my $number=0;
                   7890:     my $errormsg='';
1.420     www      7891:     my $skipline=1;
                   7892:     my $questionnumber=0;
                   7893:     my %idresponses=();
1.419     www      7894:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7895:         my %components=&Apache::loncommon::record_sep($line);
                   7896:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7897:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7898:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7899:         next if $skipline;
                   7900:         if ($entries[0]!=$questionnumber) {
                   7901:            $questionnumber=$entries[0];
                   7902:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7903:            $number++;
1.419     www      7904:         }
1.420     www      7905:         my $id=$entries[4];
                   7906:         $id=~s/^[\#0]+//;
1.421     www      7907:         $id=~s/^v\d*\://i;
                   7908:         $id=~s/[\-\:]//g;
1.420     www      7909:         $idresponses{$id}[$number]=$entries[6];
                   7910:     }
                   7911:     foreach my $id (keys %idresponses) {
                   7912:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7913:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7914:     }
                   7915:     return ($errormsg,$number);
                   7916: }
                   7917: 
1.414     www      7918: sub assign_clicker_grades {
                   7919:     my ($r)=@_;
                   7920:     my ($symb)=&get_symb($r);
                   7921:     if (!$symb) {return '';}
1.416     www      7922: # See which part we are saving to
                   7923:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7924: # FIXME: This should probably look for the first handgradeable part
                   7925:     my $part=$$partlist[0];
                   7926: # Start screen output
1.414     www      7927:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7928: 
1.414     www      7929:     my $heading=&mt('Assigning grades based on clicker file');
                   7930:     $result.=(<<ENDHEADER);
                   7931: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7932: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7933: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7934: ENDHEADER
                   7935: # Get correct result
                   7936: # FIXME: Possibly need delimiter other than ":"
                   7937:     my @correct=();
1.415     www      7938:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7939:     my $number=$env{'form.number'};
                   7940:     if ($gradingmechanism ne 'attendance') {
1.414     www      7941:        foreach my $key (keys(%env)) {
                   7942:           if ($key=~/^form\.correct\:/) {
                   7943:              my @input=split(/\,/,$env{$key});
                   7944:              for (my $i=0;$i<=$#input;$i++) {
                   7945:                  if (($correct[$i]) && ($input[$i]) &&
                   7946:                      ($correct[$i] ne $input[$i])) {
                   7947:                     $result.='<br /><span class="LC_warning">'.
                   7948:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7949:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7950:                  } elsif ($input[$i]) {
                   7951:                     $correct[$i]=$input[$i];
                   7952:                  }
                   7953:              }
                   7954:           }
                   7955:        }
1.415     www      7956:        for (my $i=0;$i<$number;$i++) {
1.414     www      7957:           if (!$correct[$i]) {
                   7958:              $result.='<br /><span class="LC_error">'.
                   7959:                       &mt('No correct result given for question "[_1]"!',
                   7960:                           $env{'form.question:'.$i}).'</span>';
                   7961:           }
                   7962:        }
                   7963:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7964:     }
                   7965: # Start grading
1.415     www      7966:     my $pcorrect=$env{'form.pcorrect'};
                   7967:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7968:     my $storecount=0;
1.415     www      7969:     foreach my $key (keys(%env)) {
1.420     www      7970:        my $user='';
1.415     www      7971:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7972:           $user=$1;
                   7973:        }
                   7974:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7975:           my $id=$1;
                   7976:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7977:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7978:           } elsif ($env{'form.multi'.$id}) {
                   7979:              $user=$env{'form.multi'.$id};
1.420     www      7980:           }
                   7981:        }
                   7982:        if ($user) { 
1.415     www      7983:           my @answer=split(/\,/,$env{$key});
                   7984:           my $sum=0;
                   7985:           for (my $i=0;$i<$number;$i++) {
                   7986:              if ($answer[$i]) {
                   7987:                 if ($gradingmechanism eq 'attendance') {
                   7988:                    $sum+=$pcorrect;
                   7989:                 } else {
                   7990:                    if ($answer[$i] eq $correct[$i]) {
                   7991:                       $sum+=$pcorrect;
                   7992:                    } else {
                   7993:                       $sum+=$pincorrect;
                   7994:                    }
                   7995:                 }
                   7996:              }
                   7997:           }
1.416     www      7998:           my $ave=$sum/(100*$number);
                   7999: # Store
                   8000:           my ($username,$domain)=split(/\:/,$user);
                   8001:           my %grades=();
                   8002:           $grades{"resource.$part.solved"}='correct_by_override';
                   8003:           $grades{"resource.$part.awarded"}=$ave;
                   8004:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8005:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8006:                                                  $env{'request.course.id'},
                   8007:                                                  $domain,$username);
                   8008:           if ($returncode ne 'ok') {
                   8009:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8010:           } else {
                   8011:              $storecount++;
                   8012:           }
1.415     www      8013:        }
                   8014:     }
                   8015: # We are done
1.416     www      8016:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8017:              '</td></tr></table>'."\n".
1.414     www      8018:              '</td></tr></table><br /><br />'."\n";
                   8019:     return $result.&show_grading_menu_form($symb);
                   8020: }
                   8021: 
1.1       albertel 8022: sub handler {
1.41      ng       8023:     my $request=$_[0];
1.434     albertel 8024:     &reset_caches();
1.257     albertel 8025:     if ($env{'browser.mathml'}) {
1.141     www      8026: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8027:     } else {
1.141     www      8028: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8029:     }
                   8030:     $request->send_http_header;
1.44      ng       8031:     return '' if $request->header_only;
1.41      ng       8032:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8033:     my $symb=&get_symb($request,1);
1.160     albertel 8034:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8035:     my $command=$commands[0];
1.447     foxr     8036: 
1.160     albertel 8037:     if ($#commands > 0) {
                   8038: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8039:     }
1.447     foxr     8040: 
                   8041: 
1.353     albertel 8042:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8043:     if ($symb eq '' && $command eq '') {
1.257     albertel 8044: 	if ($env{'user.adv'}) {
                   8045: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8046: 		($env{'form.codethree'})) {
                   8047: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8048: 		    $env{'form.codethree'};
1.41      ng       8049: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8050: 		    &Apache::lonnet::checkin($token);
                   8051: 		if ($tsymb) {
1.137     albertel 8052: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8053: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8054: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8055: 					  ('grade_username' => $tuname,
                   8056: 					   'grade_domain' => $tudom,
                   8057: 					   'grade_courseid' => $tcrsid,
                   8058: 					   'grade_symb' => $tsymb)));
1.41      ng       8059: 		    } else {
1.45      ng       8060: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8061: 		    }
1.41      ng       8062: 		} else {
1.45      ng       8063: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8064: 		}
1.14      www      8065: 	    } else {
1.41      ng       8066: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8067: 	    }
                   8068: 	}
                   8069:     } else {
1.285     albertel 8070: 	&init_perm();
1.104     albertel 8071: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8072: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8073: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8074: 	    &pickStudentPage($request);
1.103     albertel 8075: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8076: 	    &displayPage($request);
1.104     albertel 8077: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8078: 	    &updateGradeByPage($request);
1.104     albertel 8079: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8080: 	    &processGroup($request);
1.104     albertel 8081: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8082: 	    $request->print(&grading_menu($request));
                   8083: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8084: 	    $request->print(&submit_options($request));
1.104     albertel 8085: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8086: 	    $request->print(&viewgrades($request));
1.104     albertel 8087: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8088: 	    $request->print(&processHandGrade($request));
1.106     albertel 8089: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8090: 	    $request->print(&editgrades($request));
1.106     albertel 8091: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8092: 	    $request->print(&verifyreceipt($request));
1.400     www      8093:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8094:             $request->print(&process_clicker($request));
                   8095:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8096:             $request->print(&process_clicker_file($request));
1.414     www      8097:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8098:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8099: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8100: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8101: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8102: 	    $request->print(&csvupload($request));
1.106     albertel 8103: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8104: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8105: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8106: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8107: 		$request->print(&csvuploadoptions($request));
1.41      ng       8108: 	    } else {
1.257     albertel 8109: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8110: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8111: 		} else {
1.257     albertel 8112: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8113: 		}
                   8114: 		$request->print(&csvuploadmap($request));
                   8115: 	    }
1.246     albertel 8116: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8117: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8118: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8119: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8120:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8121:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8122: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8123: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8124: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8125: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8126:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8127:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8128: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8129:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8130:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8131:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8132: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8133:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8134:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8135: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8136:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8137: 	} elsif ($command) {
1.157     albertel 8138: 	    $request->print("Access Denied ($command)");
1.26      albertel 8139: 	}
1.2       albertel 8140:     }
1.353     albertel 8141:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8142:     &reset_caches();
1.44      ng       8143:     return '';
                   8144: }
                   8145: 
1.1       albertel 8146: 1;
                   8147: 
1.13      albertel 8148: __END__;

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