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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.480   ! foxr        4: # $Id: grades.pm,v 1.479 2007/11/05 10:19:03 foxr Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.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.479     foxr       45: use Data::Dumper;
1.359     www        46: use LONCAPA;
                     47: 
1.315     bowersj2   48: use POSIX qw(floor);
1.87      www        49: 
1.435     foxr       50: 
                     51: my %perm=();
1.447     foxr       52: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       53:                                    # index is "symb.part_id"
                     54: 
1.447     foxr       55: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     56: 
                     57: # Save and restore the bubble lines array to the form env.
                     58: 
                     59: 
                     60: sub save_bubble_lines {
                     61:     foreach my $line (keys(%bubble_lines_per_response)) {
                     62: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     63: 	$env{"form.scantron.first_bubble_line.$line"} =
                     64: 	    $first_bubble_line{$line};
                     65:     }
                     66: }
                     67: 
                     68: 
                     69: sub restore_bubble_lines {
                     70:     my $line = 0;
                     71:     %bubble_lines_per_response = ();
                     72:     while ($env{"form.scantron.bubblelines.$line"}) {
                     73: 	my $value = $env{"form.scantron.bubblelines.$line"};
                     74: 	$bubble_lines_per_response{$line} = $value;
                     75: 	$first_bubble_line{$line}  =
                     76: 	    $env{"form.scantron.first_bubble_line.$line"};
                     77: 	$line++;
                     78:     }
                     79: 
                     80: }
                     81: 
                     82: #  Given the parsed scanline, get the response for 
                     83: #  'answer' number n:
                     84: 
                     85: sub get_response_bubbles {
                     86:     my ($parsed_line, $response)  = @_;
                     87: 
1.460     foxr       88: 
                     89:     my $bubble_line = $first_bubble_line{$response-1} +1;
                     90:     my $bubble_lines= $bubble_lines_per_response{$response-1};
                     91:     
1.447     foxr       92:     my $selected = "";
                     93: 
                     94:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
1.461     foxr       95: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"}.":";
1.447     foxr       96: 	$bubble_line++;
                     97:     }
                     98:     return $selected;
                     99: }
                    100: 
1.1       albertel  101: 
1.68      ng        102: # ----- These first few routines are general use routines.----
1.447     foxr      103: 
                    104: # Return the number of occurences of a pattern in a string.
                    105: 
                    106: sub occurence_count {
                    107:     my ($string, $pattern) = @_;
                    108: 
                    109:     my @matches = ($string =~ /$pattern/g);
                    110: 
                    111:     return scalar(@matches);
                    112: }
                    113: 
                    114: 
                    115: # Take a string known to have digits and convert all the
                    116: # digits into letters in the range J,A..I.
                    117: 
                    118: sub digits_to_letters {
                    119:     my ($input) = @_;
                    120: 
                    121:     my @alphabet = ('J', 'A'..'I');
                    122: 
                    123:     my @input    = split(//, $input);
                    124:     my $output ='';
                    125:     for (my $i = 0; $i < scalar(@input); $i++) {
                    126: 	if ($input[$i] =~ /\d/) {
                    127: 	    $output .= $alphabet[$input[$i]];
                    128: 	} else {
                    129: 	    $output .= $input[$i];
                    130: 	}
                    131:     }
                    132:     return $output;
                    133: }
                    134: 
1.44      ng        135: #
1.146     albertel  136: # --- Retrieve the parts from the metadata file.---
1.44      ng        137: sub getpartlist {
1.324     albertel  138:     my ($symb) = @_;
1.439     albertel  139: 
                    140:     my $navmap   = Apache::lonnavmaps::navmap->new();
                    141:     my $res      = $navmap->getBySymb($symb);
                    142:     my $partlist = $res->parts();
                    143:     my $url      = $res->src();
                    144:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                    145: 
1.146     albertel  146:     my @stores;
1.439     albertel  147:     foreach my $part (@{ $partlist }) {
1.146     albertel  148: 	foreach my $key (@metakeys) {
                    149: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                    150: 	}
                    151:     }
                    152:     return @stores;
1.2       albertel  153: }
                    154: 
1.44      ng        155: # --- Get the symbolic name of a problem and the url
1.324     albertel  156: sub get_symb {
1.173     albertel  157:     my ($request,$silent) = @_;
1.257     albertel  158:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                    159:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel  160:     if ($symb eq '') { 
                    161: 	if (!$silent) {
                    162: 	    $request->print("Unable to handle ambiguous references:$url:.");
                    163: 	    return ();
                    164: 	}
                    165:     }
1.418     albertel  166:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel  167:     return ($symb);
1.32      ng        168: }
                    169: 
1.129     ng        170: #--- Format fullname, username:domain if different for display
                    171: #--- Use anywhere where the student names are listed
                    172: sub nameUserString {
                    173:     my ($type,$fullname,$uname,$udom) = @_;
                    174:     if ($type eq 'header') {
1.398     albertel  175: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng        176:     } else {
1.398     albertel  177: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                    178: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng        179:     }
                    180: }
                    181: 
1.44      ng        182: #--- Get the partlist and the response type for a given problem. ---
                    183: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        184: sub response_type {
1.324     albertel  185:     my ($symb) = shift;
1.377     albertel  186: 
                    187:     my $navmap = Apache::lonnavmaps::navmap->new();
                    188:     my $res = $navmap->getBySymb($symb);
                    189:     my $partlist = $res->parts();
1.392     albertel  190:     my %vPart = 
                    191: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  192:     my (%response_types,%handgrade);
                    193:     foreach my $part (@{ $partlist }) {
1.392     albertel  194: 	next if (%vPart && !exists($vPart{$part}));
                    195: 
1.377     albertel  196: 	my @types = $res->responseType($part);
                    197: 	my @ids = $res->responseIds($part);
                    198: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    199: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    200: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    201: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    202: 				     '.handgrade',$symb);
1.41      ng        203: 	}
                    204:     }
1.377     albertel  205:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        206: }
                    207: 
1.375     albertel  208: sub flatten_responseType {
                    209:     my ($responseType) = @_;
                    210:     my @part_response_id =
                    211: 	map { 
                    212: 	    my $part = $_;
                    213: 	    map {
                    214: 		[$part,$_]
                    215: 		} sort(keys(%{ $responseType->{$part} }));
                    216: 	} sort(keys(%$responseType));
                    217:     return @part_response_id;
                    218: }
                    219: 
1.207     albertel  220: sub get_display_part {
1.324     albertel  221:     my ($partID,$symb)=@_;
1.207     albertel  222:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    223:     if (defined($display) and $display ne '') {
1.398     albertel  224: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  225:     } else {
                    226: 	$display=$partID;
                    227:     }
                    228:     return $display;
                    229: }
1.269     raeburn   230: 
1.118     ng        231: #--- Show resource title
                    232: #--- and parts and response type
                    233: sub showResourceInfo {
1.324     albertel  234:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  235:     my $col=3;
                    236:     if ($checkboxes) { $col=4; }
1.398     albertel  237:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    238:     $result .='<table border="0">';
1.324     albertel  239:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        240:     my %resptype = ();
1.122     ng        241:     my $hdgrade='no';
1.154     albertel  242:     my %partsseen;
1.375     albertel  243:     foreach my $partID (sort keys(%$responseType)) {
                    244: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    245: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    246: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    247: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    248: 	    $result.='<tr>';
                    249: 	    if ($checkboxes) {
                    250: 		if (exists($partsseen{$partID})) {
                    251: 		    $result.="<td>&nbsp;</td>";
                    252: 		} else {
1.401     albertel  253: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  254: 		}
                    255: 		$partsseen{$partID}=1;
1.154     albertel  256: 	    }
1.375     albertel  257: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  258: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    259: 		$resID.'</span></td>'.
1.375     albertel  260: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    261: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  262: 	}
1.118     ng        263:     }
                    264:     $result.='</table>'."\n";
1.147     albertel  265:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        266: }
                    267: 
1.434     albertel  268: sub reset_caches {
                    269:     &reset_analyze_cache();
                    270:     &reset_perm();
                    271: }
                    272: 
                    273: {
                    274:     my %analyze_cache;
1.148     albertel  275: 
1.434     albertel  276:     sub reset_analyze_cache {
                    277: 	undef(%analyze_cache);
                    278:     }
                    279: 
                    280:     sub get_analyze {
                    281: 	my ($symb,$uname,$udom)=@_;
                    282: 	my $key = "$symb\0$uname\0$udom";
                    283: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    284: 
                    285: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    286: 	$url=&Apache::lonnet::clutter($url);
                    287: 	my $subresult=&Apache::lonnet::ssi($url,
                    288: 					   ('grade_target' => 'analyze'),
                    289: 					   ('grade_domain' => $udom),
                    290: 					   ('grade_symb' => $symb),
                    291: 					   ('grade_courseid' => 
                    292: 					    $env{'request.course.id'}),
                    293: 					   ('grade_username' => $uname));
                    294: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    295: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    296: 	return $analyze_cache{$key} = \%analyze;
                    297:     }
                    298: 
                    299:     sub get_order {
                    300: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    301: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    302: 	return $analyze->{"$partid.$respid.shown"};
                    303:     }
                    304: 
                    305:     sub get_radiobutton_correct_foil {
                    306: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    307: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    308: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    309: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    310: 		return $foil;
                    311: 	    }
                    312: 	}
                    313:     }
1.148     albertel  314: }
1.434     albertel  315: 
1.118     ng        316: #--- Clean response type for display
1.335     albertel  317: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    318: #        response types only.
1.118     ng        319: sub cleanRecord {
1.336     albertel  320:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    321: 	$uname,$udom) = @_;
1.398     albertel  322:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  323:     if ($response =~ /^(option|rank)$/) {
                    324: 	my %answer=&Apache::lonnet::str2hash($answer);
                    325: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    326: 	my ($toprow,$bottomrow);
                    327: 	foreach my $foil (@$order) {
                    328: 	    if ($grading{$foil} == 1) {
                    329: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    330: 	    } else {
                    331: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    332: 	    }
1.398     albertel  333: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  334: 	}
                    335: 	return '<blockquote><table border="1">'.
1.466     albertel  336: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    337: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  338: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    339:     } elsif ($response eq 'match') {
                    340: 	my %answer=&Apache::lonnet::str2hash($answer);
                    341: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    342: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    343: 	my ($toprow,$middlerow,$bottomrow);
                    344: 	foreach my $foil (@$order) {
                    345: 	    my $item=shift(@items);
                    346: 	    if ($grading{$foil} == 1) {
                    347: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  348: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  349: 	    } else {
                    350: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  351: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  352: 	    }
1.398     albertel  353: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        354: 	}
1.126     ng        355: 	return '<blockquote><table border="1">'.
1.466     albertel  356: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    357: 	    '<tr valign="top"><td>'.$grayFont.&mt('Item ID').'</span></td>'.
1.148     albertel  358: 	    $middlerow.'</tr>'.
1.466     albertel  359: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  360: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    361:     } elsif ($response eq 'radiobutton') {
                    362: 	my %answer=&Apache::lonnet::str2hash($answer);
                    363: 	my ($toprow,$bottomrow);
1.434     albertel  364: 	my $correct = 
                    365: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    366: 	foreach my $foil (@$order) {
1.148     albertel  367: 	    if (exists($answer{$foil})) {
1.434     albertel  368: 		if ($foil eq $correct) {
1.466     albertel  369: 		    $toprow.='<td><b>'.&mt('true').'</b></td>';
1.148     albertel  370: 		} else {
1.466     albertel  371: 		    $toprow.='<td><i>'.&mt('true').'</i></td>';
1.148     albertel  372: 		}
                    373: 	    } else {
1.466     albertel  374: 		$toprow.='<td>'.&mt('false').'</td>';
1.148     albertel  375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  377: 	}
                    378: 	return '<blockquote><table border="1">'.
1.466     albertel  379: 	    '<tr valign="top"><td>'.&mt('Answer').'</td>'.$toprow.'</tr>'.
                    380: 	    '<tr valign="top"><td>'.$grayFont.&mt('Option ID').'</span></td>'.
1.148     albertel  381: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    382:     } elsif ($response eq 'essay') {
1.257     albertel  383: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        384: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  385: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    386: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        387: 
1.257     albertel  388: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    389: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    390: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    391: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    392: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    393: 	    $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        394: 	}
1.166     albertel  395: 	$answer =~ s-\n-<br />-g;
                    396: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  397:     } elsif ( $response eq 'organic') {
                    398: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    399: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    400: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    401: 	return $result;
1.335     albertel  402:     } elsif ( $response eq 'Task') {
                    403: 	if ( $answer eq 'SUBMITTED') {
                    404: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  405: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  406: 	    return $result;
                    407: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    408: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    409: 			       keys(%{$record}));
                    410: 	    return join('<br />',($version,@matches));
                    411: 			       
                    412: 			       
                    413: 	} else {
                    414: 	    my $result =
                    415: 		'<p>'
                    416: 		.&mt('Overall result: [_1]',
                    417: 		     $record->{$version."resource.$respid.$partid.status"})
                    418: 		.'</p>';
                    419: 	    
                    420: 	    $result .= '<ul>';
                    421: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    422: 			     keys(%{$record}));
                    423: 	    foreach my $grade (sort(@grade)) {
                    424: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    425: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    426: 				     $dim, $record->{$grade}).
                    427: 			  '</li>';
                    428: 	    }
                    429: 	    $result.='</ul>';
                    430: 	    return $result;
                    431: 	}
1.440     albertel  432:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    433: 	$answer = 
                    434: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    435: 							      $answer);
1.122     ng        436:     }
1.118     ng        437:     return $answer;
                    438: }
                    439: 
                    440: #-- A couple of common js functions
                    441: sub commonJSfunctions {
                    442:     my $request = shift;
                    443:     $request->print(<<COMMONJSFUNCTIONS);
                    444: <script type="text/javascript" language="javascript">
                    445:     function radioSelection(radioButton) {
                    446: 	var selection=null;
                    447: 	if (radioButton.length > 1) {
                    448: 	    for (var i=0; i<radioButton.length; i++) {
                    449: 		if (radioButton[i].checked) {
                    450: 		    return radioButton[i].value;
                    451: 		}
                    452: 	    }
                    453: 	} else {
                    454: 	    if (radioButton.checked) return radioButton.value;
                    455: 	}
                    456: 	return selection;
                    457:     }
                    458: 
                    459:     function pullDownSelection(selectOne) {
                    460: 	var selection="";
                    461: 	if (selectOne.length > 1) {
                    462: 	    for (var i=0; i<selectOne.length; i++) {
                    463: 		if (selectOne[i].selected) {
                    464: 		    return selectOne[i].value;
                    465: 		}
                    466: 	    }
                    467: 	} else {
1.138     albertel  468:             // only one value it must be the selected one
                    469: 	    return selectOne.value;
1.118     ng        470: 	}
                    471:     }
                    472: </script>
                    473: COMMONJSFUNCTIONS
                    474: }
                    475: 
1.44      ng        476: #--- Dumps the class list with usernames,list of sections,
                    477: #--- section, ids and fullnames for each user.
                    478: sub getclasslist {
1.449     banghart  479:     my ($getsec,$filterlist,$getgroup) = @_;
1.291     albertel  480:     my @getsec;
1.450     banghart  481:     my @getgroup;
1.442     banghart  482:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  483:     if (!ref($getsec)) {
                    484: 	if ($getsec ne '' && $getsec ne 'all') {
                    485: 	    @getsec=($getsec);
                    486: 	}
                    487:     } else {
                    488: 	@getsec=@{$getsec};
                    489:     }
                    490:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
1.450     banghart  491:     if (!ref($getgroup)) {
                    492: 	if ($getgroup ne '' && $getgroup ne 'all') {
                    493: 	    @getgroup=($getgroup);
                    494: 	}
                    495:     } else {
                    496: 	@getgroup=@{$getgroup};
                    497:     }
                    498:     if (grep(/^all$/,@getgroup)) { undef(@getgroup); }
1.291     albertel  499: 
1.449     banghart  500:     my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
1.49      albertel  501:     # Bail out if we were unable to get the classlist
1.56      matthew   502:     return if (! defined($classlist));
1.449     banghart  503:     &Apache::loncoursedata::get_group_memberships($classlist,$keylist);
1.56      matthew   504:     #
                    505:     my %sections;
                    506:     my %fullnames;
1.205     matthew   507:     foreach my $student (keys(%$classlist)) {
                    508:         my $end      = 
                    509:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    510:         my $start    = 
                    511:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    512:         my $id       = 
                    513:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    514:         my $section  = 
                    515:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    516:         my $fullname = 
                    517:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    518:         my $status   = 
                    519:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.449     banghart  520:         my $group   = 
                    521:             $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.76      ng        522: 	# filter students according to status selected
1.442     banghart  523: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    524: 	    if (!($stu_status =~ $status)) {
1.450     banghart  525: 		delete($classlist->{$student});
1.76      ng        526: 		next;
                    527: 	    }
                    528: 	}
1.450     banghart  529: 	# filter students according to groups selected
1.453     banghart  530: 	my @stu_groups = split(/,/,$group);
1.450     banghart  531: 	if (@getgroup) {
                    532: 	    my $exclude = 1;
1.454     banghart  533: 	    foreach my $grp (@getgroup) {
                    534: 	        foreach my $stu_group (@stu_groups) {
1.453     banghart  535: 	            if ($stu_group eq $grp) {
                    536: 	                $exclude = 0;
                    537:     	            } 
1.450     banghart  538: 	        }
1.453     banghart  539:     	        if (($grp eq 'none') && !$group) {
                    540:         	        $exclude = 0;
                    541:         	}
1.450     banghart  542: 	    }
                    543: 	    if ($exclude) {
                    544: 	        delete($classlist->{$student});
                    545: 	    }
                    546: 	}
1.205     matthew   547: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  548: 	if (&canview($section)) {
1.291     albertel  549: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  550: 		$sections{$section}++;
1.450     banghart  551: 		if ($classlist->{$student}) {
                    552: 		    $fullnames{$student}=$fullname;
                    553: 		}
1.103     albertel  554: 	    } else {
1.205     matthew   555: 		delete($classlist->{$student});
1.103     albertel  556: 	    }
                    557: 	} else {
1.205     matthew   558: 	    delete($classlist->{$student});
1.103     albertel  559: 	}
1.44      ng        560:     }
                    561:     my %seen = ();
1.56      matthew   562:     my @sections = sort(keys(%sections));
                    563:     return ($classlist,\@sections,\%fullnames);
1.44      ng        564: }
                    565: 
1.103     albertel  566: sub canmodify {
                    567:     my ($sec)=@_;
                    568:     if ($perm{'mgr'}) {
                    569: 	if (!defined($perm{'mgr_section'})) {
                    570: 	    # can modify whole class
                    571: 	    return 1;
                    572: 	} else {
                    573: 	    if ($sec eq $perm{'mgr_section'}) {
                    574: 		#can modify the requested section
                    575: 		return 1;
                    576: 	    } else {
                    577: 		# can't modify the request section
                    578: 		return 0;
                    579: 	    }
                    580: 	}
                    581:     }
                    582:     #can't modify
                    583:     return 0;
                    584: }
                    585: 
                    586: sub canview {
                    587:     my ($sec)=@_;
                    588:     if ($perm{'vgr'}) {
                    589: 	if (!defined($perm{'vgr_section'})) {
                    590: 	    # can modify whole class
                    591: 	    return 1;
                    592: 	} else {
                    593: 	    if ($sec eq $perm{'vgr_section'}) {
                    594: 		#can modify the requested section
                    595: 		return 1;
                    596: 	    } else {
                    597: 		# can't modify the request section
                    598: 		return 0;
                    599: 	    }
                    600: 	}
                    601:     }
                    602:     #can't modify
                    603:     return 0;
                    604: }
                    605: 
1.44      ng        606: #--- Retrieve the grade status of a student for all the parts
                    607: sub student_gradeStatus {
1.324     albertel  608:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  609:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        610:     my %partstatus = ();
                    611:     foreach (@$partlist) {
1.128     ng        612: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        613: 	$status              = 'nothing' if ($status eq '');
                    614: 	$partstatus{$_}      = $status;
                    615: 	my $subkey           = "resource.$_.submitted_by";
                    616: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    617:     }
                    618:     return %partstatus;
                    619: }
                    620: 
1.45      ng        621: # hidden form and javascript that calls the form
                    622: # Use by verifyscript and viewgrades
                    623: # Shows a student's view of problem and submission
                    624: sub jscriptNform {
1.324     albertel  625:     my ($symb) = @_;
1.442     banghart  626:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        627:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    628: 	'    function viewOneStudent(user,domain) {'."\n".
                    629: 	'	document.onestudent.student.value = user;'."\n".
                    630: 	'	document.onestudent.userdom.value = domain;'."\n".
                    631: 	'	document.onestudent.submit();'."\n".
                    632: 	'    }'."\n".
                    633: 	'</script>'."\n";
                    634:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  635: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  636: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    637: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  638: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        639: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    640: 	'<input type="hidden" name="student" value="" />'."\n".
                    641: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    642: 	'</form>'."\n";
                    643:     return $jscript;
                    644: }
1.39      ng        645: 
1.447     foxr      646: 
                    647: 
1.315     bowersj2  648: # Given the score (as a number [0-1] and the weight) what is the final
                    649: # point value? This function will round to the nearest tenth, third,
                    650: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  651: sub compute_points {
1.315     bowersj2  652:     my ($score, $weight) = @_;
                    653:     
                    654:     my $tolerance = .00001;
                    655:     my $points = $score * $weight;
                    656: 
                    657:     # Check for nearness to 1/x.
                    658:     my $check_for_nearness = sub {
                    659:         my ($factor) = @_;
                    660:         my $num = ($points * $factor) + $tolerance;
                    661:         my $floored_num = floor($num);
1.316     albertel  662:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  663:             return $floored_num / $factor;
                    664:         }
                    665:         return $points;
                    666:     };
                    667: 
                    668:     $points = $check_for_nearness->(10);
                    669:     $points = $check_for_nearness->(3);
                    670:     $points = $check_for_nearness->(4);
                    671:     
                    672:     return $points;
                    673: }
                    674: 
1.44      ng        675: #------------------ End of general use routines --------------------
1.87      www       676: 
                    677: #
                    678: # Find most similar essay
                    679: #
                    680: 
                    681: sub most_similar {
1.426     albertel  682:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       683: 
                    684: # ignore spaces and punctuation
                    685: 
                    686:     $uessay=~s/\W+/ /gs;
                    687: 
1.282     www       688: # ignore empty submissions (occuring when only files are sent)
                    689: 
                    690:     unless ($uessay=~/\w+/) { return ''; }
                    691: 
1.87      www       692: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       693:     my $limit=0.6;
1.87      www       694:     my $sname='';
                    695:     my $sdom='';
                    696:     my $scrsid='';
                    697:     my $sessay='';
                    698: # go through all essays ...
1.426     albertel  699:     foreach my $tkey (keys(%$old_essays)) {
                    700: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       701: # ... except the same student
1.426     albertel  702:         next if (($tname eq $uname) && ($tdom eq $udom));
                    703: 	my $tessay=$old_essays->{$tkey};
                    704: 	$tessay=~s/\W+/ /gs;
1.87      www       705: # String similarity gives up if not even limit
1.426     albertel  706: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       707: # Found one
1.426     albertel  708: 	if ($tsimilar>$limit) {
                    709: 	    $limit=$tsimilar;
                    710: 	    $sname=$tname;
                    711: 	    $sdom=$tdom;
                    712: 	    $scrsid=$tcrsid;
                    713: 	    $sessay=$old_essays->{$tkey};
                    714: 	}
1.87      www       715:     }
1.88      www       716:     if ($limit>0.6) {
1.87      www       717:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    718:     } else {
                    719:        return ('','','','',0);
                    720:     }
                    721: }
                    722: 
1.44      ng        723: #-------------------------------------------------------------------
                    724: 
                    725: #------------------------------------ Receipt Verification Routines
1.45      ng        726: #
1.44      ng        727: #--- Check whether a receipt number is valid.---
                    728: sub verifyreceipt {
                    729:     my $request  = shift;
                    730: 
1.257     albertel  731:     my $courseid = $env{'request.course.id'};
1.184     www       732:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  733: 	$env{'form.receipt'};
1.44      ng        734:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  735:     my ($symb)   = &get_symb($request);
1.44      ng        736: 
1.398     albertel  737:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    738: 	$receipt.'</h3></span>'."\n".
                    739: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        740: 
                    741:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   742:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  743:     
                    744:     my $receiptparts=0;
1.390     albertel  745:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    746: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  747:     my $parts=['0'];
1.324     albertel  748:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  749:     foreach (sort 
                    750: 	     {
                    751: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    752: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    753: 		 }
                    754: 		 return $a cmp $b;
                    755: 	     } (keys(%$fullname))) {
1.44      ng        756: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  757: 	foreach my $part (@$parts) {
                    758: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    759: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    760: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  761: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  762: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    763: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    764: 		if ($receiptparts) {
                    765: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    766: 		}
                    767: 		$contents.='</tr>'."\n";
                    768: 		
                    769: 		$matches++;
                    770: 	    }
1.44      ng        771: 	}
                    772:     }
                    773:     if ($matches == 0) {
                    774: 	$string = $title.'No match found for the above receipt.';
                    775:     } else {
1.324     albertel  776: 	$string = &jscriptNform($symb).$title.
1.44      ng        777: 	    'The above receipt matches the following student'.
                    778: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    779: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    780: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    781: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    782: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  783: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    784: 	if ($receiptparts) {
                    785: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    786: 	}
                    787: 	$string.='</tr>'."\n".$contents.
1.44      ng        788: 	    '</table></td></tr></table>'."\n";
                    789:     }
1.324     albertel  790:     return $string.&show_grading_menu_form($symb);
1.44      ng        791: }
                    792: 
                    793: #--- This is called by a number of programs.
                    794: #--- Called from the Grading Menu - View/Grade an individual student
                    795: #--- Also called directly when one clicks on the subm button 
                    796: #    on the problem page.
1.30      ng        797: sub listStudents {
1.41      ng        798:     my ($request) = shift;
1.49      albertel  799: 
1.324     albertel  800:     my ($symb) = &get_symb($request);
1.257     albertel  801:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    802:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    803:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.449     banghart  804:     my $getgroup  = $env{'form.group'} eq '' ? 'all' : $env{'form.group'};
1.257     albertel  805:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    806:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    807:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    808: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  809: 
1.398     albertel  810:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    811: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        812: 
1.324     albertel  813:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  814: 
1.45      ng        815:     $request->print(<<LISTJAVASCRIPT);
                    816: <script type="text/javascript" language="javascript">
1.110     ng        817:     function checkSelect(checkBox) {
                    818: 	var ctr=0;
                    819: 	var sense="";
                    820: 	if (checkBox.length > 1) {
                    821: 	    for (var i=0; i<checkBox.length; i++) {
                    822: 		if (checkBox[i].checked) {
                    823: 		    ctr++;
                    824: 		}
                    825: 	    }
                    826: 	    sense = "a student or group of students";
                    827: 	} else {
                    828: 	    if (checkBox.checked) {
                    829: 		ctr = 1;
                    830: 	    }
                    831: 	    sense = "the student";
                    832: 	}
                    833: 	if (ctr == 0) {
1.126     ng        834: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        835: 	    return false;
                    836: 	}
                    837: 	document.gradesub.submit();
                    838:     }
                    839: 
                    840:     function reLoadList(formname) {
1.112     ng        841: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        842: 	formname.command.value = 'submission';
                    843: 	formname.submit();
                    844:     }
1.45      ng        845: </script>
                    846: LISTJAVASCRIPT
                    847: 
1.118     ng        848:     &commonJSfunctions($request);
1.41      ng        849:     $request->print($result);
1.39      ng        850: 
1.401     albertel  851:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    852:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  853:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    854: 	"\n".$table.
1.401     albertel  855: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  856: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    857: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    858: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    859: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  860: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  861: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  862:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  863: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  864:     }
1.442     banghart  865:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    866:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  867:     $env{'form.Status'} = $saveStatus;
1.267     albertel  868:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
1.474     albertel  869: 	'<label><input type="radio" name="lastSub" value="last" /> last submission &amp; parts info </label>'."\n".
1.267     albertel  870: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  871: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    872:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    873:         '<option value="1">Whole Points</option>'.
                    874:         '<option value=".5">Half Points</option>'.
1.349     albertel  875:         '<option value=".25">Quarter Points</option>'.
                    876:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  877:         '</select>'.
1.432     banghart  878:         &build_section_inputs().
1.45      ng        879: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  880: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    881: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    882: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    883: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  884: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        885: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    886: 
1.257     albertel  887:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  888: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        889:     } else {
                    890: 	$gradeTable.='<b>Student Status:</b> '.
                    891: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    892:     }
1.112     ng        893: 
1.126     ng        894:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    895: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        896: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  897: 
                    898: # checkall buttons
                    899:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        900:     $gradeTable.='<input type="button" '."\n".
1.45      ng        901: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  902: 	'value="Next->" /> <br />'."\n";
                    903:     $gradeTable.=&check_buttons();
1.401     albertel  904:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.450     banghart  905:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1',$getgroup);
1.474     albertel  906:     $gradeTable.= &Apache::loncommon::start_data_table().
                    907: 	&Apache::loncommon::start_data_table_header_row();
1.110     ng        908:     my $loop = 0;
                    909:     while ($loop < 2) {
1.474     albertel  910: 	$gradeTable.='<th>No.</th><th>Select</th>'.
                    911: 	    '<th>'.&nameUserString('header').'&nbsp;'.'Section/Group</th>';
1.301     albertel  912: 	if ($env{'form.showgrading'} eq 'yes' 
                    913: 	    && $submitonly ne 'queued'
                    914: 	    && $submitonly ne 'all') {
1.110     ng        915: 	    foreach (sort(@$partlist)) {
1.324     albertel  916: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.474     albertel  917: 		$gradeTable.='<th>Part: '.$display_part.
                    918: 		    ' Status</h>';
1.110     ng        919: 	    }
1.301     albertel  920: 	} elsif ($submitonly eq 'queued') {
1.474     albertel  921: 	    $gradeTable.='<th>'.&mt('Queue Status').'&nbsp;</th>';
1.110     ng        922: 	}
                    923: 	$loop++;
1.126     ng        924: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        925:     }
1.474     albertel  926:     $gradeTable.=&Apache::loncommon::end_data_table_header_row()."\n";
1.41      ng        927: 
1.45      ng        928:     my $ctr = 0;
1.294     albertel  929:     foreach my $student (sort 
                    930: 			 {
                    931: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    932: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    933: 			     }
                    934: 			     return $a cmp $b;
                    935: 			 }
                    936: 			 (keys(%$fullname))) {
1.41      ng        937: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  938: 
1.110     ng        939: 	my %status = ();
1.301     albertel  940: 
                    941: 	if ($submitonly eq 'queued') {
                    942: 	    my %queue_status = 
                    943: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    944: 							$udom,$uname);
                    945: 	    next if (!defined($queue_status{'gradingqueue'}));
                    946: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    947: 	}
                    948: 
                    949: 	if ($env{'form.showgrading'} eq 'yes' 
                    950: 	    && $submitonly ne 'queued'
                    951: 	    && $submitonly ne 'all') {
1.324     albertel  952: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  953: 	    my $submitted = 0;
1.164     albertel  954: 	    my $graded = 0;
1.248     albertel  955: 	    my $incorrect = 0;
1.110     ng        956: 	    foreach (keys(%status)) {
1.145     albertel  957: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  958: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    959: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    960: 		
1.110     ng        961: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    962: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  963: 		    $submitted = 0;
1.150     albertel  964: 		    my ($part)=split(/\./,$partid);
1.110     ng        965: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  966: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        967: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    968: 		}
1.41      ng        969: 	    }
1.248     albertel  970: 	    
1.156     albertel  971: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    972: 				     $submitonly eq 'incorrect' ||
                    973: 				     $submitonly eq 'graded'));
1.248     albertel  974: 	    next if (!$graded && ($submitonly eq 'graded'));
                    975: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        976: 	}
1.34      ng        977: 
1.45      ng        978: 	$ctr++;
1.249     albertel  979: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
1.452     banghart  980:         my $group = $classlist->{$student}->[&Apache::loncoursedata::CL_GROUP()];
1.104     albertel  981: 	if ( $perm{'vgr'} eq 'F' ) {
1.474     albertel  982: 	    if ($ctr%2 ==1) {
                    983: 		$gradeTable.= &Apache::loncommon::start_data_table_row();
                    984: 	    }
1.126     ng        985: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  986:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    987:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    988: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    989: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.474     albertel  990: 	       '&nbsp;'.$section.($group ne '' ?'/'.$group:'').'</td>'."\n";
1.110     ng        991: 
1.257     albertel  992: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        993: 		foreach (sort keys(%status)) {
                    994: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  995: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        996: 		}
1.41      ng        997: 	    }
1.126     ng        998: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.474     albertel  999: 	    if ($ctr%2 ==0) {
                   1000: 		$gradeTable.=&Apache::loncommon::end_data_table_row()."\n";
                   1001: 	    }
1.41      ng       1002: 	}
                   1003:     }
1.110     ng       1004:     if ($ctr%2 ==1) {
1.126     ng       1005: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1006: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1007: 		&& $submitonly ne 'queued'
                   1008: 		&& $submitonly ne 'all') {
1.110     ng       1009: 		foreach (@$partlist) {
                   1010: 		    $gradeTable.='<td>&nbsp;</td>';
                   1011: 		}
1.301     albertel 1012: 	    } elsif ($submitonly eq 'queued') {
                   1013: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1014: 	    }
1.474     albertel 1015: 	$gradeTable.=&Apache::loncommon::end_data_table_row();
1.110     ng       1016:     }
                   1017: 
1.474     albertel 1018:     $gradeTable.=&Apache::loncommon::end_data_table()."\n".
1.45      ng       1019: 	'<input type="button" '.
                   1020: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1021: 	'value="Next->" /></form>'."\n";
1.45      ng       1022:     if ($ctr == 0) {
1.96      albertel 1023: 	my $num_students=(scalar(keys(%$fullname)));
                   1024: 	if ($num_students eq 0) {
1.398     albertel 1025: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1026: 	} else {
1.171     albertel 1027: 	    my $submissions='submissions';
                   1028: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1029: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1030: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1031: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1032: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1033: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1034: 	}
1.46      ng       1035:     } elsif ($ctr == 1) {
1.474     albertel 1036: 	$gradeTable =~ s/type="checkbox"/type="checkbox" checked="checked"/;
1.45      ng       1037:     }
1.324     albertel 1038:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1039:     $request->print($gradeTable);
1.44      ng       1040:     return '';
1.10      ng       1041: }
                   1042: 
1.44      ng       1043: #---- Called from the listStudents routine
1.249     albertel 1044: 
                   1045: sub check_script {
                   1046:     my ($form, $type)=@_;
                   1047:     my $chkallscript='<script type="text/javascript">
                   1048:     function checkall() {
                   1049:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1050:             ele = document.forms.'.$form.'.elements[i];
                   1051:             if (ele.name == "'.$type.'") {
                   1052:             document.forms.'.$form.'.elements[i].checked=true;
                   1053:                                        }
                   1054:         }
                   1055:     }
                   1056: 
                   1057:     function checksec() {
                   1058:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1059:             ele = document.forms.'.$form.'.elements[i];
                   1060:            string = document.forms.'.$form.'.chksec.value;
                   1061:            if
                   1062:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1063:               document.forms.'.$form.'.elements[i].checked=true;
                   1064:             }
                   1065:         }
                   1066:     }
                   1067: 
                   1068: 
                   1069:     function uncheckall() {
                   1070:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1071:             ele = document.forms.'.$form.'.elements[i];
                   1072:             if (ele.name == "'.$type.'") {
                   1073:             document.forms.'.$form.'.elements[i].checked=false;
                   1074:                                        }
                   1075:         }
                   1076:     }
                   1077: 
                   1078: </script>'."\n";
                   1079:     return $chkallscript;
                   1080: }
                   1081: 
                   1082: sub check_buttons {
                   1083:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1084:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1085:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1086:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1087:     return $buttons;
                   1088: }
                   1089: 
1.44      ng       1090: #     Displays the submissions for one student or a group of students
1.34      ng       1091: sub processGroup {
1.41      ng       1092:     my ($request)  = shift;
                   1093:     my $ctr        = 0;
1.155     albertel 1094:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1095:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1096: 
1.396     banghart 1097:     foreach my $student (@stuchecked) {
                   1098: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1099: 	$env{'form.student'}        = $uname;
                   1100: 	$env{'form.userdom'}        = $udom;
                   1101: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1102: 	&submission($request,$ctr,$total);
                   1103: 	$ctr++;
                   1104:     }
                   1105:     return '';
1.35      ng       1106: }
1.34      ng       1107: 
1.44      ng       1108: #------------------------------------------------------------------------------------
                   1109: #
                   1110: #-------------------------- Next few routines handles grading by student, essentially
                   1111: #                           handles essay response type problem/part
                   1112: #
                   1113: #--- Javascript to handle the submission page functionality ---
                   1114: sub sub_page_js {
                   1115:     my $request = shift;
                   1116:     $request->print(<<SUBJAVASCRIPT);
                   1117: <script type="text/javascript" language="javascript">
1.71      ng       1118:     function updateRadio(formname,id,weight) {
1.125     ng       1119: 	var gradeBox = formname["GD_BOX"+id];
                   1120: 	var radioButton = formname["RADVAL"+id];
                   1121: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1122: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1123: 	gradeBox.value = pts;
                   1124: 	var resetbox = false;
                   1125: 	if (isNaN(pts) || pts < 0) {
                   1126: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1127: 	    for (var i=0; i<radioButton.length; i++) {
                   1128: 		if (radioButton[i].checked) {
                   1129: 		    gradeBox.value = i;
                   1130: 		    resetbox = true;
                   1131: 		}
                   1132: 	    }
                   1133: 	    if (!resetbox) {
                   1134: 		formtextbox.value = "";
                   1135: 	    }
                   1136: 	    return;
1.44      ng       1137: 	}
1.71      ng       1138: 
                   1139: 	if (pts > weight) {
                   1140: 	    var resp = confirm("You entered a value ("+pts+
                   1141: 			       ") greater than the weight for the part. Accept?");
                   1142: 	    if (resp == false) {
1.125     ng       1143: 		gradeBox.value = oldpts;
1.71      ng       1144: 		return;
                   1145: 	    }
1.44      ng       1146: 	}
1.13      albertel 1147: 
1.71      ng       1148: 	for (var i=0; i<radioButton.length; i++) {
                   1149: 	    radioButton[i].checked=false;
                   1150: 	    if (pts == i && pts != "") {
                   1151: 		radioButton[i].checked=true;
                   1152: 	    }
                   1153: 	}
                   1154: 	updateSelect(formname,id);
1.125     ng       1155: 	formname["stores"+id].value = "0";
1.41      ng       1156:     }
1.5       albertel 1157: 
1.72      ng       1158:     function writeBox(formname,id,pts) {
1.125     ng       1159: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1160: 	if (checkSolved(formname,id) == 'update') {
                   1161: 	    gradeBox.value = pts;
                   1162: 	} else {
1.125     ng       1163: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1164: 	    gradeBox.value = oldpts;
1.125     ng       1165: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1166: 	    for (var i=0; i<radioButton.length; i++) {
                   1167: 		radioButton[i].checked=false;
1.72      ng       1168: 		if (i == oldpts) {
1.71      ng       1169: 		    radioButton[i].checked=true;
                   1170: 		}
                   1171: 	    }
1.41      ng       1172: 	}
1.125     ng       1173: 	formname["stores"+id].value = "0";
1.71      ng       1174: 	updateSelect(formname,id);
                   1175: 	return;
1.41      ng       1176:     }
1.44      ng       1177: 
1.71      ng       1178:     function clearRadBox(formname,id) {
                   1179: 	if (checkSolved(formname,id) == 'noupdate') {
                   1180: 	    updateSelect(formname,id);
                   1181: 	    return;
                   1182: 	}
1.125     ng       1183: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1184: 	for (var i=0; i<gradeSelect.length; i++) {
                   1185: 	    if (gradeSelect[i].selected) {
                   1186: 		var selectx=i;
                   1187: 	    }
                   1188: 	}
1.125     ng       1189: 	var stores = formname["stores"+id];
1.71      ng       1190: 	if (selectx == stores.value) { return };
1.125     ng       1191: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1192: 	gradeBox.value = "";
1.125     ng       1193: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1194: 	for (var i=0; i<radioButton.length; i++) {
                   1195: 	    radioButton[i].checked=false;
                   1196: 	}
                   1197: 	stores.value = selectx;
                   1198:     }
1.5       albertel 1199: 
1.71      ng       1200:     function checkSolved(formname,id) {
1.125     ng       1201: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1202: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1203: 	    if (!reply) {return "noupdate";}
1.120     ng       1204: 	    formname.overRideScore.value = 'yes';
1.41      ng       1205: 	}
1.71      ng       1206: 	return "update";
1.13      albertel 1207:     }
1.71      ng       1208: 
                   1209:     function updateSelect(formname,id) {
1.125     ng       1210: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1211: 	return;
1.41      ng       1212:     }
1.33      ng       1213: 
1.121     ng       1214: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1215:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1216: 	formname.gradeOpt.value = val;
1.71      ng       1217: 	if (val == "Save & Next") {
                   1218: 	    for (i=0;i<=total;i++) {
                   1219: 		for (j=0;j<parttot;j++) {
1.125     ng       1220: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1221: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1222: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1223: 			if (points == "") {
1.125     ng       1224: 			    var name = formname["name"+i].value;
1.129     ng       1225: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1226: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1227: 					       ", part "+partid+". Continue?");
1.71      ng       1228: 			    if (resp == false) {
1.125     ng       1229: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1230: 				return false;
                   1231: 			    }
                   1232: 			}
                   1233: 		    }
                   1234: 		    
                   1235: 		}
                   1236: 	    }
                   1237: 	    
                   1238: 	}
1.121     ng       1239: 	if (val == "Grade Student") {
                   1240: 	    formname.showgrading.value = "yes";
                   1241: 	    if (formname.Status.value == "") {
                   1242: 		formname.Status.value = "Active";
                   1243: 	    }
                   1244: 	    formname.studentNo.value = total;
                   1245: 	}
1.120     ng       1246: 	formname.submit();
                   1247:     }
                   1248: 
1.71      ng       1249: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1250:     function checkSubmitPage(formname,total) {
                   1251: 	noscore = new Array(100);
                   1252: 	var ptr = 0;
                   1253: 	for (i=1;i<total;i++) {
1.125     ng       1254: 	    var partid = formname["q_"+i].value;
1.127     ng       1255: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1256: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1257: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1258: 		if (points == "" && status != "correct_by_student") {
                   1259: 		    noscore[ptr] = i;
                   1260: 		    ptr++;
                   1261: 		}
                   1262: 	    }
                   1263: 	}
                   1264: 	if (ptr != 0) {
                   1265: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1266: 	    var prolist = "";
                   1267: 	    if (ptr == 1) {
                   1268: 		prolist = noscore[0];
                   1269: 	    } else {
                   1270: 		var i = 0;
                   1271: 		while (i < ptr-1) {
                   1272: 		    prolist += noscore[i]+", ";
                   1273: 		    i++;
                   1274: 		}
                   1275: 		prolist += "and "+noscore[i];
                   1276: 	    }
                   1277: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1278: 	    if (resp == false) {
                   1279: 		return false;
                   1280: 	    }
                   1281: 	}
1.45      ng       1282: 
1.71      ng       1283: 	formname.submit();
                   1284:     }
                   1285: </script>
                   1286: SUBJAVASCRIPT
                   1287: }
1.45      ng       1288: 
1.71      ng       1289: #--- javascript for essay type problem --
                   1290: sub sub_page_kw_js {
                   1291:     my $request = shift;
1.80      ng       1292:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1293:     &commonJSfunctions($request);
1.350     albertel 1294: 
1.351     albertel 1295:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1296:     <script text="text/javascript">
                   1297:     function checkInput() {
                   1298:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1299:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1300:       var usrctr = document.msgcenter.usrctr.value;
                   1301:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1302:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1303: 
                   1304:       var msgchk = "";
                   1305:       if (document.msgcenter.subchk.checked) {
                   1306:          msgchk = "msgsub,";
                   1307:       }
                   1308:       var includemsg = 0;
                   1309:       for (var i=1; i<=nmsg; i++) {
                   1310:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1311:           var frmmsg = document.msgcenter["msg"+i];
                   1312:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1313:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1314:           showflg.value = "1";
                   1315:           var chkbox = document.msgcenter["msgn"+i];
                   1316:           if (chkbox.checked) {
                   1317:              msgchk += "savemsg"+i+",";
                   1318:              includemsg = 1;
                   1319:           }
                   1320:       }
                   1321:       if (document.msgcenter.newmsgchk.checked) {
                   1322:          msgchk += "newmsg"+usrctr;
                   1323:          includemsg = 1;
                   1324:       }
                   1325:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1326:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1327:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1328:       includemsg.value = msgchk;
                   1329: 
                   1330:       self.close()
                   1331: 
                   1332:     }
                   1333:     </script>
                   1334: INNERJS
                   1335: 
1.351     albertel 1336:     my $inner_js_highlight_central=<<INNERJS;
                   1337:  <script type="text/javascript">
                   1338:     function updateChoice(flag) {
                   1339:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1340:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1341:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1342:       opener.document.SCORE.refresh.value = "on";
                   1343:       if (opener.document.SCORE.keywords.value!=""){
                   1344:          opener.document.SCORE.submit();
                   1345:       }
                   1346:       self.close()
                   1347:     }
                   1348: </script>
                   1349: INNERJS
                   1350: 
                   1351:     my $start_page_msg_central = 
                   1352:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1353: 				       {'js_ready'  => 1,
                   1354: 					'only_body' => 1,
                   1355: 					'bgcolor'   =>'#FFFFFF',});
                   1356:     my $end_page_msg_central = 
                   1357: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1358: 
                   1359: 
                   1360:     my $start_page_highlight_central = 
                   1361:         &Apache::loncommon::start_page('Highlight Central',
                   1362: 				       $inner_js_highlight_central,
1.350     albertel 1363: 				       {'js_ready'  => 1,
                   1364: 					'only_body' => 1,
                   1365: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1366:     my $end_page_highlight_central = 
1.350     albertel 1367: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1368: 
1.219     www      1369:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1370:     $docopen=~s/^document\.//;
1.71      ng       1371:     $request->print(<<SUBJAVASCRIPT);
                   1372: <script type="text/javascript" language="javascript">
1.45      ng       1373: 
1.44      ng       1374: //===================== Show list of keywords ====================
1.122     ng       1375:   function keywords(formname) {
                   1376:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1377:     if (nret==null) return;
1.122     ng       1378:     formname.keywords.value = nret;
1.44      ng       1379: 
1.122     ng       1380:     if (formname.keywords.value != "") {
1.128     ng       1381: 	formname.refresh.value = "on";
1.122     ng       1382: 	formname.submit();
1.44      ng       1383:     }
                   1384:     return;
                   1385:   }
                   1386: 
                   1387: //===================== Script to view submitted by ==================
                   1388:   function viewSubmitter(submitter) {
                   1389:     document.SCORE.refresh.value = "on";
                   1390:     document.SCORE.NCT.value = "1";
                   1391:     document.SCORE.unamedom0.value = submitter;
                   1392:     document.SCORE.submit();
                   1393:     return;
                   1394:   }
                   1395: 
                   1396: //===================== Script to add keyword(s) ==================
                   1397:   function getSel() {
                   1398:     if (document.getSelection) txt = document.getSelection();
                   1399:     else if (document.selection) txt = document.selection.createRange().text;
                   1400:     else return;
                   1401:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1402:     if (cleantxt=="") {
1.46      ng       1403: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1404: 	return;
                   1405:     }
                   1406:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1407:     if (nret==null) return;
1.127     ng       1408:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1409:     if (document.SCORE.keywords.value != "") {
1.127     ng       1410: 	document.SCORE.refresh.value = "on";
1.44      ng       1411: 	document.SCORE.submit();
                   1412:     }
                   1413:     return;
                   1414:   }
                   1415: 
                   1416: //====================== Script for composing message ==============
1.80      ng       1417:    // preload images
                   1418:    img1 = new Image();
                   1419:    img1.src = "$iconpath/mailbkgrd.gif";
                   1420:    img2 = new Image();
                   1421:    img2.src = "$iconpath/mailto.gif";
                   1422: 
1.44      ng       1423:   function msgCenter(msgform,usrctr,fullname) {
                   1424:     var Nmsg  = msgform.savemsgN.value;
                   1425:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1426:     var subject = msgform.msgsub.value;
1.127     ng       1427:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1428:     re = /msgsub/;
                   1429:     var shwsel = "";
                   1430:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1431:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1432:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1433:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1434: 	var testmsg = "savemsg"+i+",";
                   1435: 	re = new RegExp(testmsg,"g");
1.44      ng       1436: 	shwsel = "";
                   1437: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1438: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1439: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1440: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1441: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1442:     }
1.125     ng       1443:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1444:     shwsel = "";
                   1445:     re = /newmsg/;
                   1446:     if (re.test(msgchk)) { shwsel = "checked" }
                   1447:     newMsg(newmsg,shwsel);
                   1448:     msgTail(); 
                   1449:     return;
                   1450:   }
                   1451: 
1.123     ng       1452:   function checkEntities(strx) {
                   1453:     if (strx.length == 0) return strx;
                   1454:     var orgStr = ["&", "<", ">", '"']; 
                   1455:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1456:     var counter = 0;
                   1457:     while (counter < 4) {
                   1458: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1459: 	counter++;
                   1460:     }
                   1461:     return strx;
                   1462:   }
                   1463: 
                   1464:   function strReplace(strx, orgStr, newStr) {
                   1465:     return strx.split(orgStr).join(newStr);
                   1466:   }
                   1467: 
1.44      ng       1468:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1469:     var height = 70*Nmsg+250;
1.44      ng       1470:     var scrollbar = "no";
                   1471:     if (height > 600) {
                   1472: 	height = 600;
                   1473: 	scrollbar = "yes";
                   1474:     }
1.118     ng       1475:     var xpos = (screen.width-600)/2;
                   1476:     xpos = (xpos < 0) ? '0' : xpos;
                   1477:     var ypos = (screen.height-height)/2-30;
                   1478:     ypos = (ypos < 0) ? '0' : ypos;
                   1479: 
1.206     albertel 1480:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1481:     pWin.focus();
                   1482:     pDoc = pWin.document;
1.219     www      1483:     pDoc.$docopen;
1.351     albertel 1484:     pDoc.write('$start_page_msg_central');
1.76      ng       1485: 
                   1486:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1487:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.465     albertel 1488:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"<\\/span><\\/h3><br /><br />");
1.76      ng       1489: 
                   1490:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1491:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1492:     pDoc.write("<td><b>Type<\\/b><\\/td><td><b>Include<\\/b><\\/td><td><b>Message<\\/td><\\/tr>");
1.44      ng       1493: }
                   1494:     function displaySubject(msg,shwsel) {
1.76      ng       1495:     pDoc = pWin.document;
                   1496:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1497:     pDoc.write("<td>Subject<\\/td>");
                   1498:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1499:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"><\\/td><\\/tr>");
1.44      ng       1500: }
                   1501: 
1.72      ng       1502:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1503:     pDoc = pWin.document;
                   1504:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1505:     pDoc.write("<td align=\\"center\\">"+ctr+"<\\/td>");
                   1506:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1507:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1508: }
                   1509: 
                   1510:   function newMsg(newmsg,shwsel) {
1.76      ng       1511:     pDoc = pWin.document;
                   1512:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
1.465     albertel 1513:     pDoc.write("<td align=\\"center\\">New<\\/td>");
                   1514:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"><\\/td>");
                   1515:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"<\\/textarea><\\/td><\\/tr>");
1.44      ng       1516: }
                   1517: 
                   1518:   function msgTail() {
1.76      ng       1519:     pDoc = pWin.document;
1.465     albertel 1520:     pDoc.write("<\\/table>");
                   1521:     pDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1522:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1523:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1524:     pDoc.write("<\\/form>");
1.351     albertel 1525:     pDoc.write('$end_page_msg_central');
1.128     ng       1526:     pDoc.close();
1.44      ng       1527: }
                   1528: 
                   1529: //====================== Script for keyword highlight options ==============
                   1530:   function kwhighlight() {
                   1531:     var kwclr    = document.SCORE.kwclr.value;
                   1532:     var kwsize   = document.SCORE.kwsize.value;
                   1533:     var kwstyle  = document.SCORE.kwstyle.value;
                   1534:     var redsel = "";
                   1535:     var grnsel = "";
                   1536:     var blusel = "";
                   1537:     if (kwclr=="red")   {var redsel="checked"};
                   1538:     if (kwclr=="green") {var grnsel="checked"};
                   1539:     if (kwclr=="blue")  {var blusel="checked"};
                   1540:     var sznsel = "";
                   1541:     var sz1sel = "";
                   1542:     var sz2sel = "";
                   1543:     if (kwsize=="0")  {var sznsel="checked"};
                   1544:     if (kwsize=="+1") {var sz1sel="checked"};
                   1545:     if (kwsize=="+2") {var sz2sel="checked"};
                   1546:     var synsel = "";
                   1547:     var syisel = "";
                   1548:     var sybsel = "";
                   1549:     if (kwstyle=="")    {var synsel="checked"};
                   1550:     if (kwstyle=="<i>") {var syisel="checked"};
                   1551:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1552:     highlightCentral();
                   1553:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1554:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1555:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1556:     highlightend();
                   1557:     return;
                   1558:   }
                   1559: 
                   1560:   function highlightCentral() {
1.76      ng       1561: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1562:     var xpos = (screen.width-400)/2;
                   1563:     xpos = (xpos < 0) ? '0' : xpos;
                   1564:     var ypos = (screen.height-330)/2-30;
                   1565:     ypos = (ypos < 0) ? '0' : ypos;
                   1566: 
1.206     albertel 1567:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1568:     hwdWin.focus();
                   1569:     var hDoc = hwdWin.document;
1.219     www      1570:     hDoc.$docopen;
1.351     albertel 1571:     hDoc.write('$start_page_highlight_central');
1.76      ng       1572:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.465     albertel 1573:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options<\\/span><\\/h3><br /><br />");
1.76      ng       1574: 
                   1575:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1576:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
1.465     albertel 1577:     hDoc.write("<td><b>Text Color<\\/b><\\/td><td><b>Font Size<\\/b><\\/td><td><b>Font Style<\\/td><\\/tr>");
1.44      ng       1578:   }
                   1579: 
                   1580:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1581:     var hDoc = hwdWin.document;
                   1582:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1583:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1584:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"<\\/td>");
1.76      ng       1585:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1586:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"<\\/td>");
1.76      ng       1587:     hDoc.write("<td align=\\"left\\">");
1.465     albertel 1588:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"<\\/td>");
                   1589:     hDoc.write("<\\/tr>");
1.44      ng       1590:   }
                   1591: 
                   1592:   function highlightend() { 
1.76      ng       1593:     var hDoc = hwdWin.document;
1.465     albertel 1594:     hDoc.write("<\\/table>");
                   1595:     hDoc.write("<\\/td><\\/tr><\\/table>&nbsp;");
1.76      ng       1596:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1597:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.465     albertel 1598:     hDoc.write("<\\/form>");
1.351     albertel 1599:     hDoc.write('$end_page_highlight_central');
1.128     ng       1600:     hDoc.close();
1.44      ng       1601:   }
                   1602: 
                   1603: </script>
                   1604: SUBJAVASCRIPT
                   1605: }
                   1606: 
1.349     albertel 1607: sub get_increment {
1.348     bowersj2 1608:     my $increment = $env{'form.increment'};
                   1609:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1610:         $increment != .1) {
                   1611:         $increment = 1;
                   1612:     }
                   1613:     return $increment;
                   1614: }
                   1615: 
1.71      ng       1616: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1617: sub gradeBox {
1.322     albertel 1618:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1619:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1620: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1621: 	'/check.gif" height="16" border="0" />';
                   1622:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
1.466     albertel 1623:     my $wgtmsg = ($wgt > 0) ? &mt('(problem weight)') 
                   1624:                            : '<span class="LC_info">'.&mt('problem weight assigned by computer').'</span>';
1.71      ng       1625:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1626:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1627: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1628:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.466     albertel 1629:     my $display_part= &get_display_part($partid,$symb);
1.270     albertel 1630:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1631: 				       [$partid]);
                   1632:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1633:     if ($last_resets{$partid}) {
                   1634:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1635:     }
1.71      ng       1636:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1637: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1638:     my $ctr = 0;
1.348     bowersj2 1639:     my $thisweight = 0;
1.349     albertel 1640:     my $increment = &get_increment();
1.71      ng       1641:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1642:     while ($thisweight<=$wgt) {
1.381     albertel 1643: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1644: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1645: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1646: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1647: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1648:         $thisweight += $increment;
1.71      ng       1649: 	$ctr++;
                   1650:     }
                   1651:     $result.='</tr></table>';
                   1652:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1653:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1654: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1655: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1656: 	$wgt.')" /></td>'."\n";
                   1657:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1658: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1659: 	' </td><td>'."\n";
                   1660:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1661: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1662:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1663: 	$result.='<option></option>'.
1.401     albertel 1664: 	    '<option selected="selected">excused</option>';
1.71      ng       1665:     } else {
1.401     albertel 1666: 	$result.='<option selected="selected"></option>'.
1.125     ng       1667: 	    '<option>excused</option>';
1.71      ng       1668:     }
1.125     ng       1669:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1670:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1671:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1672: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1673: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1674: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1675:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1676:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1677:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1678:         $aggtries.'" />'."\n";
1.71      ng       1679:     $result.='</td></tr></table>'."\n";
1.323     banghart 1680:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1681:     return $result;
                   1682: }
1.322     albertel 1683: 
                   1684: sub handback_box {
1.323     banghart 1685:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1686:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1687:     my (@respids);
1.375     albertel 1688:      my @part_response_id = &flatten_responseType($responseType);
                   1689:     foreach my $part_response_id (@part_response_id) {
                   1690:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1691:         if ($part eq $partid) {
1.375     albertel 1692:             push(@respids,$resp);
1.323     banghart 1693:         }
                   1694:     }
1.318     banghart 1695:     my $result;
1.323     banghart 1696:     foreach my $respid (@respids) {
1.322     albertel 1697: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1698: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1699: 	next if (!@$files);
                   1700: 	my $file_counter = 1;
1.313     banghart 1701: 	foreach my $file (@$files) {
1.368     banghart 1702: 	    if ($file =~ /\/portfolio\//) {
                   1703:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1704:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1705:     	        $file_disp = "$name.$ext";
                   1706:     	        $file = $file_path.$file_disp;
                   1707:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1708:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1709:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1710:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.466     albertel 1711:     	        $result.='(File will be uploaded when you click on Save &amp; Next below.)<br />';
1.368     banghart 1712:     	        $file_counter++;
                   1713: 	    }
1.322     albertel 1714: 	}
1.313     banghart 1715:     }
1.318     banghart 1716:     return $result;    
1.71      ng       1717: }
1.44      ng       1718: 
1.58      albertel 1719: sub show_problem {
1.382     albertel 1720:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1721:     my $rendered;
1.382     albertel 1722:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1723:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1724:     if ($mode eq 'both' or $mode eq 'text') {
                   1725: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1726: 						       $env{'request.course.id'},
                   1727: 						       undef,\%form);
1.144     albertel 1728:     }
1.58      albertel 1729:     if ($removeform) {
                   1730: 	$rendered=~s|<form(.*?)>||g;
                   1731: 	$rendered=~s|</form>||g;
1.374     albertel 1732: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1733:     }
1.144     albertel 1734:     my $companswer;
                   1735:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1736: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1737: 	$companswer=
                   1738: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1739: 						    $env{'request.course.id'},
                   1740: 						    %form);
1.144     albertel 1741:     }
1.58      albertel 1742:     if ($removeform) {
                   1743: 	$companswer=~s|<form(.*?)>||g;
                   1744: 	$companswer=~s|</form>||g;
1.144     albertel 1745: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1746:     }
1.468     albertel 1747:     $rendered=
                   1748: 	'<div class="LC_grade_show_problem_header">'.
                   1749: 	&mt('View of the problem').
                   1750: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1751: 	$rendered.
                   1752: 	'</div>';
                   1753:     $companswer=
                   1754: 	'<div class="LC_grade_show_problem_header">'.
                   1755: 	&mt('Correct answer').
                   1756: 	'</div><div class="LC_grade_show_problem_problem">'.
                   1757: 	$companswer.
                   1758: 	'</div>';
                   1759:     my $result;
1.144     albertel 1760:     if ($mode eq 'both') {
1.468     albertel 1761: 	$result=$rendered.$companswer;
1.144     albertel 1762:     } elsif ($mode eq 'text') {
1.468     albertel 1763: 	$result=$rendered;
1.144     albertel 1764:     } elsif ($mode eq 'answer') {
1.468     albertel 1765: 	$result=$companswer;
1.144     albertel 1766:     }
1.468     albertel 1767:     $result='<div class="LC_grade_show_problem">'.$result.'</div>';
1.71      ng       1768:     return $result;
1.58      albertel 1769: }
1.397     albertel 1770: 
1.396     banghart 1771: sub files_exist {
                   1772:     my ($r, $symb) = @_;
                   1773:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1774: 
1.396     banghart 1775:     foreach my $student (@students) {
                   1776:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1777:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1778: 					      $udom,$uname);
1.396     banghart 1779:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1780:         foreach my $submission (@$string) {
                   1781:             my ($partid,$respid) =
                   1782: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1783:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1784: 					   \%record);
                   1785:             return 1 if (@$files);
1.396     banghart 1786:         }
                   1787:     }
1.397     albertel 1788:     return 0;
1.396     banghart 1789: }
1.397     albertel 1790: 
1.394     banghart 1791: sub download_all_link {
                   1792:     my ($r,$symb) = @_;
1.395     albertel 1793:     my $all_students = 
                   1794: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1795: 
                   1796:     my $parts =
                   1797: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1798: 
1.394     banghart 1799:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1800:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1801:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1802:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1803:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1804: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1805:     return
                   1806: }
1.395     albertel 1807: 
1.432     banghart 1808: sub build_section_inputs {
                   1809:     my $section_inputs;
                   1810:     if ($env{'form.section'} eq '') {
                   1811:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1812:     } else {
                   1813:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1814:         foreach my $section (@sections) {
1.432     banghart 1815:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1816:         }
                   1817:     }
                   1818:     return $section_inputs;
                   1819: }
                   1820: 
1.44      ng       1821: # --------------------------- show submissions of a student, option to grade 
                   1822: sub submission {
                   1823:     my ($request,$counter,$total) = @_;
1.257     albertel 1824:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1825:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1826:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1827:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1828:     my $symb = &get_symb($request); 
                   1829:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1830: 
                   1831:     if (!&canview($usec)) {
1.398     albertel 1832: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1833: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1834: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1835: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1836: 	return;
                   1837:     }
                   1838: 
1.257     albertel 1839:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1840:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1841:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1842:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1843:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1844: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1845: 	'/check.gif" height="16" border="0" />';
1.41      ng       1846: 
1.426     albertel 1847:     my %old_essays;
1.41      ng       1848:     # header info
                   1849:     if ($counter == 0) {
                   1850: 	&sub_page_js($request);
1.257     albertel 1851: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1852: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1853: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1854: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1855: 	    &download_all_link($request, $symb);
                   1856: 	}
1.398     albertel 1857: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1858: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1859: 
1.44      ng       1860: 	# option to display problem, only once else it cause problems 
                   1861:         # with the form later since the problem has a form.
1.257     albertel 1862: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1863: 	    my $mode;
1.257     albertel 1864: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1865: 		$mode='both';
1.257     albertel 1866: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1867: 		$mode='text';
1.257     albertel 1868: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1869: 		$mode='answer';
                   1870: 	    }
1.329     albertel 1871: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1872: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1873: 	}
1.441     www      1874: 
1.44      ng       1875: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1876:         # if this subroutine has been called once.
1.41      ng       1877: 	my %keyhash = ();
1.257     albertel 1878: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1879: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1880: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1881: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1882: 
1.257     albertel 1883: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1884: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1885: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1886: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1887: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1888: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1889: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1890: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1891: 	}
1.257     albertel 1892: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1893: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1894: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1895: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1896: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1897: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1898: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1899: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1900: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1901: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1902: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1903: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1904: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1905: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1906: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1907: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1908: 			&build_section_inputs().
1.326     albertel 1909: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1910: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1911: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1912: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1913: 	if ($env{'form.handgrade'} eq 'yes') {
                   1914: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1915: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1916: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1917: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1918: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1919: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1920: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1921: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1922: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1923: 	    }
1.123     ng       1924: 	}
1.41      ng       1925: 	
                   1926: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1927: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1928: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1929: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1930: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1931: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1932: 		'" />'."\n".
                   1933: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1934: 	    $cts++;
                   1935: 	}
                   1936: 	$request->print($prnmsg);
1.32      ng       1937: 
1.257     albertel 1938: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1939: #
                   1940: # Print out the keyword options line
                   1941: #
1.41      ng       1942: 	    $request->print(<<KEYWORDS);
1.38      ng       1943: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1944: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1945: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1946:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1947: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1948: KEYWORDS
1.88      www      1949: #
                   1950: # Load the other essays for similarity check
                   1951: #
1.324     albertel 1952:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1953: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1954: 	    $apath=&escape($apath);
1.88      www      1955: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1956: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1957:         }
                   1958:     }
1.44      ng       1959: 
1.441     www      1960: # This is where output for one specific student would start
1.468     albertel 1961:     my $add_class = ($counter%2) ? 'LC_grade_show_user_odd_row' : '';
1.441     www      1962:     $request->print("\n\n".
1.468     albertel 1963:                     '<div class="LC_grade_show_user '.$add_class.'">'.
                   1964: 		    '<div class="LC_grade_user_name">'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'</div>'.
                   1965: 		    '<div class="LC_grade_show_user_body">'."\n");
1.441     www      1966: 
1.257     albertel 1967:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1968: 	my $mode;
1.257     albertel 1969: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1970: 	    $mode='both';
1.257     albertel 1971: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1972: 	    $mode='text';
1.257     albertel 1973: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1974: 	    $mode='answer';
                   1975: 	}
1.329     albertel 1976: 	&Apache::lonxml::clear_problem_counter();
1.475     albertel 1977: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode,{'request.prefix' => 'ctr'.$counter}));
1.58      albertel 1978:     }
1.144     albertel 1979: 
1.257     albertel 1980:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1981:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1982: 
1.44      ng       1983:     # Display student info
1.41      ng       1984:     $request->print(($counter == 0 ? '' : '<br />'));
1.468     albertel 1985:     my $result='<div class="LC_grade_submissions">';
                   1986:     
                   1987:     $result.='<div class="LC_grade_submissions_header">';
                   1988:     $result.= &mt('Submissions');
1.45      ng       1989:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1990: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.469     albertel 1991:     if ($env{'form.handgrade'} eq 'no') {
                   1992: 	$result.='<span class="LC_grade_check_note">'.
                   1993: 	    &mt('Part(s) graded correct by the computer is marked with a [_1] symbol.',$checkIcon)."</span>\n";
                   1994: 
                   1995:     }
                   1996: 
                   1997: 
1.41      ng       1998: 
1.118     ng       1999:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.464     albertel 2000:     my $fullname;
                   2001:     my $col_fullnames = [];
1.257     albertel 2002:     if ($env{'form.handgrade'} eq 'yes') {
1.464     albertel 2003: 	(my $sub_result,$fullname,$col_fullnames)=
                   2004: 	    &check_collaborators($symb,$uname,$udom,\%record,$handgrade,
                   2005: 				 $counter);
                   2006: 	$result.=$sub_result;
1.41      ng       2007:     }
1.44      ng       2008:     $request->print($result."\n");
1.468     albertel 2009:     $request->print('</div>'."\n");
1.44      ng       2010:     # print student answer/submission
                   2011:     # Options are (1) Handgaded submission only
                   2012:     #             (2) Last submission, includes submission that is not handgraded 
                   2013:     #                  (for multi-response type part)
                   2014:     #             (3) Last submission plus the parts info
                   2015:     #             (4) The whole record for this student
1.257     albertel 2016:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2017: 	my ($string,$timestamp)= &get_last_submission(\%record);
1.468     albertel 2018: 	
                   2019: 	my $lastsubonly;
                   2020: 
1.151     albertel 2021: 	if ($$timestamp eq '') {
1.468     albertel 2022: 	    $lastsubonly.='<div class="LC_grade_submissions_body">'.$$string[0].'</div>'; 
1.151     albertel 2023: 	} else {
1.468     albertel 2024: 	    $lastsubonly = '<div class="LC_grade_submissions_body"> <b>Date Submitted:</b> '.$$timestamp."\n";
                   2025: 
1.151     albertel 2026: 	    my %seenparts;
1.375     albertel 2027: 	    my @part_response_id = &flatten_responseType($responseType);
                   2028: 	    foreach my $part (@part_response_id) {
1.393     albertel 2029: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2030: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2031: 
1.375     albertel 2032: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2033: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2034: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2035: 		    if (exists($seenparts{$partid})) { next; }
                   2036: 		    $seenparts{$partid}=1;
1.207     albertel 2037: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2038: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2039: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2040: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2041: 			'\');" target="_self">'.
1.257     albertel 2042: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2043: 		    $request->print($submitby);
                   2044: 		    next;
                   2045: 		}
                   2046: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2047: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.468     albertel 2048: 		    $lastsubonly.="\n".'<div class="LC_grade_submission_part"><b>Part:</b> '.
1.398     albertel 2049: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2050: 			' )</span>&nbsp; &nbsp;'.
1.468     albertel 2051: 			'<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br /><br /></div>';
1.151     albertel 2052: 		    next;
                   2053: 		}
1.468     albertel 2054: 		foreach my $submission (@$string) {
                   2055: 		    my ($partid,$respid) = ($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
1.375     albertel 2056: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.468     albertel 2057: 		    my ($ressub,$subval) = split(/:/,$submission,2);
1.151     albertel 2058: 		    # Similarity check
                   2059: 		    my $similar='';
1.257     albertel 2060: 		    if($env{'form.checkPlag'}){
1.151     albertel 2061: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2062: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2063: 			if ($osim) {
                   2064: 			    $osim=int($osim*100.0);
1.426     albertel 2065: 			    my %old_course_desc = 
                   2066: 				&Apache::lonnet::coursedescription($ocrsid,
                   2067: 								   {'one_time' => 1});
                   2068: 
                   2069: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2070: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2071: 				    $osim,
                   2072: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2073: 				    $oname,$odom,
1.426     albertel 2074: 				    $old_course_desc{'description'},
1.427     albertel 2075: 				    $old_course_desc{'num'},
1.426     albertel 2076: 				    $old_course_desc{'domain'}).
1.398     albertel 2077: 				'</span></h3><blockquote><i>'.
1.151     albertel 2078: 				&keywords_highlight($oessay).
                   2079: 				'</i></blockquote><hr />';
                   2080: 			}
1.150     albertel 2081: 		    }
1.151     albertel 2082: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2083: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2084: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2085: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2086: 			my $display_part=&get_display_part($partid,$symb);
1.468     albertel 2087: 			$lastsubonly.='<div class="LC_grade_submission_part"><b>Part:</b> '.
1.403     albertel 2088: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2089: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2090: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2091: 			if (@$files) {
1.468     albertel 2092: 			    $lastsubonly.='<br /><span class="LC_warning">'.&mt('Like all files provided by users, this file may contain virusses').'</span><br />';
1.303     banghart 2093: 			    my $file_counter = 0;
1.313     banghart 2094: 			    foreach my $file (@$files) {
1.468     albertel 2095: 			        $file_counter++;
1.232     albertel 2096: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2097: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2098: 			    }
1.236     albertel 2099: 			    $lastsubonly.='<br />';
1.41      ng       2100: 			}
1.468     albertel 2101: 			$lastsubonly.='<b>'.&mt('Submitted Answer:').' </b>'.
1.151     albertel 2102: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2103: 					 $respid,\%record,$order);
                   2104: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.468     albertel 2105: 			$lastsubonly.='</div>';
1.41      ng       2106: 		    }
                   2107: 		}
                   2108: 	    }
1.468     albertel 2109: 	    $lastsubonly.='</div>'."\n";
1.151     albertel 2110: 	}
                   2111: 	$request->print($lastsubonly);
1.468     albertel 2112:    } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2113: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2114: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2115:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2116: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2117: 								 $env{'request.course.id'},
1.44      ng       2118: 								 $last,'.submission',
                   2119: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2120:     }
1.120     ng       2121: 
1.121     ng       2122:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2123: 	.$udom.'" />'."\n");
1.44      ng       2124:     # return if view submission with no grading option
1.257     albertel 2125:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2126: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2127: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2128: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.468     albertel 2129: 	$toGrade.='</div>'."\n";
1.257     albertel 2130: 	if (($env{'form.command'} eq 'submission') || 
                   2131: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2132: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2133: 	}
1.180     albertel 2134: 	$request->print($toGrade);
1.41      ng       2135: 	return;
1.180     albertel 2136:     } else {
1.468     albertel 2137: 	$request->print('</div>'."\n");
1.41      ng       2138:     }
1.33      ng       2139: 
1.121     ng       2140:     # essay grading message center
1.257     albertel 2141:     if ($env{'form.handgrade'} eq 'yes') {
1.468     albertel 2142: 	my $result='<div class="LC_grade_message_center">';
                   2143:     
                   2144: 	$result.='<div class="LC_grade_message_center_header">'.
                   2145: 	    &mt('Send Message').'</div><div class="LC_grade_message_center_body">';
1.257     albertel 2146: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2147: 	my $msgfor = $givenn.' '.$lastname;
1.464     albertel 2148: 	if (scalar(@$col_fullnames) > 0) {
                   2149: 	    my $lastone = pop(@$col_fullnames);
                   2150: 	    $msgfor .= ', '.(join ', ',@$col_fullnames).' and '.$lastone.'.';
1.118     ng       2151: 	}
                   2152: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.468     albertel 2153: 	$result.='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
1.121     ng       2154: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2155: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2156: 	    ',\''.$msgfor.'\');" target="_self">'.
1.464     albertel 2157: 	    &mt('Compose message to student').(scalar(@$col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
1.350     albertel 2158: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2159: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2160: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2161: 	    '<br />&nbsp;('.
1.468     albertel 2162: 	    &mt('Message will be sent when you click on Save &amp; Next below.').")\n";
                   2163: 	$result.='</div></div>';
1.121     ng       2164: 	$request->print($result);
1.118     ng       2165:     }
1.41      ng       2166: 
                   2167:     my %seen = ();
                   2168:     my @partlist;
1.129     ng       2169:     my @gradePartRespid;
1.375     albertel 2170:     my @part_response_id = &flatten_responseType($responseType);
1.468     albertel 2171:     $request->print('<div class="LC_grade_assign">'.
                   2172: 		    
                   2173: 		    '<div class="LC_grade_assign_header">'.
                   2174: 		    &mt('Assign Grades').'</div>'.
                   2175: 		    '<div class="LC_grade_assign_body">');
1.375     albertel 2176:     foreach my $part_response_id (@part_response_id) {
                   2177:     	my ($partid,$respid) = @{ $part_response_id };
                   2178: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2179: 	next if ($seen{$partid} > 0);
1.41      ng       2180: 	$seen{$partid}++;
1.393     albertel 2181: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2182: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2183: 	push @partlist,$partid;
1.129     ng       2184: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2185: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2186:     }
1.468     albertel 2187:     $request->print('</div></div>');
                   2188: 
                   2189:     $request->print('<div class="LC_grade_info_links">');
                   2190:     if ($perm{'vgr'}) {
                   2191: 	$request->print(
                   2192: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2193: 						   $uname,$udom,'check'));
                   2194:     }
                   2195:     if ($perm{'opa'}) {
                   2196: 	$request->print(
                   2197: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2198: 					 $uname,$udom,$symb,'check'));
                   2199:     }
                   2200:     $request->print('</div>');
                   2201: 
1.45      ng       2202:     $result='<input type="hidden" name="partlist'.$counter.
                   2203: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2204:     $result.='<input type="hidden" name="gradePartRespid'.
                   2205: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2206:     my $ctr = 0;
                   2207:     while ($ctr < scalar(@partlist)) {
                   2208: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2209: 	    $partlist[$ctr].'" />'."\n";
                   2210: 	$ctr++;
                   2211:     }
1.468     albertel 2212:     $request->print($result.''."\n");
1.41      ng       2213: 
1.441     www      2214: # Done with printing info for one student
                   2215: 
1.468     albertel 2216:     $request->print('</div>');#LC_grade_show_user_body
                   2217:     $request->print('</div>');#LC_grade_show_user
1.441     www      2218: 
                   2219: 
1.41      ng       2220:     # print end of form
                   2221:     if ($counter == $total) {
1.297     www      2222: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2223: 	$endform.='<input type="button" value="Save & Next" '.
                   2224: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2225: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2226: 	my $ntstu ='<select name="NTSTU">'.
                   2227: 	    '<option>1</option><option>2</option>'.
                   2228: 	    '<option>3</option><option>5</option>'.
                   2229: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2230: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2231: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2232: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2233: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2234: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2235: 	    '<input type="button" value="Next" '.
1.417     albertel 2236: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2237: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2238:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2239:             "' name='increment' />";
1.45      ng       2240: 	$endform.='</td><tr></table></form>';
1.324     albertel 2241: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2242: 	$request->print($endform);
                   2243:     }
                   2244:     return '';
1.38      ng       2245: }
                   2246: 
1.464     albertel 2247: sub check_collaborators {
                   2248:     my ($symb,$uname,$udom,$record,$handgrade,$counter) = @_;
                   2249:     my ($result,@col_fullnames);
                   2250:     my ($classlist,undef,$fullname) = &getclasslist('all','0');
                   2251:     foreach my $part (keys(%$handgrade)) {
                   2252: 	my $ncol = &Apache::lonnet::EXT('resource.'.$part.
                   2253: 					'.maxcollaborators',
                   2254: 					$symb,$udom,$uname);
                   2255: 	next if ($ncol <= 0);
                   2256: 	$part =~ s/\_/\./g;
                   2257: 	next if ($record->{'resource.'.$part.'.collaborators'} eq '');
                   2258: 	my (@good_collaborators, @bad_collaborators);
                   2259: 	foreach my $possible_collaborator
                   2260: 	    (split(/,?\s+/,$record->{'resource.'.$part.'.collaborators'})) { 
                   2261: 	    $possible_collaborator =~ s/[\$\^\(\)]//g;
                   2262: 	    next if ($possible_collaborator eq '');
                   2263: 	    my ($co_name,$co_dom) = split(/\@|:/,$possible_collaborator);
                   2264: 	    $co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
                   2265: 	    next if ($co_name eq $uname && $co_dom eq $udom);
                   2266: 	    # Doing this grep allows 'fuzzy' specification
                   2267: 	    my @matches = grep(/^\Q$co_name\E:\Q$co_dom\E$/i, 
                   2268: 			       keys(%$classlist));
                   2269: 	    if (! scalar(@matches)) {
                   2270: 		push(@bad_collaborators, $possible_collaborator);
                   2271: 	    } else {
                   2272: 		push(@good_collaborators, @matches);
                   2273: 	    }
                   2274: 	}
                   2275: 	if (scalar(@good_collaborators) != 0) {
1.466     albertel 2276: 	    $result.='<br />'.&mt('Collaborators: ');
1.464     albertel 2277: 	    foreach my $name (@good_collaborators) {
                   2278: 		my ($lastname,$givenn) = split(/,/,$$fullname{$name});
                   2279: 		push(@col_fullnames, $givenn.' '.$lastname);
                   2280: 		$result.=$fullname->{$name}.'&nbsp; &nbsp; &nbsp;';
                   2281: 	    }
                   2282: 	    $result.='<br />'."\n";
1.466     albertel 2283: 	    my ($part)=split(/\./,$part);
1.464     albertel 2284: 	    $result.='<input type="hidden" name="collaborator'.$counter.
                   2285: 		'" value="'.$part.':'.(join ':',@good_collaborators).'" />'.
                   2286: 		"\n";
                   2287: 	}
                   2288: 	if (scalar(@bad_collaborators) > 0) {
1.466     albertel 2289: 	    $result.='<div class="LC_warning">';
1.464     albertel 2290: 	    $result.=&mt('This student has submitted [quant,_1,invalid collaborator]: [_2]',scalar(@bad_collaborators),join(', ',@bad_collaborators));
                   2291: 	    $result .= '</div>';
                   2292: 	}         
                   2293: 	if (scalar(@bad_collaborators > $ncol)) {
1.466     albertel 2294: 	    $result .= '<div class="LC_warning">';
1.464     albertel 2295: 	    $result .= &mt('This student has submitted too many '.
                   2296: 		'collaborators.  Maximum is [_1].',$ncol);
                   2297: 	    $result .= '</div>';
                   2298: 	}
                   2299:     }
                   2300:     return ($result,$fullname,\@col_fullnames);
                   2301: }
                   2302: 
1.44      ng       2303: #--- Retrieve the last submission for all the parts
1.38      ng       2304: sub get_last_submission {
1.119     ng       2305:     my ($returnhash)=@_;
1.46      ng       2306:     my (@string,$timestamp);
1.119     ng       2307:     if ($$returnhash{'version'}) {
1.46      ng       2308: 	my %lasthash=();
                   2309: 	my ($version);
1.119     ng       2310: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2311: 	    foreach my $key (sort(split(/\:/,
                   2312: 					$$returnhash{$version.':keys'}))) {
                   2313: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2314: 		$timestamp = 
                   2315: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2316: 	    }
                   2317: 	}
1.397     albertel 2318: 	foreach my $key (keys(%lasthash)) {
                   2319: 	    next if ($key !~ /\.submission$/);
                   2320: 
                   2321: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2322: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2323: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2324: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2325: 	}
                   2326:     }
1.397     albertel 2327:     if (!@string) {
                   2328: 	$string[0] =
1.398     albertel 2329: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2330:     }
                   2331:     return (\@string,\$timestamp);
1.38      ng       2332: }
1.35      ng       2333: 
1.44      ng       2334: #--- High light keywords, with style choosen by user.
1.38      ng       2335: sub keywords_highlight {
1.44      ng       2336:     my $string    = shift;
1.257     albertel 2337:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2338:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2339:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2340:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2341:     foreach my $keyword (@keylist) {
                   2342: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2343:     }
                   2344:     return $string;
1.38      ng       2345: }
1.36      ng       2346: 
1.44      ng       2347: #--- Called from submission routine
1.38      ng       2348: sub processHandGrade {
1.41      ng       2349:     my ($request) = shift;
1.324     albertel 2350:     my $symb   = &get_symb($request);
                   2351:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2352:     my $button = $env{'form.gradeOpt'};
                   2353:     my $ngrade = $env{'form.NCT'};
                   2354:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2355:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2356:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2357: 
1.44      ng       2358:     if ($button eq 'Save & Next') {
                   2359: 	my $ctr = 0;
                   2360: 	while ($ctr < $ngrade) {
1.257     albertel 2361: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2362: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2363: 	    if ($errorflag eq 'no_score') {
                   2364: 		$ctr++;
                   2365: 		next;
                   2366: 	    }
1.104     albertel 2367: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2368: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2369: 		$ctr++;
                   2370: 		next;
                   2371: 	    }
1.257     albertel 2372: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2373: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2374: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2375:             my ($feedurl,$showsymb) =
                   2376: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2377: 	    my $messagetail;
1.62      albertel 2378: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2379: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2380: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2381: 		$subject.=' ['.$restitle.']';
1.44      ng       2382: 		my (@msgnum) = split(/,/,$includemsg);
                   2383: 		foreach (@msgnum) {
1.257     albertel 2384: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2385: 		}
1.80      ng       2386: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2387: 		if ($env{'form.withgrades'.$ctr}) {
                   2388: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2389: 		    $messagetail = " for <a href=\"".
1.418     albertel 2390: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2391: 		}
                   2392: 		$msgstatus = 
                   2393:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2394: 						     $message.$messagetail,
1.418     albertel 2395:                                                      undef,$feedurl,undef,
1.386     raeburn  2396:                                                      undef,undef,$showsymb,
                   2397:                                                      $restitle);
                   2398: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2399: 				$msgstatus);
1.44      ng       2400: 	    }
1.257     albertel 2401: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2402: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2403: 		foreach my $collabstr (@collabstrs) {
                   2404: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2405: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2406: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2407: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2408: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2409: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2410: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2411: 			    next;
1.418     albertel 2412: 			} elsif ($message ne '') {
                   2413: 			    my ($baseurl,$showsymb) = 
                   2414: 				&get_feedurl_and_symb($symb,$collaborator,
                   2415: 						      $udom);
                   2416: 			    if ($env{'form.withgrades'.$ctr}) {
                   2417: 				$messagetail = " for <a href=\"".
1.386     raeburn  2418:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2419: 			    }
1.418     albertel 2420: 			    $msgstatus = 
                   2421: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2422: 			}
1.44      ng       2423: 		    }
                   2424: 		}
                   2425: 	    }
                   2426: 	    $ctr++;
                   2427: 	}
                   2428:     }
                   2429: 
1.257     albertel 2430:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2431: 	# Keywords sorted in alphabatical order
1.257     albertel 2432: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2433: 	my %keyhash = ();
1.257     albertel 2434: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2435: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2436: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2437: 	$env{'form.keywords'} = join(' ',@keywords);
                   2438: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2439: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2440: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2441: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2442: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2443: 
                   2444: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2445: 	# New messages are saved in env for the next student.
1.119     ng       2446: 	# All messages are saved in nohist_handgrade.db
                   2447: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2448: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2449: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2450: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2451: 		$idx++;
                   2452: 	    }
                   2453: 	    $ctr++;
1.41      ng       2454: 	}
1.119     ng       2455: 	$ctr = 0;
                   2456: 	while ($ctr < $ngrade) {
1.257     albertel 2457: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2458: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2459: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2460: 		$idx++;
                   2461: 	    }
                   2462: 	    $ctr++;
1.41      ng       2463: 	}
1.257     albertel 2464: 	$env{'form.savemsgN'} = --$idx;
                   2465: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2466: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2467: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2468:     }
1.44      ng       2469:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2470:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2471:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2472: 	my ($ctr,$total) = (0,0);
                   2473: 	while ($ctr < $ngrade) {
1.257     albertel 2474: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2475: 	    $ctr++;
                   2476: 	}
1.257     albertel 2477: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2478: 	$ctr = 0;
                   2479: 	while ($ctr < $total) {
1.257     albertel 2480: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2481: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2482: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2483: 	    &submission($request,$ctr,$total-1);
1.41      ng       2484: 	    $ctr++;
                   2485: 	}
                   2486: 	return '';
                   2487:     }
1.36      ng       2488: 
1.121     ng       2489: # Go directly to grade student - from submission or link from chart page
1.120     ng       2490:     if ($button eq 'Grade Student') {
1.324     albertel 2491: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2492: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2493: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2494: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2495: 	&submission($request,0,0);
                   2496: 	return '';
                   2497:     }
                   2498: 
1.44      ng       2499:     # Get the next/previous one or group of students
1.257     albertel 2500:     my $firststu = $env{'form.unamedom0'};
                   2501:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2502:     my $ctr = 2;
1.41      ng       2503:     while ($laststu eq '') {
1.257     albertel 2504: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2505: 	$ctr++;
                   2506: 	$laststu = $firststu if ($ctr > $ngrade);
                   2507:     }
1.44      ng       2508: 
1.41      ng       2509:     my (@parsedlist,@nextlist);
                   2510:     my ($nextflg) = 0;
1.294     albertel 2511:     foreach (sort 
                   2512: 	     {
                   2513: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2514: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2515: 		 }
                   2516: 		 return $a cmp $b;
                   2517: 	     } (keys(%$fullname))) {
1.41      ng       2518: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2519: 	    push @parsedlist,$_;
                   2520: 	}
                   2521: 	$nextflg = 1 if ($_ eq $laststu);
                   2522: 	if ($button eq 'Previous') {
                   2523: 	    last if ($_ eq $firststu);
                   2524: 	    push @parsedlist,$_;
                   2525: 	}
                   2526:     }
                   2527:     $ctr = 0;
                   2528:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2529:     my ($partlist) = &response_type($symb);
1.41      ng       2530:     foreach my $student (@parsedlist) {
1.257     albertel 2531: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2532: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2533: 	
                   2534: 	if ($submitonly eq 'queued') {
                   2535: 	    my %queue_status = 
                   2536: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2537: 							$udom,$uname);
                   2538: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2539: 	}
                   2540: 
1.156     albertel 2541: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2542: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2543: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2544: 	    my $submitted = 0;
1.248     albertel 2545: 	    my $ungraded = 0;
                   2546: 	    my $incorrect = 0;
1.145     albertel 2547: 	    foreach (keys(%status)) {
                   2548: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2549: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2550: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2551: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2552: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2553: 		    $submitted = 0;
                   2554: 		}
1.41      ng       2555: 	    }
1.156     albertel 2556: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2557: 				     $submitonly eq 'incorrect' ||
                   2558: 				     $submitonly eq 'graded'));
1.248     albertel 2559: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2560: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2561: 	}
                   2562: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2563: 	last if ($ctr == $ntstu);
1.41      ng       2564: 	$ctr++;
                   2565:     }
1.36      ng       2566: 
1.41      ng       2567:     $ctr = 0;
                   2568:     my $total = scalar(@nextlist)-1;
1.39      ng       2569: 
1.41      ng       2570:     foreach (sort @nextlist) {
                   2571: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2572: 	$env{'form.student'}  = $uname;
                   2573: 	$env{'form.userdom'}  = $udom;
                   2574: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2575: 	&submission($request,$ctr,$total);
                   2576: 	$ctr++;
                   2577:     }
                   2578:     if ($total < 0) {
1.398     albertel 2579: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2580: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2581: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2582: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2583: 	$request->print($the_end);
                   2584:     }
                   2585:     return '';
1.38      ng       2586: }
1.36      ng       2587: 
1.44      ng       2588: #---- Save the score and award for each student, if changed
1.38      ng       2589: sub saveHandGrade {
1.324     albertel 2590:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2591:     my @version_parts;
1.104     albertel 2592:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2593: 					   $env{'request.course.id'});
1.104     albertel 2594:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2595:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2596:     my @parts_graded;
1.77      ng       2597:     my %newrecord  = ();
                   2598:     my ($pts,$wgt) = ('','');
1.269     raeburn  2599:     my %aggregate = ();
                   2600:     my $aggregateflag = 0;
1.301     albertel 2601:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2602:     foreach my $new_part (@parts) {
1.337     banghart 2603: 	#collaborator ($submi may vary for different parts
1.259     banghart 2604: 	if ($submitter && $new_part ne $part) { next; }
                   2605: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2606: 	if ($dropMenu eq 'excused') {
1.259     banghart 2607: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2608: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2609: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2610: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2611: 		}
1.364     banghart 2612: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2613: 	    }
1.125     ng       2614: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2615: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2616: 	    foreach my $key (keys (%record)) {
1.259     banghart 2617: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2618: 	    }
1.259     banghart 2619: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2620: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2621:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2622: 
                   2623:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2624: 					       [$new_part]);
                   2625:             my $aggtries =$totaltries;
1.269     raeburn  2626:             if ($last_resets{$new_part}) {
1.270     albertel 2627:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2628: 					   $new_part);
1.269     raeburn  2629:             }
1.270     albertel 2630: 
                   2631:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2632:             if ($aggtries > 0) {
1.327     albertel 2633:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2634:                 $aggregateflag = 1;
                   2635:             }
1.125     ng       2636: 	} elsif ($dropMenu eq '') {
1.259     banghart 2637: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2638: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2639: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2640: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2641: 		next;
                   2642: 	    }
1.259     banghart 2643: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2644: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2645: 	    my $partial= $pts/$wgt;
1.259     banghart 2646: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2647: 		#do not update score for part if not changed.
1.346     banghart 2648:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2649: 		next;
1.251     banghart 2650: 	    } else {
1.259     banghart 2651: 	        push @parts_graded, $new_part;
1.153     albertel 2652: 	    }
1.259     banghart 2653: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2654: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2655: 	    }
1.259     banghart 2656: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2657: 	    if ($partial == 0) {
1.153     albertel 2658: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2659: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2660: 		}
1.41      ng       2661: 	    } else {
1.153     albertel 2662: 		if ($record{$reckey} ne 'correct_by_override') {
                   2663: 		    $newrecord{$reckey} = 'correct_by_override';
                   2664: 		}
                   2665: 	    }	    
                   2666: 	    if ($submitter && 
1.259     banghart 2667: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2668: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2669: 	    }
1.259     banghart 2670: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2671: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2672: 	}
1.259     banghart 2673: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2674: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2675: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2676: 	        $dropMenu eq 'reset status')
                   2677: 	   {
1.342     banghart 2678: 	    push (@version_parts,$new_part);
1.259     banghart 2679: 	}
1.41      ng       2680:     }
1.301     albertel 2681:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2682:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2683: 
1.344     albertel 2684:     if (%newrecord) {
                   2685:         if (@version_parts) {
1.364     banghart 2686:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2687:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2688: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2689: 	    foreach my $new_part (@version_parts) {
                   2690: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2691: 				$new_part,\%newrecord);
                   2692: 	    }
1.259     banghart 2693:         }
1.44      ng       2694: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2695: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2696: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2697: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2698:     }
1.269     raeburn  2699:     if ($aggregateflag) {
                   2700:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2701: 			      $cdom,$cnum);
1.269     raeburn  2702:     }
1.301     albertel 2703:     return ('',$pts,$wgt);
1.36      ng       2704: }
1.322     albertel 2705: 
1.380     albertel 2706: sub check_and_remove_from_queue {
                   2707:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2708:     my @ungraded_parts;
                   2709:     foreach my $part (@{$parts}) {
                   2710: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2711: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2712: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2713: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2714: 		) {
                   2715: 	    push(@ungraded_parts, $part);
                   2716: 	}
                   2717:     }
                   2718:     if ( !@ungraded_parts ) {
                   2719: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2720: 					       $cnum,$domain,$stuname);
                   2721:     }
                   2722: }
                   2723: 
1.337     banghart 2724: sub handback_files {
                   2725:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2726:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2727:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2728: 
                   2729:     my @part_response_id = &flatten_responseType($responseType);
                   2730:     foreach my $part_response_id (@part_response_id) {
                   2731:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2732: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2733:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2734:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2735:                 my $file_counter = 1;
1.367     albertel 2736: 		my $file_msg;
1.337     banghart 2737:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2738:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2739:                     my ($directory,$answer_file) = 
                   2740:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2741:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2742: 		        &file_name_version_ext($answer_file);
1.355     banghart 2743: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2744: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2745: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2746:                     # fix file name
                   2747:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2748:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2749:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2750:             	                                $save_file_name);
1.337     banghart 2751:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2752:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2753:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2754:                     } else {
1.360     banghart 2755:                         # mark the file as read only
                   2756:                         my @files = ($save_file_name);
1.372     albertel 2757:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2758:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2759: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2760: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2761: 			}
                   2762:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2763: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2764: 
1.337     banghart 2765:                     }
                   2766:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2767:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2768:                     $file_counter++;
                   2769:                 }
1.367     albertel 2770: 		my $subject = "File Handed Back by Instructor ";
                   2771: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2772: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2773: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2774: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2775: 		my ($feedurl,$showsymb) = 
                   2776: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2777:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2778: 		my $msgstatus = 
                   2779:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2780: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2781:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2782:             }
                   2783:         }
1.338     banghart 2784:     return;
1.337     banghart 2785: }
                   2786: 
1.418     albertel 2787: sub get_feedurl_and_symb {
                   2788:     my ($symb,$uname,$udom) = @_;
                   2789:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2790:     $url = &Apache::lonnet::clutter($url);
                   2791:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2792: 					$symb,$udom,$uname);
                   2793:     if ($encrypturl =~ /^yes$/i) {
                   2794: 	&Apache::lonenc::encrypted(\$url,1);
                   2795: 	&Apache::lonenc::encrypted(\$symb,1);
                   2796:     }
                   2797:     return ($url,$symb);
                   2798: }
                   2799: 
1.313     banghart 2800: sub get_submitted_files {
                   2801:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2802:     my @files;
                   2803:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2804:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2805:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2806:     	    push(@files,$file_url.$file);
                   2807:         }
                   2808:     }
                   2809:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2810:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2811:     }
                   2812:     return (\@files);
                   2813: }
1.322     albertel 2814: 
1.269     raeburn  2815: # ----------- Provides number of tries since last reset.
                   2816: sub get_num_tries {
                   2817:     my ($record,$last_reset,$part) = @_;
                   2818:     my $timestamp = '';
                   2819:     my $num_tries = 0;
                   2820:     if ($$record{'version'}) {
                   2821:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2822:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2823:                 $timestamp = $$record{$version.':timestamp'};
                   2824:                 if ($timestamp > $last_reset) {
                   2825:                     $num_tries ++;
                   2826:                 } else {
                   2827:                     last;
                   2828:                 }
                   2829:             }
                   2830:         }
                   2831:     }
                   2832:     return $num_tries;
                   2833: }
                   2834: 
                   2835: # ----------- Determine decrements required in aggregate totals 
                   2836: sub decrement_aggs {
                   2837:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2838:     my %decrement = (
                   2839:                         attempts => 0,
                   2840:                         users => 0,
                   2841:                         correct => 0
                   2842:                     );
                   2843:     $decrement{'attempts'} = $aggtries;
                   2844:     if ($solvedstatus =~ /^correct/) {
                   2845:         $decrement{'correct'} = 1;
                   2846:     }
                   2847:     if ($aggtries == $totaltries) {
                   2848:         $decrement{'users'} = 1;
                   2849:     }
                   2850:     foreach my $type (keys (%decrement)) {
                   2851:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2852:     }
                   2853:     return;
                   2854: }
                   2855: 
                   2856: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2857: sub get_last_resets {
1.270     albertel 2858:     my ($symb,$courseid,$partids) =@_;
                   2859:     my %last_resets;
1.269     raeburn  2860:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2861:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2862:     my @keys;
                   2863:     foreach my $part (@{$partids}) {
                   2864: 	push(@keys,"$symb\0$part\0resettime");
                   2865:     }
                   2866:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2867: 				     $cdom,$cname);
                   2868:     foreach my $part (@{$partids}) {
                   2869: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2870:     }
1.270     albertel 2871:     return %last_resets;
1.269     raeburn  2872: }
                   2873: 
1.251     banghart 2874: # ----------- Handles creating versions for portfolio files as answers
                   2875: sub version_portfiles {
1.343     banghart 2876:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2877:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2878:     my @returned_keys;
1.255     banghart 2879:     my $parts = join('|', @$parts_graded);
1.359     www      2880:     my $portfolio_root = &propath($domain,$stu_name).
                   2881: 	'/userfiles/portfolio';
1.277     albertel 2882:     foreach my $key (keys(%$record)) {
1.259     banghart 2883:         my $new_portfiles;
1.263     banghart 2884:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2885:             my @versioned_portfiles;
1.367     albertel 2886:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2887:             foreach my $file (@portfiles) {
1.306     banghart 2888:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2889:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2890: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2891: 		    &file_name_version_ext($answer_file);
1.306     banghart 2892:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2893:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2894:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2895:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2896:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2897:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2898:                         [$directory.$new_answer],
1.306     banghart 2899:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2900:                 }
1.252     banghart 2901:             }
1.343     banghart 2902:             $$record{$key} = join(',',@versioned_portfiles);
                   2903:             push(@returned_keys,$key);
1.251     banghart 2904:         }
                   2905:     } 
1.343     banghart 2906:     return (@returned_keys);   
1.305     banghart 2907: }
                   2908: 
1.307     banghart 2909: sub get_next_version {
1.341     banghart 2910:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2911:     my $version;
                   2912:     foreach my $row (@$dir_list) {
                   2913:         my ($file) = split(/\&/,$row,2);
                   2914:         my ($file_name,$file_version,$file_ext) =
                   2915: 	    &file_name_version_ext($file);
                   2916:         if (($file_name eq $answer_name) && 
                   2917: 	    ($file_ext eq $answer_ext)) {
                   2918:                 # gets here if filename and extension match, regardless of version
                   2919:                 if ($file_version ne '') {
                   2920:                 # a versioned file is found  so save it for later
                   2921:                 if ($file_version > $version) {
                   2922: 		    $version = $file_version;
                   2923: 	        }
                   2924:             }
                   2925:         }
                   2926:     } 
                   2927:     $version ++;
                   2928:     return($version);
                   2929: }
                   2930: 
1.305     banghart 2931: sub version_selected_portfile {
1.306     banghart 2932:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2933:     my ($answer_name,$answer_ver,$answer_ext) =
                   2934:         &file_name_version_ext($file_name);
                   2935:     my $new_answer;
                   2936:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2937:     if($env{'form.copy'} eq '-1') {
                   2938:         $new_answer = 'problem getting file';
                   2939:     } else {
                   2940:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2941:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2942:                             $stu_name,$domain,'copy',
                   2943: 		        '/portfolio'.$directory.$new_answer);
                   2944:     }    
                   2945:     return ($new_answer);
1.251     banghart 2946: }
                   2947: 
1.304     albertel 2948: sub file_name_version_ext {
                   2949:     my ($file)=@_;
                   2950:     my @file_parts = split(/\./, $file);
                   2951:     my ($name,$version,$ext);
                   2952:     if (@file_parts > 1) {
                   2953: 	$ext=pop(@file_parts);
                   2954: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2955: 	    $version=pop(@file_parts);
                   2956: 	}
                   2957: 	$name=join('.',@file_parts);
                   2958:     } else {
                   2959: 	$name=join('.',@file_parts);
                   2960:     }
                   2961:     return($name,$version,$ext);
                   2962: }
                   2963: 
1.44      ng       2964: #--------------------------------------------------------------------------------------
                   2965: #
                   2966: #-------------------------- Next few routines handles grading by section or whole class
                   2967: #
                   2968: #--- Javascript to handle grading by section or whole class
1.42      ng       2969: sub viewgrades_js {
                   2970:     my ($request) = shift;
                   2971: 
1.41      ng       2972:     $request->print(<<VIEWJAVASCRIPT);
                   2973: <script type="text/javascript" language="javascript">
1.45      ng       2974:    function writePoint(partid,weight,point) {
1.125     ng       2975: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2976: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2977: 	if (point == "textval") {
1.125     ng       2978: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2979: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2980: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2981: 		var resetbox = false;
                   2982: 		for (var i=0; i<radioButton.length; i++) {
                   2983: 		    if (radioButton[i].checked) {
                   2984: 			textbox.value = i;
                   2985: 			resetbox = true;
                   2986: 		    }
                   2987: 		}
                   2988: 		if (!resetbox) {
                   2989: 		    textbox.value = "";
                   2990: 		}
                   2991: 		return;
                   2992: 	    }
1.109     matthew  2993: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2994: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2995: 				   ") greater than the weight for the part. Accept?");
                   2996: 		if (resp == false) {
                   2997: 		    textbox.value = "";
                   2998: 		    return;
                   2999: 		}
                   3000: 	    }
1.42      ng       3001: 	    for (var i=0; i<radioButton.length; i++) {
                   3002: 		radioButton[i].checked=false;
1.109     matthew  3003: 		if (parseFloat(point) == i) {
1.42      ng       3004: 		    radioButton[i].checked=true;
                   3005: 		}
                   3006: 	    }
1.41      ng       3007: 
1.42      ng       3008: 	} else {
1.125     ng       3009: 	    textbox.value = parseFloat(point);
1.42      ng       3010: 	}
1.41      ng       3011: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3012: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 3013: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3014: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3015: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3016: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3017: 	    if (saveval != "correct") {
                   3018: 		scorename.value = point;
1.43      ng       3019: 		if (selname[0].selected != true) {
                   3020: 		    selname[0].selected = true;
                   3021: 		}
1.42      ng       3022: 	    }
                   3023: 	}
1.125     ng       3024: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       3025:     }
                   3026: 
                   3027:     function writeRadText(partid,weight) {
1.125     ng       3028: 	var selval   = document.classgrade["SELVAL_"+partid];
                   3029: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      3030:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       3031: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   3032: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3033: 	    for (var i=0; i<radioButton.length; i++) {
                   3034: 		radioButton[i].checked=false;
                   3035: 
                   3036: 	    }
                   3037: 	    textbox.value = "";
                   3038: 
                   3039: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3040: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3041: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3042: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3043: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3044: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3045: 		if ((saveval != "correct") || override) {
1.42      ng       3046: 		    scorename.value = "";
1.125     ng       3047: 		    if (selval[1].selected) {
                   3048: 			selname[1].selected = true;
                   3049: 		    } else {
                   3050: 			selname[2].selected = true;
                   3051: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3052: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3053: 		    }
1.42      ng       3054: 		}
                   3055: 	    }
1.43      ng       3056: 	} else {
                   3057: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3058: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3059: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3060: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3061: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3062: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3063: 		if ((saveval != "correct") || override) {
1.125     ng       3064: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3065: 		    selname[0].selected = true;
                   3066: 		}
                   3067: 	    }
                   3068: 	}	    
1.42      ng       3069:     }
                   3070: 
                   3071:     function changeSelect(partid,user) {
1.125     ng       3072: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3073: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3074: 	var point  = textbox.value;
1.125     ng       3075: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3076: 
1.109     matthew  3077: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3078: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3079: 	    textbox.value = "";
                   3080: 	    return;
                   3081: 	}
1.109     matthew  3082: 	if (parseFloat(point) > parseFloat(weight)) {
                   3083: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3084: 			       ") greater than the weight of the part. Accept?");
                   3085: 	    if (resp == false) {
                   3086: 		textbox.value = "";
                   3087: 		return;
                   3088: 	    }
                   3089: 	}
1.42      ng       3090: 	selval[0].selected = true;
                   3091:     }
                   3092: 
                   3093:     function changeOneScore(partid,user) {
1.125     ng       3094: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3095: 	if (selval[1].selected || selval[2].selected) {
                   3096: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3097: 	    if (selval[2].selected) {
                   3098: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3099: 	    }
1.269     raeburn  3100:         }
1.42      ng       3101:     }
                   3102: 
                   3103:     function resetEntry(numpart) {
                   3104: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3105: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3106: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3107: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3108: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3109: 	    for (var i=0; i<radioButton.length; i++) {
                   3110: 		radioButton[i].checked=false;
                   3111: 
                   3112: 	    }
                   3113: 	    textbox.value = "";
                   3114: 	    selval[0].selected = true;
                   3115: 
                   3116: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3117: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3118: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3119: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3120: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3121: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3122: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3123: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3124: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3125: 		if (saveselval == "excused") {
1.43      ng       3126: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3127: 		} else {
1.43      ng       3128: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3129: 		}
                   3130: 	    }
1.41      ng       3131: 	}
1.42      ng       3132:     }
                   3133: 
1.41      ng       3134: </script>
                   3135: VIEWJAVASCRIPT
1.42      ng       3136: }
                   3137: 
1.44      ng       3138: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3139: sub viewgrades {
                   3140:     my ($request) = shift;
                   3141:     &viewgrades_js($request);
1.41      ng       3142: 
1.324     albertel 3143:     my ($symb) = &get_symb($request);
1.168     albertel 3144:     #need to make sure we have the correct data for later EXT calls, 
                   3145:     #thus invalidate the cache
                   3146:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3147:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3148:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3149:     &Apache::lonnet::clear_EXT_cache_status();
                   3150: 
1.398     albertel 3151:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3152:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3153: 
                   3154:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3155:     $result.=&jscriptNform($symb);
1.41      ng       3156: 
1.44      ng       3157:     #beginning of class grading form
1.442     banghart 3158:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3159:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3160: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3161: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3162: 	&build_section_inputs().
1.257     albertel 3163: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3164: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3165: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3166: 
1.126     ng       3167:     my $sectionClass;
1.430     banghart 3168:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3169:     if ($env{'form.section'} eq 'all') {
1.126     ng       3170: 	$sectionClass='Class </h3>';
1.257     albertel 3171:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3172: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3173:     } else {
1.431     banghart 3174: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3175:     }
1.431     banghart 3176:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.474     albertel 3177:     $result.= &Apache::loncommon::start_data_table();
1.44      ng       3178:     #radio buttons/text box for assigning points for a section or class.
                   3179:     #handles different parts of a problem
1.375     albertel 3180:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3181:     my %weight = ();
                   3182:     my $ctsparts = 0;
1.45      ng       3183:     my %seen = ();
1.375     albertel 3184:     my @part_response_id = &flatten_responseType($responseType);
                   3185:     foreach my $part_response_id (@part_response_id) {
                   3186:     	my ($partid,$respid) = @{ $part_response_id };
                   3187: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3188: 	next if $seen{$partid};
                   3189: 	$seen{$partid}++;
1.375     albertel 3190: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3191: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3192: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3193: 
1.474     albertel 3194: 	$result.=&Apache::loncommon::start_data_table_row().'<td>';
1.44      ng       3195: 	$result.='<input type="hidden" name="partid_'.
                   3196: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3197: 	$result.='<input type="hidden" name="weight_'.
                   3198: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3199: 	my $display_part=&get_display_part($partid,$symb);
1.474     albertel 3200: 	$result.=
                   3201: 	    '<b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3202: 	$result.='<table border="0"><tr>';  
1.41      ng       3203: 	my $ctr = 0;
1.42      ng       3204: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3205: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3206: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3207: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3208: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3209: 	    $ctr++;
                   3210: 	}
                   3211: 	$result.='</tr></table>';
1.44      ng       3212: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3213: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3214: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3215: 	    $weight{$partid}.' (problem weight)</td>'."\n";
1.474     albertel 3216: 	$result.= '<td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3217: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3218: 		$weight{$partid}.')"> '.
1.401     albertel 3219: 	    '<option selected="selected"> </option>'.
1.125     ng       3220: 	    '<option>excused</option>'.
1.265     www      3221: 	    '<option>reset status</option></select></td>'.
1.474     albertel 3222:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td>'.&Apache::loncommon::end_data_table_row()."\n";
1.42      ng       3223: 	$ctsparts++;
1.41      ng       3224:     }
1.474     albertel 3225:     $result.=&Apache::loncommon::end_data_table()."\n".
1.52      albertel 3226: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3227:     $result.='<input type="button" value="Revert to Default" '.
1.474     albertel 3228: 	'onClick="javascript:resetEntry('.$ctsparts.');" />';
1.41      ng       3229: 
1.44      ng       3230:     #table listing all the students in a section/class
                   3231:     #header of table
1.126     ng       3232:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.474     albertel 3233:     $result.= &Apache::loncommon::start_data_table().
                   3234: 	&Apache::loncommon::start_data_table_header_row().
                   3235: 	'<th>No.</th>'.
                   3236: 	'<th>'.&nameUserString('header')."</th>\n";
1.324     albertel 3237:     my (@parts) = sort(&getpartlist($symb));
                   3238:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3239:     my @partids = ();
1.41      ng       3240:     foreach my $part (@parts) {
                   3241: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3242: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3243: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3244: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3245:         push(@partids, $partid);
1.324     albertel 3246: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3247: 	if ($display =~ /^Partial Credit Factor/) {
1.474     albertel 3248: 	    $result.='<th>Score Part: '.$display_part.
                   3249: 		' <br />(weight = '.$weight{$partid}.')</th>'."\n";
1.41      ng       3250: 	    next;
1.207     albertel 3251: 	} else {
                   3252: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3253: 	}
1.53      albertel 3254: 	$display =~ s|Problem Status|Grade Status<br />|;
1.474     albertel 3255: 	$result.='<th>'.$display.'</th>'."\n";
1.41      ng       3256:     }
1.474     albertel 3257:     $result.=&Apache::loncommon::end_data_table_header_row();
1.44      ng       3258: 
1.270     albertel 3259:     my %last_resets = 
                   3260: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3261: 
1.41      ng       3262:     #get info for each student
1.44      ng       3263:     #list all the students - with points and grade status
1.257     albertel 3264:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3265:     my $ctr = 0;
1.294     albertel 3266:     foreach (sort 
                   3267: 	     {
                   3268: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3269: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3270: 		 }
                   3271: 		 return $a cmp $b;
                   3272: 	     } (keys(%$fullname))) {
1.126     ng       3273: 	$ctr++;
1.324     albertel 3274: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3275: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3276:     }
1.474     albertel 3277:     $result.=&Apache::loncommon::end_data_table();
1.41      ng       3278:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3279:     $result.='<input type="button" value="Save" '.
1.417     albertel 3280: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3281:     if (scalar(%$fullname) eq 0) {
                   3282: 	my $colspan=3+scalar(@parts);
1.433     banghart 3283: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3284:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3285: 	$result='<span class="LC_warning">'.
                   3286: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3287: 	        $section_display, $stu_status).
1.433     banghart 3288: 	    '</span>';
1.96      albertel 3289:     }
1.324     albertel 3290:     $result.=&show_grading_menu_form($symb);
1.41      ng       3291:     return $result;
                   3292: }
                   3293: 
1.44      ng       3294: #--- call by previous routine to display each student
1.41      ng       3295: sub viewstudentgrade {
1.324     albertel 3296:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3297:     my ($uname,$udom) = split(/:/,$student);
                   3298:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3299:     my %aggregates = (); 
1.474     albertel 3300:     my $result=&Apache::loncommon::start_data_table_row().'<td align="right">'.
1.233     albertel 3301: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3302: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3303: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3304: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3305: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3306:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3307:     foreach my $apart (@$parts) {
                   3308: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3309: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3310:         $result.='<td align="center">';
1.269     raeburn  3311:         my ($aggtries,$totaltries);
                   3312:         unless (exists($aggregates{$part})) {
1.270     albertel 3313: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3314: 
                   3315: 	    $aggtries = $totaltries;
1.269     raeburn  3316:             if ($$last_resets{$part}) {  
1.270     albertel 3317:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3318: 					   $part);
                   3319:             }
1.269     raeburn  3320:             $result.='<input type="hidden" name="'.
                   3321:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3322:             $result.='<input type="hidden" name="'.
                   3323:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3324:             $aggregates{$part} = 1;
                   3325:         }
1.41      ng       3326: 	if ($type eq 'awarded') {
1.320     albertel 3327: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3328: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3329: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3330: 	    $result.='<input type="text" name="'.
1.89      albertel 3331: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3332: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3333: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3334: 	} elsif ($type eq 'solved') {
                   3335: 	    my ($status,$foo)=split(/_/,$score,2);
                   3336: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3337: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3338: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3339: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3340: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3341: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3342: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3343: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3344: 	    $result.='<option>reset status</option>';
1.126     ng       3345: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3346: 	} else {
                   3347: 	    $result.='<input type="hidden" name="'.
                   3348: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3349: 		    "\n";
1.233     albertel 3350: 	    $result.='<input type="text" name="'.
1.122     ng       3351: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3352: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3353: 	}
                   3354:     }
1.474     albertel 3355:     $result.=&Apache::loncommon::end_data_table_row();
1.41      ng       3356:     return $result;
1.38      ng       3357: }
                   3358: 
1.44      ng       3359: #--- change scores for all the students in a section/class
                   3360: #    record does not get update if unchanged
1.38      ng       3361: sub editgrades {
1.41      ng       3362:     my ($request) = @_;
                   3363: 
1.324     albertel 3364:     my $symb=&get_symb($request);
1.433     banghart 3365:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.477     albertel 3366:     my $title='<h2>'.&mt('Current Grade Status').'</h2>';
                   3367:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4>'."\n";
1.433     banghart 3368:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3369: 
1.477     albertel 3370:     my $result= &Apache::loncommon::start_data_table().
                   3371: 	&Apache::loncommon::start_data_table_header_row().
                   3372: 	'<th rowspan="2" valign="middle">'.&mt('No.').'</th>'.
                   3373: 	'<th rowspan="2" valign="middle">'.&nameUserString('header')."</th>\n";
1.43      ng       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) {
1.478     albertel 3398: 	$header .= '<th align="center">'.&mt('Old Score').'</th>'.
                   3399: 	    '<th align="center">'.&mt('New Score').'</th>';
1.54      albertel 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/;
1.478     albertel 3408: 	    $header .= '<th align="center">'.&mt('Old '.$display).'</th>'.
                   3409: 		'<th align="center">'.&mt('New '.$display).'</th>';
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.478     albertel 3415: 	$result .= '<th colspan="'.$columns{$partid}.'" align="center">'.
                   3416: 	    &mt('Part: [_1] (Weight = [_2])',$display_part,$weight{$partid}).
                   3417: 	    '</th>';
1.54      albertel 3418: 
1.44      ng       3419:     }
1.477     albertel 3420:     $result .= &Apache::loncommon::end_data_table_header_row().
                   3421: 	&Apache::loncommon::start_data_table_header_row().
                   3422: 	$header.
                   3423: 	&Apache::loncommon::end_data_table_header_row();
                   3424:     my @noupdate;
1.126     ng       3425:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3426:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3427: 	my $line;
1.257     albertel 3428: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3429: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3430: 	my %newrecord;
                   3431: 	my $updateflag = 0;
1.281     albertel 3432: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3433: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3434: 	if (!&canmodify($usec)) {
1.126     ng       3435: 	    my $numcols=scalar(@partid)*4+2;
1.477     albertel 3436: 	    push(@noupdate,
1.478     albertel 3437: 		 $line."<td colspan=\"$numcols\"><span class=\"LC_warning\">".
                   3438: 		 &mt('Not allowed to modify student')."</span></td></tr>");
1.105     albertel 3439: 	    next;
                   3440: 	}
1.269     raeburn  3441:         my %aggregate = ();
                   3442:         my $aggregateflag = 0;
1.281     albertel 3443: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3444: 	foreach (@partid) {
1.257     albertel 3445: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3446: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3447: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3448: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3449: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3450: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3451: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3452: 	    my $score;
                   3453: 	    if ($partial eq '') {
1.257     albertel 3454: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3455: 	    } elsif ($partial > 0) {
                   3456: 		$score = 'correct_by_override';
                   3457: 	    } elsif ($partial == 0) {
                   3458: 		$score = 'incorrect_by_override';
                   3459: 	    }
1.257     albertel 3460: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3461: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3462: 
1.292     albertel 3463: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3464: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3465: 	    if ($dropMenu eq 'reset status' &&
                   3466: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3467: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3468: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3469: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3470: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3471: 		$updateflag = 1;
1.269     raeburn  3472:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3473:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3474:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3475:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3476:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3477:                     $aggregateflag = 1;
                   3478:                 }
1.139     albertel 3479: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3480: 		$updateflag = 1;
                   3481: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3482: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3483: 		$rec_update++;
1.125     ng       3484: 	    }
                   3485: 
1.93      albertel 3486: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3487: 		'<td align="center">'.$awarded.
                   3488: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3489: 
1.54      albertel 3490: 
                   3491: 	    my $partid=$_;
                   3492: 	    foreach my $stores (@parts) {
                   3493: 		my ($part,$type) = &split_part_type($stores);
                   3494: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3495: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3496: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3497: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3498: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3499: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3500: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3501: 		    $updateflag=1;
                   3502: 		}
1.93      albertel 3503: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3504: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3505: 	    }
1.44      ng       3506: 	}
1.477     albertel 3507: 	$line.="\n";
1.301     albertel 3508: 
                   3509: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3510: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3511: 
1.44      ng       3512: 	if ($updateflag) {
                   3513: 	    $count++;
1.257     albertel 3514: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3515: 				    $udom,$uname);
1.301     albertel 3516: 
                   3517: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3518: 					      $cnum,$udom,$uname)) {
                   3519: 		# need to figure out if should be in queue.
                   3520: 		my %record =  
                   3521: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3522: 					     $udom,$uname);
                   3523: 		my $all_graded = 1;
                   3524: 		my $none_graded = 1;
                   3525: 		foreach my $part (@parts) {
                   3526: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3527: 			$all_graded = 0;
                   3528: 		    } else {
                   3529: 			$none_graded = 0;
                   3530: 		    }
                   3531: 		}
                   3532: 
                   3533: 		if ($all_graded || $none_graded) {
                   3534: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3535: 							   $symb,$cdom,$cnum,
                   3536: 							   $udom,$uname);
                   3537: 		}
                   3538: 	    }
                   3539: 
1.477     albertel 3540: 	    $result.=&Apache::loncommon::start_data_table_row().
                   3541: 		'<td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line.
                   3542: 		&Apache::loncommon::end_data_table_row();
1.126     ng       3543: 	    $updateCtr++;
1.93      albertel 3544: 	} else {
1.477     albertel 3545: 	    push(@noupdate,
                   3546: 		 '<td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line);
1.126     ng       3547: 	    $noupdateCtr++;
1.44      ng       3548: 	}
1.269     raeburn  3549:         if ($aggregateflag) {
                   3550:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3551: 				  $cdom,$cnum);
1.269     raeburn  3552:         }
1.93      albertel 3553:     }
1.477     albertel 3554:     if (@noupdate) {
1.126     ng       3555: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3556: 	my $numcols=scalar(@partid)*4+2;
1.477     albertel 3557: 	$result .= &Apache::loncommon::start_data_table_row('LC_empty_row').
1.478     albertel 3558: 	    '<td align="center" colspan="'.$numcols.'">'.
                   3559: 	    &mt('No Changes Occurred For the Students Below').
                   3560: 	    '</td>'.
1.477     albertel 3561: 	    &Apache::loncommon::end_data_table_row();
                   3562: 	foreach my $line (@noupdate) {
                   3563: 	    $result.=
                   3564: 		&Apache::loncommon::start_data_table_row().
                   3565: 		$line.
                   3566: 		&Apache::loncommon::end_data_table_row();
                   3567: 	}
1.44      ng       3568:     }
1.477     albertel 3569:     $result .= &Apache::loncommon::end_data_table().
                   3570: 	&show_grading_menu_form($symb);
1.478     albertel 3571:     my $msg = '<p><b>'.
                   3572: 	&mt('Number of records updated = [_1] for [quant,_2,student].',
                   3573: 	    $rec_update,$count).'</b><br />'.
                   3574: 	'<b>'.&mt('Total number of students = [_1]',$env{'form.total'}).
                   3575: 	'</b></p>';
1.44      ng       3576:     return $title.$msg.$result;
1.5       albertel 3577: }
1.54      albertel 3578: 
                   3579: sub split_part_type {
                   3580:     my ($partstr) = @_;
                   3581:     my ($temp,@allparts)=split(/_/,$partstr);
                   3582:     my $type=pop(@allparts);
1.439     albertel 3583:     my $part=join('_',@allparts);
1.54      albertel 3584:     return ($part,$type);
                   3585: }
                   3586: 
1.44      ng       3587: #------------- end of section for handling grading by section/class ---------
                   3588: #
                   3589: #----------------------------------------------------------------------------
                   3590: 
1.5       albertel 3591: 
1.44      ng       3592: #----------------------------------------------------------------------------
                   3593: #
                   3594: #-------------------------- Next few routines handles grading by csv upload
                   3595: #
                   3596: #--- Javascript to handle csv upload
1.27      albertel 3597: sub csvupload_javascript_reverse_associate {
1.246     albertel 3598:     my $error1=&mt('You need to specify the username or ID');
                   3599:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3600:   return(<<ENDPICK);
                   3601:   function verify(vf) {
                   3602:     var foundsomething=0;
                   3603:     var founduname=0;
1.243     albertel 3604:     var foundID=0;
1.27      albertel 3605:     for (i=0;i<=vf.nfields.value;i++) {
                   3606:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3607:       if (i==0 && tw!=0) { foundID=1; }
                   3608:       if (i==1 && tw!=0) { founduname=1; }
                   3609:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3610:     }
1.246     albertel 3611:     if (founduname==0 && foundID==0) {
                   3612: 	alert('$error1');
                   3613: 	return;
1.27      albertel 3614:     }
                   3615:     if (foundsomething==0) {
1.246     albertel 3616: 	alert('$error2');
                   3617: 	return;
1.27      albertel 3618:     }
                   3619:     vf.submit();
                   3620:   }
                   3621:   function flip(vf,tf) {
                   3622:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3623:     var i;
                   3624:     for (i=0;i<=vf.nfields.value;i++) {
                   3625:       //can not pick the same destination field for both name and domain
                   3626:       if (((i ==0)||(i ==1)) && 
                   3627:           ((tf==0)||(tf==1)) && 
                   3628:           (i!=tf) &&
                   3629:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3630:         eval('vf.f'+i+'.selectedIndex=0;')
                   3631:       }
                   3632:     }
                   3633:   }
                   3634: ENDPICK
                   3635: }
                   3636: 
                   3637: sub csvupload_javascript_forward_associate {
1.246     albertel 3638:     my $error1=&mt('You need to specify the username or ID');
                   3639:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3640:   return(<<ENDPICK);
                   3641:   function verify(vf) {
                   3642:     var foundsomething=0;
                   3643:     var founduname=0;
1.243     albertel 3644:     var foundID=0;
1.27      albertel 3645:     for (i=0;i<=vf.nfields.value;i++) {
                   3646:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3647:       if (tw==1) { foundID=1; }
                   3648:       if (tw==2) { founduname=1; }
                   3649:       if (tw>3) { foundsomething=1; }
1.27      albertel 3650:     }
1.246     albertel 3651:     if (founduname==0 && foundID==0) {
                   3652: 	alert('$error1');
                   3653: 	return;
1.27      albertel 3654:     }
                   3655:     if (foundsomething==0) {
1.246     albertel 3656: 	alert('$error2');
                   3657: 	return;
1.27      albertel 3658:     }
                   3659:     vf.submit();
                   3660:   }
                   3661:   function flip(vf,tf) {
                   3662:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3663:     var i;
                   3664:     //can not pick the same destination field twice
                   3665:     for (i=0;i<=vf.nfields.value;i++) {
                   3666:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3667:         eval('vf.f'+i+'.selectedIndex=0;')
                   3668:       }
                   3669:     }
                   3670:   }
                   3671: ENDPICK
                   3672: }
                   3673: 
1.26      albertel 3674: sub csvuploadmap_header {
1.324     albertel 3675:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3676:     my $javascript;
1.257     albertel 3677:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3678: 	$javascript=&csvupload_javascript_reverse_associate();
                   3679:     } else {
                   3680: 	$javascript=&csvupload_javascript_forward_associate();
                   3681:     }
1.45      ng       3682: 
1.324     albertel 3683:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3684:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3685:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3686:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3687:     $request->print(<<ENDPICK);
1.26      albertel 3688: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3689: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3690: $result
1.326     albertel 3691: <hr />
1.26      albertel 3692: <h3>Identify fields</h3>
                   3693: Total number of records found in file: $distotal <hr />
                   3694: Enter as many fields as you can. The system will inform you and bring you back
                   3695: to this page if the data selected is insufficient to run your class.<hr />
                   3696: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3697: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3698: <input type="hidden" name="associate"  value="" />
                   3699: <input type="hidden" name="phase"      value="three" />
                   3700: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3701: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3702: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3703: <input type="hidden" name="upfile_associate" 
1.257     albertel 3704:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3705: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3706: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3707: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3708: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3709: <hr />
                   3710: <script type="text/javascript" language="Javascript">
                   3711: $javascript
                   3712: </script>
                   3713: ENDPICK
1.118     ng       3714:     return '';
1.26      albertel 3715: 
                   3716: }
                   3717: 
                   3718: sub csvupload_fields {
1.324     albertel 3719:     my ($symb) = @_;
                   3720:     my (@parts) = &getpartlist($symb);
1.243     albertel 3721:     my @fields=(['ID','Student ID'],
                   3722: 		['username','Student Username'],
                   3723: 		['domain','Student Domain']);
1.324     albertel 3724:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3725:     foreach my $part (sort(@parts)) {
                   3726: 	my @datum;
                   3727: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3728: 	my $name=$part;
                   3729: 	if  (!$display) { $display = $name; }
                   3730: 	@datum=($name,$display);
1.244     albertel 3731: 	if ($name=~/^stores_(.*)_awarded/) {
                   3732: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3733: 	}
1.41      ng       3734: 	push(@fields,\@datum);
                   3735:     }
                   3736:     return (@fields);
1.26      albertel 3737: }
                   3738: 
                   3739: sub csvuploadmap_footer {
1.41      ng       3740:     my ($request,$i,$keyfields) =@_;
                   3741:     $request->print(<<ENDPICK);
1.26      albertel 3742: </table>
                   3743: <input type="hidden" name="nfields" value="$i" />
                   3744: <input type="hidden" name="keyfields" value="$keyfields" />
                   3745: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3746: </form>
                   3747: ENDPICK
                   3748: }
                   3749: 
1.283     albertel 3750: sub checkforfile_js {
1.86      ng       3751:     my $result =<<CSVFORMJS;
                   3752: <script type="text/javascript" language="javascript">
                   3753:     function checkUpload(formname) {
                   3754: 	if (formname.upfile.value == "") {
                   3755: 	    alert("Please use the browse button to select a file from your local directory.");
                   3756: 	    return false;
                   3757: 	}
                   3758: 	formname.submit();
                   3759:     }
                   3760:     </script>
                   3761: CSVFORMJS
1.283     albertel 3762:     return $result;
                   3763: }
                   3764: 
                   3765: sub upcsvScores_form {
                   3766:     my ($request) = shift;
1.324     albertel 3767:     my ($symb)=&get_symb($request);
1.283     albertel 3768:     if (!$symb) {return '';}
                   3769:     my $result=&checkforfile_js();
1.257     albertel 3770:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3771:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3772:     $result.=$table;
1.326     albertel 3773:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3774:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3775:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3776: 	'.</b></td></tr>'."\n";
                   3777:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3778:     my $upload=&mt("Upload Scores");
1.86      ng       3779:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3780:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3781:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3782:     $result.=<<ENDUPFORM;
1.106     albertel 3783: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3784: <input type="hidden" name="symb" value="$symb" />
                   3785: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3786: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3787: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3788: $upfile_select
1.370     www      3789: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3790: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3791: </form>
                   3792: ENDUPFORM
1.370     www      3793:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3794:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3795:     .'</td></tr></table>'."\n";
1.86      ng       3796:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3797:     $result.=&show_grading_menu_form($symb);
1.86      ng       3798:     return $result;
                   3799: }
                   3800: 
                   3801: 
1.26      albertel 3802: sub csvuploadmap {
1.41      ng       3803:     my ($request)= @_;
1.324     albertel 3804:     my ($symb)=&get_symb($request);
1.41      ng       3805:     if (!$symb) {return '';}
1.72      ng       3806: 
1.41      ng       3807:     my $datatoken;
1.257     albertel 3808:     if (!$env{'form.datatoken'}) {
1.41      ng       3809: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3810:     } else {
1.257     albertel 3811: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3812: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3813:     }
1.41      ng       3814:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3815:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3816:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3817:     my ($i,$keyfields);
                   3818:     if (@records) {
1.324     albertel 3819: 	my @fields=&csvupload_fields($symb);
1.45      ng       3820: 
1.257     albertel 3821: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3822: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3823: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3824: 							  \@fields);
                   3825: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3826: 	    chop($keyfields);
                   3827: 	} else {
                   3828: 	    unshift(@fields,['none','']);
                   3829: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3830: 							    \@fields);
1.311     banghart 3831:             foreach my $rec (@records) {
                   3832:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3833:                 if (%temp) {
                   3834:                     $keyfields=join(',',sort(keys(%temp)));
                   3835:                     last;
                   3836:                 }
                   3837:             }
1.41      ng       3838: 	}
                   3839:     }
                   3840:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3841:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3842: 
1.41      ng       3843:     return '';
1.27      albertel 3844: }
                   3845: 
1.246     albertel 3846: sub csvuploadoptions {
1.41      ng       3847:     my ($request)= @_;
1.324     albertel 3848:     my ($symb)=&get_symb($request);
1.257     albertel 3849:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3850:     my $ignore=&mt('Ignore First Line');
                   3851:     $request->print(<<ENDPICK);
                   3852: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3853: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3854: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3855: <!--
1.246     albertel 3856: <p>
                   3857: <label>
                   3858:    <input type="checkbox" name="show_full_results" />
                   3859:    Show a table of all changes
                   3860: </label>
                   3861: </p>
1.302     albertel 3862: -->
1.246     albertel 3863: <p>
                   3864: <label>
                   3865:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3866:    Overwrite any existing score
                   3867: </label>
                   3868: </p>
                   3869: ENDPICK
                   3870:     my %fields=&get_fields();
                   3871:     if (!defined($fields{'domain'})) {
1.257     albertel 3872: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3873: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3874:     }
1.257     albertel 3875:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3876: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3877: 	my $cleankey=$1;
                   3878: 	if ($cleankey eq 'command') { next; }
                   3879: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3880: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3881:     }
                   3882:     # FIXME do a check for any duplicated user ids...
                   3883:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3884:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3885: <hr /></form>'."\n");
1.324     albertel 3886:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3887:     return '';
                   3888: }
                   3889: 
                   3890: sub get_fields {
                   3891:     my %fields;
1.257     albertel 3892:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3893:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3894: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3895: 	    if ($env{'form.f'.$i} ne 'none') {
                   3896: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3897: 	    }
                   3898: 	} else {
1.257     albertel 3899: 	    if ($env{'form.f'.$i} ne 'none') {
                   3900: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3901: 	    }
                   3902: 	}
1.27      albertel 3903:     }
1.246     albertel 3904:     return %fields;
                   3905: }
                   3906: 
                   3907: sub csvuploadassign {
                   3908:     my ($request)= @_;
1.324     albertel 3909:     my ($symb)=&get_symb($request);
1.246     albertel 3910:     if (!$symb) {return '';}
1.345     bowersj2 3911:     my $error_msg = '';
1.246     albertel 3912:     &Apache::loncommon::load_tmp_file($request);
                   3913:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3914:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3915:     my %fields=&get_fields();
1.41      ng       3916:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3917:     my $courseid=$env{'request.course.id'};
1.97      albertel 3918:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3919:     my @notallowed;
1.41      ng       3920:     my @skipped;
                   3921:     my $countdone=0;
                   3922:     foreach my $grade (@gradedata) {
                   3923: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3924: 	my $domain;
                   3925: 	if ($entries{$fields{'domain'}}) {
                   3926: 	    $domain=$entries{$fields{'domain'}};
                   3927: 	} else {
1.257     albertel 3928: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3929: 	}
1.243     albertel 3930: 	$domain=~s/\s//g;
1.41      ng       3931: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3932: 	$username=~s/\s//g;
1.243     albertel 3933: 	if (!$username) {
                   3934: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3935: 	    $id=~s/\s//g;
1.243     albertel 3936: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3937: 	    $username=$ids{$id};
                   3938: 	}
1.41      ng       3939: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3940: 	    my $id=$entries{$fields{'ID'}};
                   3941: 	    $id=~s/\s//g;
                   3942: 	    if ($id) {
                   3943: 		push(@skipped,"$id:$domain");
                   3944: 	    } else {
                   3945: 		push(@skipped,"$username:$domain");
                   3946: 	    }
1.41      ng       3947: 	    next;
                   3948: 	}
1.108     albertel 3949: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3950: 	if (!&canmodify($usec)) {
                   3951: 	    push(@notallowed,"$username:$domain");
                   3952: 	    next;
                   3953: 	}
1.244     albertel 3954: 	my %points;
1.41      ng       3955: 	my %grades;
                   3956: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3957: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3958: 		$dest eq 'domain') { next; }
                   3959: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3960: 	    if ($dest=~/stores_(.*)_points/) {
                   3961: 		my $part=$1;
                   3962: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3963: 					      $symb,$domain,$username);
1.345     bowersj2 3964:                 if ($wgt) {
                   3965:                     $entries{$fields{$dest}}=~s/\s//g;
                   3966:                     my $pcr=$entries{$fields{$dest}} / $wgt;
1.463     albertel 3967:                     my $award=($pcr == 0) ? 'incorrect_by_override'
                   3968:                                           : 'correct_by_override';
1.345     bowersj2 3969:                     $grades{"resource.$part.awarded"}=$pcr;
                   3970:                     $grades{"resource.$part.solved"}=$award;
                   3971:                     $points{$part}=1;
                   3972:                 } else {
                   3973:                     $error_msg = "<br />" .
                   3974:                         &mt("Some point values were assigned"
                   3975:                             ." for problems with a weight "
                   3976:                             ."of zero. These values were "
                   3977:                             ."ignored.");
                   3978:                 }
1.244     albertel 3979: 	    } else {
                   3980: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3981: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3982: 		my $store_key=$dest;
                   3983: 		$store_key=~s/^stores/resource/;
                   3984: 		$store_key=~s/_/\./g;
                   3985: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3986: 	    }
1.41      ng       3987: 	}
1.398     albertel 3988: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3989: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3990: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3991: 					   $env{'request.course.id'},
                   3992: 					   $domain,$username);
                   3993: 	if ($result eq 'ok') {
                   3994: 	    $request->print('.');
                   3995: 	} else {
                   3996: 	    $request->print("<p>
1.398     albertel 3997:                               <span class=\"LC_error\">
                   3998:                                  Failed to save student $username:$domain.
                   3999:                                  Message when trying to save was ($result)
                   4000:                               </span>
1.302     albertel 4001:                              </p>" );
                   4002: 	}
1.41      ng       4003: 	$request->rflush();
                   4004: 	$countdone++;
                   4005:     }
1.398     albertel 4006:     $request->print("<br />Saved $countdone students\n");
1.41      ng       4007:     if (@skipped) {
1.398     albertel 4008: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 4009: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   4010:     }
                   4011:     if (@notallowed) {
1.398     albertel 4012: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 4013: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       4014:     }
1.106     albertel 4015:     $request->print("<br />\n");
1.324     albertel 4016:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 4017:     return $error_msg;
1.26      albertel 4018: }
1.44      ng       4019: #------------- end of section for handling csv file upload ---------
                   4020: #
                   4021: #-------------------------------------------------------------------
                   4022: #
1.122     ng       4023: #-------------- Next few routines handle grading by page/sequence
1.72      ng       4024: #
                   4025: #--- Select a page/sequence and a student to grade
1.68      ng       4026: sub pickStudentPage {
                   4027:     my ($request) = shift;
                   4028: 
                   4029:     $request->print(<<LISTJAVASCRIPT);
                   4030: <script type="text/javascript" language="javascript">
                   4031: 
                   4032: function checkPickOne(formname) {
1.76      ng       4033:     if (radioSelection(formname.student) == null) {
1.68      ng       4034: 	alert("Please select the student you wish to grade.");
                   4035: 	return;
                   4036:     }
1.125     ng       4037:     ptr = pullDownSelection(formname.selectpage);
                   4038:     formname.page.value = formname["page"+ptr].value;
                   4039:     formname.title.value = formname["title"+ptr].value;
1.68      ng       4040:     formname.submit();
                   4041: }
                   4042: 
                   4043: </script>
                   4044: LISTJAVASCRIPT
1.118     ng       4045:     &commonJSfunctions($request);
1.324     albertel 4046:     my ($symb) = &get_symb($request);
1.257     albertel 4047:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4048:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4049:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       4050: 
1.398     albertel 4051:     my $result='<h3><span class="LC_info">&nbsp;'.
                   4052: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       4053: 
1.80      ng       4054:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       4055:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 4056:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4057:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4058: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4059: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4060:     my $ctr=0;
1.68      ng       4061:     foreach (@$titles) {
                   4062: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4063: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4064: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4065: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4066: 	$ctr++;
1.68      ng       4067:     }
1.326     albertel 4068:     $result.= '</select>'."<br />\n";
1.70      ng       4069:     $ctr=0;
                   4070:     foreach (@$titles) {
                   4071: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4072: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4073: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4074: 	$ctr++;
                   4075:     }
1.72      ng       4076:     $result.='<input type="hidden" name="page" />'."\n".
                   4077: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4078: 
1.401     albertel 4079:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4080: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4081: 
1.71      ng       4082:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4083: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4084: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4085: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4086:     
                   4087:     $result.=&build_section_inputs();
1.442     banghart 4088:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4089:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4090: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4091: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4092: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4093: 
1.382     albertel 4094:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4095: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4096: 
1.80      ng       4097:     $result.='&nbsp;<input type="button" '.
1.126     ng       4098: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4099: 
1.68      ng       4100:     $request->print($result);
                   4101: 
1.326     albertel 4102:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4103: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4104: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4105: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4106: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4107: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4108: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4109:  
1.76      ng       4110:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4111:     my $ptr = 1;
1.294     albertel 4112:     foreach my $student (sort 
                   4113: 			 {
                   4114: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4115: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4116: 			     }
                   4117: 			     return $a cmp $b;
                   4118: 			 } (keys(%$fullname))) {
1.68      ng       4119: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4120: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4121: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4122: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4123: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4124: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4125: 	$ptr++;
                   4126:     }
1.381     albertel 4127:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4128:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4129:     $studentTable.='<input type="button" '.
                   4130: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4131: 
1.324     albertel 4132:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4133:     $request->print($studentTable);
                   4134: 
                   4135:     return '';
                   4136: }
                   4137: 
                   4138: sub getSymbMap {
1.132     bowersj2 4139:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4140: 
                   4141:     my %symbx = ();
                   4142:     my @titles = ();
1.117     bowersj2 4143:     my $minder = 0;
                   4144: 
                   4145:     # Gather every sequence that has problems.
1.240     albertel 4146:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4147: 					       1,0,1);
1.117     bowersj2 4148:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4149: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4150: 	    my $title = $minder.'.'.
                   4151: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4152: 	    push(@titles, $title); # minder in case two titles are identical
                   4153: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4154: 	    $minder++;
1.241     albertel 4155: 	}
1.68      ng       4156:     }
                   4157:     return \@titles,\%symbx;
                   4158: }
                   4159: 
1.72      ng       4160: #
                   4161: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4162: sub displayPage {
                   4163:     my ($request) = shift;
                   4164: 
1.324     albertel 4165:     my ($symb) = &get_symb($request);
1.257     albertel 4166:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4167:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4168:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4169:     my $pageTitle = $env{'form.page'};
1.103     albertel 4170:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4171:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4172:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4173: 
                   4174:     #need to make sure we have the correct data for later EXT calls, 
                   4175:     #thus invalidate the cache
                   4176:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4177:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4178:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4179:     &Apache::lonnet::clear_EXT_cache_status();
                   4180: 
1.103     albertel 4181:     if (!&canview($usec)) {
1.398     albertel 4182: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4183: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4184: 	return;
                   4185:     }
1.398     albertel 4186:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4187:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4188: 	'</h3>'."\n";
1.382     albertel 4189:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4190: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4191:     } else {
                   4192: 	delete($env{'form.CODE'});
                   4193:     }
1.71      ng       4194:     &sub_page_js($request);
                   4195:     $request->print($result);
                   4196: 
1.132     bowersj2 4197:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4198:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4199:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4200:     if (!$map) {
1.398     albertel 4201: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4202: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4203: 	return; 
                   4204:     }
1.68      ng       4205:     my $iterator = $navmap->getIterator($map->map_start(),
                   4206: 					$map->map_finish());
                   4207: 
1.71      ng       4208:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4209: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4210: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4211: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4212: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4213: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4214: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4215: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4216: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4217: 
1.382     albertel 4218:     if (defined($env{'form.CODE'})) {
                   4219: 	$studentTable.=
                   4220: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4221:     }
1.381     albertel 4222:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4223: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4224: 	'/check.gif" height="16" border="0" />';
                   4225: 
1.118     ng       4226:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4227: 	' symbol.'."\n".
1.71      ng       4228: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4229: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4230: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4231: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4232: 
1.329     albertel 4233:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4234:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4235:     $iterator->next(); # skip the first BEGIN_MAP
                   4236:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4237:     while ($depth > 0) {
1.68      ng       4238:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4239:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4240: 
1.385     albertel 4241:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4242: 	    my $parts = $curRes->parts();
1.68      ng       4243:             my $title = $curRes->compTitle();
1.71      ng       4244: 	    my $symbx = $curRes->symb();
1.196     albertel 4245: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4246: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4247: 	    $studentTable.='<td valign="top">';
1.382     albertel 4248: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4249: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4250: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4251: 					     undef,'both',\%form);
1.71      ng       4252: 	    } else {
1.382     albertel 4253: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4254: 		$companswer =~ s|<form(.*?)>||g;
                   4255: 		$companswer =~ s|</form>||g;
1.71      ng       4256: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4257: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4258: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4259: #		}
1.116     ng       4260: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4261: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4262: 	    }
                   4263: 
1.257     albertel 4264: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4265: 
1.257     albertel 4266: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4267: 		if ($record{'version'} eq '') {
1.398     albertel 4268: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4269: 		} else {
1.116     ng       4270: 		    my %responseType = ();
                   4271: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4272: 			my @responseIds =$curRes->responseIds($partid);
                   4273: 			my @responseType =$curRes->responseType($partid);
                   4274: 			my %responseIds;
                   4275: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4276: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4277: 			}
                   4278: 			$responseType{$partid} = \%responseIds;
1.116     ng       4279: 		    }
1.148     albertel 4280: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4281: 
1.71      ng       4282: 		}
1.257     albertel 4283: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4284: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4285: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4286: 									$env{'request.course.id'},
1.71      ng       4287: 									'','.submission');
                   4288:  
                   4289: 	    }
1.103     albertel 4290: 	    if (&canmodify($usec)) {
                   4291: 		foreach my $partid (@{$parts}) {
                   4292: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4293: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4294: 		    $question++;
                   4295: 		}
1.196     albertel 4296: 		$prob++;
1.71      ng       4297: 	    }
                   4298: 	    $studentTable.='</td></tr>';
1.68      ng       4299: 
1.103     albertel 4300: 	}
1.68      ng       4301:         $curRes = $iterator->next();
                   4302:     }
                   4303: 
1.381     albertel 4304:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4305: 	'<input type="button" value="Save" '.
1.381     albertel 4306: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4307: 	'</form>'."\n";
1.324     albertel 4308:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4309:     $request->print($studentTable);
                   4310: 
                   4311:     return '';
1.119     ng       4312: }
                   4313: 
                   4314: sub displaySubByDates {
1.148     albertel 4315:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4316:     my $isCODE=0;
1.335     albertel 4317:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4318:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.467     albertel 4319:     my $studentTable=&Apache::loncommon::start_data_table().
                   4320: 	&Apache::loncommon::start_data_table_header_row().
                   4321: 	'<th>'.&mt('Date/Time').'</th>'.
                   4322: 	($isCODE?'<th>'.&mt('CODE').'</th>':'').
                   4323: 	'<th>'.&mt('Submission').'</th>'.
                   4324: 	'<th>'.&mt('Status').'</th>'.
                   4325: 	&Apache::loncommon::end_data_table_header_row();
1.119     ng       4326:     my ($version);
                   4327:     my %mark;
1.148     albertel 4328:     my %orders;
1.119     ng       4329:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4330:     if (!exists($$record{'1:timestamp'})) {
1.467     albertel 4331: 	return '<br />&nbsp;<span class="LC_warning">'.&mt('Nothing submitted - no attempts').'</span><br />';
1.147     albertel 4332:     }
1.335     albertel 4333: 
                   4334:     my $interaction;
1.119     ng       4335:     for ($version=1;$version<=$$record{'version'};$version++) {
1.467     albertel 4336: 	my $timestamp = 
                   4337: 	    &Apache::lonlocal::locallocaltime($$record{$version.':timestamp'});
1.335     albertel 4338: 	if (exists($$record{$version.':resource.0.version'})) {
                   4339: 	    $interaction = $$record{$version.':resource.0.version'};
                   4340: 	}
                   4341: 
                   4342: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4343: 		             : "$version:resource");
1.467     albertel 4344: 	$studentTable.=&Apache::loncommon::start_data_table_row().
                   4345: 	    '<td>'.$timestamp.'</td>';
1.224     albertel 4346: 	if ($isCODE) {
                   4347: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4348: 	}
1.119     ng       4349: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4350: 	my @displaySub = ();
                   4351: 	foreach my $partid (@{$parts}) {
1.335     albertel 4352: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4353: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4354: 	    
                   4355: 
1.122     ng       4356: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4357: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4358: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4359: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4360: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4361: 
                   4362: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4363: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.467     albertel 4364: 		    $displaySub[0].='<b>'.&mt('Part:').'</b>&nbsp;'.$display_part.'&nbsp;';
                   4365: 		    $displaySub[0].='<span class="LC_internal_info">('.&mt('ID').'&nbsp;'.
1.398     albertel 4366: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4367: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.467     albertel 4368: 			$displaySub[0].=&mt('Trial&nbsp;not&nbsp;counted');
1.147     albertel 4369: 		    } else {
1.467     albertel 4370: 			$displaySub[0].=&mt('Trial&nbsp;[_1]',
                   4371: 					    $$record{"$where.$partid.tries"});
1.147     albertel 4372: 		    }
1.335     albertel 4373: 		    my $responseType=($isTask ? 'Task'
                   4374:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4375: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4376: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4377: 			$orders{$partid}->{$responseId}=
                   4378: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4379: 		    }
1.147     albertel 4380: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4381: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4382: 		}
                   4383: 	    }
1.335     albertel 4384: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4385: 		$displaySub[1].='Checked in by '.
                   4386: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4387: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4388: 		    '<br />';
                   4389: 	    }
                   4390: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4391: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4392: 		    lc($$record{"$where.$partid.award"}).' '.
                   4393: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4394: 		    '<br />';
                   4395: 	    }
1.335     albertel 4396: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4397: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4398: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4399: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4400: 		$displaySub[2].=
                   4401: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4402: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4403: 	    }
                   4404: 	}
                   4405: 	# needed because old essay regrader has not parts info
                   4406: 	if (exists $$record{"$version:resource.regrader"}) {
                   4407: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4408: 	}
                   4409: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4410: 	if ($displaySub[2]) {
1.467     albertel 4411: 	    $studentTable.=&mt('Manually graded by [_1]',$displaySub[2]);
1.147     albertel 4412: 	}
1.467     albertel 4413: 	$studentTable.='&nbsp;</td>'.
                   4414: 	    &Apache::loncommon::end_data_table_row();
1.119     ng       4415:     }
1.467     albertel 4416:     $studentTable.=&Apache::loncommon::end_data_table();
1.119     ng       4417:     return $studentTable;
1.71      ng       4418: }
                   4419: 
                   4420: sub updateGradeByPage {
                   4421:     my ($request) = shift;
                   4422: 
1.257     albertel 4423:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4424:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4425:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4426:     my $pageTitle = $env{'form.page'};
1.103     albertel 4427:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4428:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4429:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4430:     if (!&canmodify($usec)) {
1.398     albertel 4431: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4432: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4433: 	return;
                   4434:     }
1.398     albertel 4435:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4436:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4437: 	'</h3>'."\n";
1.70      ng       4438: 
1.68      ng       4439:     $request->print($result);
                   4440: 
1.132     bowersj2 4441:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4442:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4443:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4444:     if (!$map) {
1.398     albertel 4445: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4446: 	my ($symb)=&get_symb($request);
                   4447: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4448: 	return; 
                   4449:     }
1.71      ng       4450:     my $iterator = $navmap->getIterator($map->map_start(),
                   4451: 					$map->map_finish());
1.70      ng       4452: 
1.71      ng       4453:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4454: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4455: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4456: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4457: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4458: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4459: 
                   4460:     $iterator->next(); # skip the first BEGIN_MAP
                   4461:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4462:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4463:     while ($depth > 0) {
1.71      ng       4464:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4465:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4466: 
1.385     albertel 4467:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4468: 	    my $parts = $curRes->parts();
1.71      ng       4469:             my $title = $curRes->compTitle();
                   4470: 	    my $symbx = $curRes->symb();
1.196     albertel 4471: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4472: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4473: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4474: 
                   4475: 	    my %newrecord=();
                   4476: 	    my @displayPts=();
1.269     raeburn  4477:             my %aggregate = ();
                   4478:             my $aggregateflag = 0;
1.71      ng       4479: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4480: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4481: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4482: 
1.257     albertel 4483: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4484: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4485: 		my $partial = $newpts/$wgt;
                   4486: 		my $score;
                   4487: 		if ($partial > 0) {
                   4488: 		    $score = 'correct_by_override';
1.125     ng       4489: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4490: 		    $score = 'incorrect_by_override';
                   4491: 		}
1.257     albertel 4492: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4493: 		if ($dropMenu eq 'excused') {
1.71      ng       4494: 		    $partial = '';
                   4495: 		    $score = 'excused';
1.125     ng       4496: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4497: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4498: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4499: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4500: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4501: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4502: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4503: 		    $changeflag++;
                   4504: 		    $newpts = '';
1.269     raeburn  4505:                     
                   4506:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4507:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4508:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4509:                     if ($aggtries > 0) {
                   4510:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4511:                         $aggregateflag = 1;
                   4512:                     }
1.71      ng       4513: 		}
1.324     albertel 4514: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4515: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4516: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4517: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4518: 		    '&nbsp;<br />';
1.207     albertel 4519: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4520: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4521: 		    '&nbsp;<br />';
1.71      ng       4522: 		$question++;
1.380     albertel 4523: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4524: 
1.71      ng       4525: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4526: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4527: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4528: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4529: 
                   4530: 		$changeflag++;
                   4531: 	    }
                   4532: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4533: 		my %record = 
                   4534: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4535: 					     $udom,$uname);
                   4536: 
                   4537: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4538: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4539: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4540: 		    $newrecord{'resource.CODE'} = '';
                   4541: 		}
1.257     albertel 4542: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4543: 					$udom,$uname);
1.382     albertel 4544: 		%record = &Apache::lonnet::restore($symbx,
                   4545: 						   $env{'request.course.id'},
                   4546: 						   $udom,$uname);
1.380     albertel 4547: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4548: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4549: 	    }
1.380     albertel 4550: 	    
1.269     raeburn  4551:             if ($aggregateflag) {
                   4552:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4553:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4554:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4555:             }
1.125     ng       4556: 
1.71      ng       4557: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4558: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4559: 		'</tr>';
1.68      ng       4560: 
1.196     albertel 4561: 	    $prob++;
1.68      ng       4562: 	}
1.71      ng       4563:         $curRes = $iterator->next();
1.68      ng       4564:     }
1.98      albertel 4565: 
1.71      ng       4566:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4567:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4568:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4569: 		  'The scores were changed for '.
                   4570: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4571:     $request->print($grademsg.$studentTable);
1.68      ng       4572: 
1.70      ng       4573:     return '';
                   4574: }
                   4575: 
1.72      ng       4576: #-------- end of section for handling grading by page/sequence ---------
                   4577: #
                   4578: #-------------------------------------------------------------------
                   4579: 
1.75      albertel 4580: #--------------------Scantron Grading-----------------------------------
                   4581: #
                   4582: #------ start of section for handling grading by page/sequence ---------
                   4583: 
1.423     albertel 4584: =pod
                   4585: 
                   4586: =head1 Bubble sheet grading routines
                   4587: 
1.424     albertel 4588:   For this documentation:
                   4589: 
                   4590:    'scanline' refers to the full line of characters
                   4591:    from the file that we are parsing that represents one entire sheet
                   4592: 
                   4593:    'bubble line' refers to the data
                   4594:    representing the line of bubbles that are on the physical bubble sheet
                   4595: 
                   4596: 
                   4597: The overall process is that a scanned in bubble sheet data is uploaded
                   4598: into a course. When a user wants to grade, they select a
                   4599: sequence/folder of resources, a file of bubble sheet info, and pick
                   4600: one of the predefined configurations for what each scanline looks
                   4601: like.
                   4602: 
                   4603: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4604: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4605: because too light bubbling), 'double bubble' (each bubble line should
                   4606: have no more that one letter picked), invalid or duplicated CODE,
                   4607: invalid student ID
                   4608: 
                   4609: If the CODE option is used that determines the randomization of the
                   4610: homework problems, either way the student ID is looked up into a
                   4611: username:domain.
                   4612: 
                   4613: During the validation phase the instructor can choose to skip scanlines. 
                   4614: 
1.435     foxr     4615: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4616: 
                   4617:   scantron_original_filename (unmodified original file)
                   4618:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4619:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4620: 
                   4621: Also there is a separate hash nohist_scantrondata that contains extra
                   4622: correction information that isn't representable in the bubble sheet
                   4623: file (see &scantron_getfile() for more information)
                   4624: 
                   4625: After all scanlines are either valid, marked as valid or skipped, then
                   4626: foreach line foreach problem in the picked sequence, an ssi request is
                   4627: made that simulates a user submitting their selected letter(s) against
                   4628: the homework problem.
1.423     albertel 4629: 
                   4630: =over 4
                   4631: 
                   4632: 
                   4633: 
                   4634: =item defaultFormData
                   4635: 
                   4636:   Returns html hidden inputs used to hold context/default values.
                   4637: 
                   4638:  Arguments:
                   4639:   $symb - $symb of the current resource 
                   4640: 
                   4641: =cut
1.422     foxr     4642: 
1.81      albertel 4643: sub defaultFormData {
1.324     albertel 4644:     my ($symb)=@_;
1.447     foxr     4645:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4646:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4647:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4648: }
                   4649: 
1.447     foxr     4650: 
1.423     albertel 4651: =pod 
                   4652: 
                   4653: =item getSequenceDropDown
                   4654: 
                   4655:    Return html dropdown of possible sequences to grade
                   4656:  
                   4657:  Arguments:
                   4658:    $symb - $symb of the current resource 
                   4659: 
                   4660: =cut
1.422     foxr     4661: 
1.75      albertel 4662: sub getSequenceDropDown {
1.423     albertel 4663:     my ($symb)=@_;
1.75      albertel 4664:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4665:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4666:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4667:     my $ctr=0;
                   4668:     foreach (@$titles) {
                   4669: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4670: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4671: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4672: 	    '>'.$showtitle.'</option>'."\n";
                   4673: 	$ctr++;
                   4674:     }
                   4675:     $result.= '</select>';
                   4676:     return $result;
                   4677: }
                   4678: 
1.423     albertel 4679: 
                   4680: =pod 
                   4681: 
                   4682: =item scantron_filenames
                   4683: 
                   4684:    Returns a list of the scantron files in the current course 
                   4685: 
                   4686: =cut
1.422     foxr     4687: 
1.202     albertel 4688: sub scantron_filenames {
1.257     albertel 4689:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4690:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4691:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4692: 				    &propath($cdom,$cname));
1.202     albertel 4693:     my @possiblenames;
1.201     albertel 4694:     foreach my $filename (sort(@files)) {
1.157     albertel 4695: 	($filename)=split(/&/,$filename);
                   4696: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4697: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4698: 	push(@possiblenames,$filename);
                   4699:     }
                   4700:     return @possiblenames;
                   4701: }
                   4702: 
1.423     albertel 4703: =pod 
                   4704: 
                   4705: =item scantron_uploads
                   4706: 
                   4707:    Returns  html drop-down list of scantron files in current course.
                   4708: 
                   4709:  Arguments:
                   4710:    $file2grade - filename to set as selected in the dropdown
                   4711: 
                   4712: =cut
1.422     foxr     4713: 
1.202     albertel 4714: sub scantron_uploads {
1.209     ng       4715:     my ($file2grade) = @_;
1.202     albertel 4716:     my $result=	'<select name="scantron_selectfile">';
                   4717:     $result.="<option></option>";
                   4718:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4719: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4720:     }
                   4721:     $result.="</select>";
                   4722:     return $result;
                   4723: }
                   4724: 
1.423     albertel 4725: =pod 
                   4726: 
                   4727: =item scantron_scantab
                   4728: 
                   4729:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4730:   file.
                   4731: 
                   4732: =cut
1.422     foxr     4733: 
1.82      albertel 4734: sub scantron_scantab {
                   4735:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4736:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4737:     $result.='<option></option>'."\n";
1.82      albertel 4738:     foreach my $line (<$fh>) {
                   4739: 	my ($name,$descrip)=split(/:/,$line);
                   4740: 	if ($name =~ /^\#/) { next; }
                   4741: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4742:     }
                   4743:     $result.='</select>'."\n";
                   4744: 
                   4745:     return $result;
                   4746: }
                   4747: 
1.423     albertel 4748: =pod 
                   4749: 
                   4750: =item scantron_CODElist
                   4751: 
                   4752:   Returns html drop down of the saved CODE lists from current course,
                   4753:   generated from earlier printings.
                   4754: 
                   4755: =cut
1.422     foxr     4756: 
1.186     albertel 4757: sub scantron_CODElist {
1.257     albertel 4758:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4759:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4760:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4761:     my $namechoice='<option></option>';
1.225     albertel 4762:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4763: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4764: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4765: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4766:     }
                   4767:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4768:     return $namechoice;
                   4769: }
                   4770: 
1.423     albertel 4771: =pod 
                   4772: 
                   4773: =item scantron_CODEunique
                   4774: 
                   4775:   Returns the html for "Each CODE to be used once" radio.
                   4776: 
                   4777: =cut
1.422     foxr     4778: 
1.186     albertel 4779: sub scantron_CODEunique {
1.381     albertel 4780:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4781:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4782:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4783:                 </span>
                   4784:                 <span style="white-space: nowrap;">
1.272     albertel 4785:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4786:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4787:                 </span>';
1.186     albertel 4788:     return $result;
                   4789: }
1.423     albertel 4790: 
                   4791: =pod 
                   4792: 
                   4793: =item scantron_selectphase
                   4794: 
                   4795:   Generates the initial screen to start the bubble sheet process.
                   4796:   Allows for - starting a grading run.
1.424     albertel 4797:              - downloading existing scan data (original, corrected
1.423     albertel 4798:                                                 or skipped info)
                   4799: 
                   4800:              - uploading new scan data
                   4801: 
                   4802:  Arguments:
                   4803:   $r          - The Apache request object
                   4804:   $file2grade - name of the file that contain the scanned data to score
                   4805: 
                   4806: =cut
1.186     albertel 4807: 
1.75      albertel 4808: sub scantron_selectphase {
1.209     ng       4809:     my ($r,$file2grade) = @_;
1.324     albertel 4810:     my ($symb)=&get_symb($r);
1.75      albertel 4811:     if (!$symb) {return '';}
1.423     albertel 4812:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4813:     my $default_form_data=&defaultFormData($symb);
                   4814:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4815:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4816:     my $format_selector=&scantron_scantab();
1.186     albertel 4817:     my $CODE_selector=&scantron_CODElist();
                   4818:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4819:     my $result;
1.422     foxr     4820: 
                   4821:     # Chunk of form to prompt for a file to grade and how:
                   4822: 
1.75      albertel 4823:     $result.= <<SCANTRONFORM;
1.162     albertel 4824:     <table width="100%" border="0">
1.75      albertel 4825:     <tr>
1.226     albertel 4826:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4827:       <td bgcolor="#777777">
1.203     albertel 4828:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4829:         $default_form_data
1.75      albertel 4830:         <table width="100%" border="0">
                   4831:           <tr bgcolor="#e6ffff">
1.174     albertel 4832:             <td colspan="2">
                   4833:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4834:             </td>
                   4835:           </tr>
                   4836:           <tr bgcolor="#ffffe6">
1.174     albertel 4837:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4838:           </tr>
                   4839:           <tr bgcolor="#ffffe6">
1.174     albertel 4840:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4841:           </tr>
1.82      albertel 4842:           <tr bgcolor="#ffffe6">
1.174     albertel 4843:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4844:           </tr>
1.157     albertel 4845:           <tr bgcolor="#ffffe6">
1.186     albertel 4846:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4847:           </tr>
                   4848:           <tr bgcolor="#ffffe6">
                   4849:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4850:           </tr>
                   4851:           <tr bgcolor="#ffffe6">
1.187     albertel 4852: 	    <td> Options: </td>
                   4853:             <td>
1.272     albertel 4854: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4855:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4856:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4857: 	    </td>
                   4858:           </tr>
                   4859:           <tr bgcolor="#ffffe6">
1.174     albertel 4860:             <td colspan="2">
1.265     www      4861:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4862:             </td>
                   4863:           </tr>
                   4864:         </table>
1.226     albertel 4865:        </td>
                   4866:      </form>
1.162     albertel 4867:     </tr>
                   4868: SCANTRONFORM
                   4869:    
                   4870:     $r->print($result);
                   4871: 
1.257     albertel 4872:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4873:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4874: 
1.422     foxr     4875: 	# Chunk of form to prompt for a scantron file upload.
                   4876: 
1.162     albertel 4877:         $r->print(<<SCANTRONFORM);
                   4878:     <tr>
                   4879:       <td bgcolor="#777777">
                   4880:         <table width="100%" border="0">
                   4881:           <tr bgcolor="#e6ffff">
                   4882:             <td>
1.174     albertel 4883:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4884:             </td>
                   4885:           </tr>
                   4886:           <tr bgcolor="#ffffe6">
                   4887:             <td>
                   4888: SCANTRONFORM
1.324     albertel 4889:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4890:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4891:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4892:     $r->print(<<UPLOAD);
                   4893:               <script type="text/javascript" language="javascript">
                   4894:     function checkUpload(formname) {
                   4895: 	if (formname.upfile.value == "") {
                   4896: 	    alert("Please use the browse button to select a file from your local directory.");
                   4897: 	    return false;
                   4898: 	}
                   4899: 	formname.submit();
                   4900:     }
                   4901:               </script>
                   4902: 
                   4903:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4904:                 $default_form_data
                   4905:                 <input name='courseid' type='hidden' value='$cnum' />
                   4906:                 <input name='domainid' type='hidden' value='$cdom' />
                   4907:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4908:                 File to upload:<input type="file" name="upfile" size="50" />
                   4909:                 <br />
                   4910:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4911:               </form>
                   4912: UPLOAD
1.162     albertel 4913: 
                   4914:         $r->print(<<SCANTRONFORM);
                   4915:             </td>
                   4916:           </tr>
1.75      albertel 4917:         </table>
                   4918:       </td>
                   4919:     </tr>
1.162     albertel 4920: SCANTRONFORM
                   4921:     }
1.422     foxr     4922: 
                   4923:     # Chunk of the form that prompts to view a scoring office file,
                   4924:     # corrected file, skipped records in a file.
                   4925: 
1.187     albertel 4926:     $r->print(<<SCANTRONFORM);
                   4927:     <tr>
1.226     albertel 4928:       <form action='/adm/grades' name='scantron_download'>
                   4929:         <td bgcolor="#777777">
1.379     albertel 4930: 	  $default_form_data
1.187     albertel 4931:           <input type="hidden" name="command" value="scantron_download" />
                   4932:           <table width="100%" border="0">
                   4933:             <tr bgcolor="#e6ffff">
                   4934:               <td colspan="2">
                   4935:                 &nbsp;<b>Download a scoring office file</b>
                   4936:               </td>
                   4937:             </tr>
                   4938:             <tr bgcolor="#ffffe6">
                   4939:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4940:             </tr>
                   4941:             <tr bgcolor="#ffffe6">
                   4942:               <td colspan="2">
1.293     www      4943:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4944:               </td>
                   4945:             </tr>
                   4946:           </table>
1.226     albertel 4947:         </td>
                   4948:       </form>
1.187     albertel 4949:     </tr>
                   4950: SCANTRONFORM
1.162     albertel 4951: 
1.457     banghart 4952:     $r->print('<tr><td bgcolor="#777777">');
                   4953:     &Apache::lonpickcode::code_list($r,2);
                   4954:     $r->print('</td></tr></table>');
                   4955:     $r->print($grading_menu_button);
1.162     albertel 4956:     return
1.75      albertel 4957: }
                   4958: 
1.423     albertel 4959: =pod
                   4960: 
                   4961: =item get_scantron_config
                   4962: 
                   4963:    Parse and return the scantron configuration line selected as a
                   4964:    hash of configuration file fields.
                   4965: 
                   4966:  Arguments:
                   4967:     which - the name of the configuration to parse from the file.
                   4968: 
                   4969: 
                   4970:  Returns:
                   4971:             If the named configuration is not in the file, an empty
                   4972:             hash is returned.
                   4973:     a hash with the fields
                   4974:       name         - internal name for the this configuration setup
                   4975:       description  - text to display to operator that describes this config
                   4976:       CODElocation - if 0 or the string 'none'
                   4977:                           - no CODE exists for this config
                   4978:                      if -1 || the string 'letter'
                   4979:                           - a CODE exists for this config and is
                   4980:                             a string of letters
                   4981:                      Unsupported value (but planned for future support)
                   4982:                           if a positive integer
                   4983:                                - The CODE exists as the first n items from
                   4984:                                  the question section of the form
                   4985:                           if the string 'number'
                   4986:                                - The CODE exists for this config and is
                   4987:                                  a string of numbers
                   4988:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4989:                      the CODE starts
                   4990:       CODElength  - length of the CODE
                   4991:       IDstart     - column where the student ID number starts
                   4992:       IDlength    - length of the student ID info
                   4993:       Qstart      - column where the information from the bubbled
                   4994:                     'questions' start
                   4995:       Qlength     - number of columns comprising a single bubble line from
                   4996:                     the sheet. (usually either 1 or 10)
1.424     albertel 4997:       Qon         - either a single character representing the character used
1.423     albertel 4998:                     to signal a bubble was chosen in the positional setup, or
                   4999:                     the string 'letter' if the letter of the chosen bubble is
                   5000:                     in the final, or 'number' if a number representing the
                   5001:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 5002:       Qoff        - the character used to represent that a bubble was
                   5003:                     left blank
1.423     albertel 5004:       PaperID     - if the scanning process generates a unique number for each
                   5005:                     sheet scanned the column that this ID number starts in
                   5006:       PaperIDlength - number of columns that comprise the unique ID number
                   5007:                       for the sheet of paper
1.424     albertel 5008:       FirstName   - column that the first name starts in
1.423     albertel 5009:       FirstNameLength - number of columns that the first name spans
                   5010:  
                   5011:       LastName    - column that the last name starts in
                   5012:       LastNameLength - number of columns that the last name spans
                   5013: 
                   5014: =cut
1.422     foxr     5015: 
1.82      albertel 5016: sub get_scantron_config {
                   5017:     my ($which) = @_;
                   5018:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   5019:     my %config;
1.157     albertel 5020:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 5021:     foreach my $line (<$fh>) {
                   5022: 	my ($name,$descrip)=split(/:/,$line);
                   5023: 	if ($name ne $which ) { next; }
                   5024: 	chomp($line);
                   5025: 	my @config=split(/:/,$line);
                   5026: 	$config{'name'}=$config[0];
                   5027: 	$config{'description'}=$config[1];
                   5028: 	$config{'CODElocation'}=$config[2];
                   5029: 	$config{'CODEstart'}=$config[3];
                   5030: 	$config{'CODElength'}=$config[4];
                   5031: 	$config{'IDstart'}=$config[5];
                   5032: 	$config{'IDlength'}=$config[6];
                   5033: 	$config{'Qstart'}=$config[7];
                   5034: 	$config{'Qlength'}=$config[8];
                   5035: 	$config{'Qoff'}=$config[9];
                   5036: 	$config{'Qon'}=$config[10];
1.157     albertel 5037: 	$config{'PaperID'}=$config[11];
                   5038: 	$config{'PaperIDlength'}=$config[12];
                   5039: 	$config{'FirstName'}=$config[13];
                   5040: 	$config{'FirstNamelength'}=$config[14];
                   5041: 	$config{'LastName'}=$config[15];
                   5042: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 5043: 	last;
                   5044:     }
                   5045:     return %config;
                   5046: }
                   5047: 
1.423     albertel 5048: =pod 
                   5049: 
                   5050: =item username_to_idmap
                   5051: 
                   5052:     creates a hash keyed by student id with values of the corresponding
                   5053:     student username:domain.
                   5054: 
                   5055:   Arguments:
                   5056: 
                   5057:     $classlist - reference to the class list hash. This is a hash
                   5058:                  keyed by student name:domain  whose elements are references
1.424     albertel 5059:                  to arrays containing various chunks of information
1.423     albertel 5060:                  about the student. (See loncoursedata for more info).
                   5061: 
                   5062:   Returns
                   5063:     %idmap - the constructed hash
                   5064: 
                   5065: =cut
                   5066: 
1.82      albertel 5067: sub username_to_idmap {
                   5068:     my ($classlist)= @_;
                   5069:     my %idmap;
                   5070:     foreach my $student (keys(%$classlist)) {
                   5071: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5072: 	    $student;
                   5073:     }
                   5074:     return %idmap;
                   5075: }
1.423     albertel 5076: 
                   5077: =pod
                   5078: 
1.424     albertel 5079: =item scantron_fixup_scanline
1.423     albertel 5080: 
                   5081:    Process a requested correction to a scanline.
                   5082: 
                   5083:   Arguments:
                   5084:     $scantron_config   - hash from &get_scantron_config()
                   5085:     $scan_data         - hash of correction information 
                   5086:                           (see &scantron_getfile())
                   5087:     $line              - existing scanline
                   5088:     $whichline         - line number of the passed in scanline
                   5089:     $field             - type of change to process 
                   5090:                          (either 
                   5091:                           'ID'     -> correct the student ID number
                   5092:                           'CODE'   -> correct the CODE
                   5093:                           'answer' -> fixup the submitted answers)
                   5094:     
                   5095:    $args               - hash of additional info,
                   5096:                           - 'ID' 
                   5097:                                'newid' -> studentID to use in replacement
1.424     albertel 5098:                                           of existing one
1.423     albertel 5099:                           - 'CODE' 
                   5100:                                'CODE_ignore_dup' - set to true if duplicates
                   5101:                                                    should be ignored.
                   5102: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5103:                                         if the existing unfound code should
1.423     albertel 5104:                                         be used as is
                   5105:                           - 'answer'
                   5106:                                'response' - new answer or 'none' if blank
                   5107:                                'question' - the bubble line to change
                   5108: 
                   5109:   Returns:
                   5110:     $line - the modified scanline
                   5111: 
                   5112:   Side effects: 
                   5113:     $scan_data - may be updated
                   5114: 
                   5115: =cut
                   5116: 
1.82      albertel 5117: 
1.157     albertel 5118: sub scantron_fixup_scanline {
                   5119:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.479     foxr     5120:     
                   5121:     
1.157     albertel 5122:     if ($field eq 'ID') {
                   5123: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5124: 	    return ($line,1,'New value too large');
1.157     albertel 5125: 	}
                   5126: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5127: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5128: 				     $args->{'newid'});
                   5129: 	}
                   5130: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5131: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5132: 	if ($args->{'newid'}=~/^\s*$/) {
                   5133: 	    &scan_data($scan_data,"$whichline.user",
                   5134: 		       $args->{'username'}.':'.$args->{'domain'});
                   5135: 	}
1.186     albertel 5136:     } elsif ($field eq 'CODE') {
1.192     albertel 5137: 	if ($args->{'CODE_ignore_dup'}) {
                   5138: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5139: 	}
                   5140: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5141: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5142: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5143: 		return ($line,1,'New CODE value too large');
                   5144: 	    }
                   5145: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5146: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5147: 	    }
                   5148: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5149: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5150: 	}
1.157     albertel 5151:     } elsif ($field eq 'answer') {
1.479     foxr     5152: 	&scantron_get_maxbubble(); # Need the bubble counter info.
1.157     albertel 5153: 	my $length=$scantron_config->{'Qlength'};
                   5154: 	my $off=$scantron_config->{'Qoff'};
                   5155: 	my $on=$scantron_config->{'Qon'};
                   5156: 	my $answer=${off}x$length;
1.479     foxr     5157:         my $question_number = $args->{'question'} -1;
                   5158:         my $first_position  = $first_bubble_line{$question_number};
                   5159: 	my $bubble_count    = $bubble_lines_per_response{$question_number};
                   5160:         my $bubbles_per_line= $$scantron_config{'Qlength'};
                   5161:         my $final_answer;
                   5162:         if ($$scantron_config{'Qon'} eq 'letter'  ||
                   5163: 	    $$scantron_config{'Qon'} eq 'number') { 
                   5164: 	    $bubbles_per_line = 10;
                   5165: 	}
                   5166: 	if (defined $args->{'response'}) {
                   5167: 	    
                   5168: 	    if ($args->{'response'} eq 'none') {
                   5169: 		&scan_data($scan_data,
                   5170: 			   "$whichline.no_bubble.".$args->{'question'},'1');
1.274     albertel 5171: 	    } else {
1.479     foxr     5172: 		my ($bubble_line, $bubble_number) = split(/:/,$args->{'response'});
                   5173: 		if ($on eq 'letter') {
                   5174: 		    my @alphabet=('A'..'Z');
                   5175: 		    $answer=$alphabet[$bubble_number];
                   5176: 		} elsif ($on eq 'number') {
                   5177: 		    $answer=$args->$bubble_number+1;
                   5178: 		    if ($answer == 10) { $answer = '0'; }
                   5179: 		} else {
                   5180: 		    substr($answer,$args->{'response'},1)=$on;
                   5181: 		}
                   5182: 		&scan_data($scan_data,
                   5183: 			   "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5184: 		for (my $l = 0; $l < $bubble_count; $l++) {
                   5185: 		    if ($l eq $bubble_line) {
                   5186: 			$final_answer .= $answer;
                   5187: 		    } else {
                   5188: 			$final_answer .= ' ';
                   5189: 		    }
                   5190: 		}
1.274     albertel 5191: 	    }
1.479     foxr     5192: 	    # $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5193: 	    #substr($line,$where-1,$length)=$answer;
                   5194: 	    substr($line, 
                   5195: 		   $scantron_config->{'Qstart'}+$first_position-1,
                   5196: 		   $bubbles_per_line) = $final_answer;
1.157     albertel 5197: 	}
                   5198:     }
                   5199:     return $line;
                   5200: }
1.423     albertel 5201: 
                   5202: =pod
                   5203: 
                   5204: =item scan_data
                   5205: 
                   5206:     Edit or look up  an item in the scan_data hash.
                   5207: 
                   5208:   Arguments:
                   5209:     $scan_data  - The hash (see scantron_getfile)
                   5210:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5211:                   scantronfilename_key).
1.423     albertel 5212:     $data        - New value of the hash entry.
                   5213:     $delete      - If true, the entry is removed from the hash.
                   5214: 
                   5215:   Returns:
                   5216:     The new value of the hash table field (undefined if deleted).
                   5217: 
                   5218: =cut
                   5219: 
                   5220: 
1.157     albertel 5221: sub scan_data {
                   5222:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5223:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5224:     if (defined($value)) {
                   5225: 	$scan_data->{$filename.'_'.$key} = $value;
                   5226:     }
                   5227:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5228:     return $scan_data->{$filename.'_'.$key};
                   5229: }
1.423     albertel 5230: 
                   5231: =pod 
                   5232: 
                   5233: =item scantron_parse_scanline
                   5234: 
                   5235:   Decodes a scanline from the selected scantron file
                   5236: 
                   5237:  Arguments:
                   5238:     line             - The text of the scantron file line to process
                   5239:     whichline        - Line number
                   5240:     scantron_config  - Hash describing the format of the scantron lines.
                   5241:     scan_data        - Hash of extra information about the scanline
                   5242:                        (see scantron_getfile for more information)
                   5243:     just_header      - True if should not process question answers but only
                   5244:                        the stuff to the left of the answers.
                   5245:  Returns:
                   5246:    Hash containing the result of parsing the scanline
                   5247: 
                   5248:    Keys are all proceeded by the string 'scantron.'
                   5249: 
                   5250:        CODE    - the CODE in use for this scanline
                   5251:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5252:                  by the operator
                   5253:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5254:                             CODEs were selected, but the usage has been
                   5255:                             forced by the operator
                   5256:        ID  - student ID
                   5257:        PaperID - if used, the ID number printed on the sheet when the 
                   5258:                  paper was scanned
                   5259:        FirstName - first name from the sheet
                   5260:        LastName  - last name from the sheet
                   5261: 
                   5262:      if just_header was not true these key may also exist
                   5263: 
1.447     foxr     5264:        missingerror - a list of bubble ranges that are considered to be answers
                   5265:                       to a single question that don't have any bubbles filled in.
                   5266:                       Of the form questionnumber:firstbubblenumber:count.
                   5267:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5268:                       to a single question that have more than one bubble filled in.
                   5269:                       Of the form questionnumber::firstbubblenumber:count
                   5270:    
                   5271:                 In the above, count is the number of bubble responses in the
                   5272:                 input line needed to represent the possible answers to the question.
                   5273:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5274:                 per line would have count = 2.
                   5275: 
1.423     albertel 5276:        maxquest     - the number of the last bubble line that was parsed
                   5277: 
                   5278:        (<number> starts at 1)
                   5279:        <number>.answer - zero or more letters representing the selected
                   5280:                          letters from the scanline for the bubble line 
                   5281:                          <number>.
                   5282:                          if blank there was either no bubble or there where
                   5283:                          multiple bubbles, (consult the keys missingerror and
                   5284:                          doubleerror if this is an error condition)
                   5285: 
                   5286: =cut
                   5287: 
1.82      albertel 5288: sub scantron_parse_scanline {
1.423     albertel 5289:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.470     foxr     5290: 
1.82      albertel 5291:     my %record;
1.422     foxr     5292:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5293:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5294:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5295: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5296: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5297: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5298: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5299: 	    $record{'scantron.CODE'}=substr($data,
                   5300: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5301: 					    $$scantron_config{'CODElength'});
1.191     albertel 5302: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5303: 		$record{'scantron.useCODE'}=1;
                   5304: 	    }
1.192     albertel 5305: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5306: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5307: 	    }
1.82      albertel 5308: 	} else {
                   5309: 	    #FIXME interpret first N questions
                   5310: 	}
                   5311:     }
1.83      albertel 5312:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5313: 				  $$scantron_config{'IDlength'});
1.157     albertel 5314:     $record{'scantron.PaperID'}=
                   5315: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5316: 	       $$scantron_config{'PaperIDlength'});
                   5317:     $record{'scantron.FirstName'}=
                   5318: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5319: 	       $$scantron_config{'FirstNamelength'});
                   5320:     $record{'scantron.LastName'}=
                   5321: 	substr($data,$$scantron_config{'LastName'}-1,
                   5322: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5323:     if ($just_header) { return \%record; }
1.194     albertel 5324: 
1.82      albertel 5325:     my @alphabet=('A'..'Z');
                   5326:     my $questnum=0;
1.447     foxr     5327:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5328: 
1.470     foxr     5329:     chomp($questions);		# Get rid of any trailing \n.
                   5330:     $questions =~ s/\r$//;      # Get rid of trailing \r too (MAC or Win uploads).
                   5331:     while (length($questions)) {
1.447     foxr     5332: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5333: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5334: 
                   5335: 
                   5336: 
1.82      albertel 5337: 	$questnum++;
1.447     foxr     5338: 	my $currentquest = substr($questions,0,$answer_length);
                   5339: 	$questions       = substr($questions,0,$answer_length)='';
                   5340: 	if (length($currentquest) < $answer_length) { next; }
                   5341: 
                   5342: 	# Qon letter implies for each slot in currentquest we have:
                   5343: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5344:         #    about anything else (esp. a value of Qoff for missing
                   5345: 	#    bubbles.
                   5346: 
                   5347: 
1.239     albertel 5348: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5349: 
                   5350: 	    if ($currentquest =~ /\?/
                   5351: 		|| $currentquest =~ /\*/
                   5352: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5353: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5354: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
1.460     foxr     5355: 		    my $bubble = substr($currentquest, $ans, 1);
                   5356: 		    if ($bubble =~ /[A-Z]/ ) {
                   5357: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5358: 		    } else {
                   5359: 			$record{"scantron.$ansnum.answer"}='';
                   5360: 		    }
1.447     foxr     5361: 		    $ansnum++;
                   5362: 		}
                   5363: 
1.389     albertel 5364: 	    } elsif (!defined($currentquest)
1.447     foxr     5365: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5366: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5367: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5368: 		    $record{"scantron.$ansnum.answer"}='';
                   5369: 		    $ansnum++;
                   5370: 
                   5371: 		}
1.239     albertel 5372: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5373: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.470     foxr     5374: 		   #  $ansnum += $answers_needed;
1.239     albertel 5375: 		}
                   5376: 	    } else {
1.447     foxr     5377: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5378: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5379: 		    $ansnum++;
                   5380: 		}
1.239     albertel 5381: 	    }
1.447     foxr     5382: 
                   5383: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5384: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5385:         #    and *? for double bubbles on a line.
                   5386: 	#    these answers are also stored as letters.
                   5387: 
1.239     albertel 5388: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5389: 	    if ($currentquest =~ /\?/
                   5390: 		|| $currentquest =~ /\*/
                   5391: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5392: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5393: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
1.460     foxr     5394: 		    my $bubble = substr($currentquest, $ans, 1);
                   5395: 		    if ($bubble =~ /\d/) {
                   5396: 			$record{"scantron.$ansnum.answer"} = $alphabet[$bubble];
                   5397: 		    } else {
1.461     foxr     5398: 			$record{"scantron.$ansnum.answer"}=' ';
1.460     foxr     5399: 		    }
1.447     foxr     5400: 		    $ansnum++;
                   5401: 		}
                   5402: 
1.389     albertel 5403: 	    } elsif (!defined($currentquest)
1.447     foxr     5404: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5405: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5406: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5407: 		    $record{"scantron.$ansnum.answer"}='';
                   5408: 		    $ansnum++;
                   5409: 
                   5410: 		}
1.239     albertel 5411: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5412: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5413: 		    $ansnum += $answers_needed;
1.239     albertel 5414: 		}
1.447     foxr     5415: 
1.239     albertel 5416: 	    } else {
1.447     foxr     5417: 		$currentquest = &digits_to_letters($currentquest);
                   5418: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5419: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5420: 		    $ansnum++;
1.371     albertel 5421: 		}
1.239     albertel 5422: 	    }
1.82      albertel 5423: 	} else {
1.447     foxr     5424: 
                   5425: 	    # Otherwise there's a positional notation;
                   5426: 	    # each bubble line requires Qlength items, and there are filled in
                   5427: 	    # bubbles for each case where there 'Qon' characters.
                   5428: 	    #
                   5429: 
1.239     albertel 5430: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5431: 
                   5432: 	    # If the split only  giveas us one element.. the full length of the
                   5433: 	    # answser string, no bubbles are filled in:
                   5434: 
                   5435: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5436: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5437: 		    $record{"scantron.$ansnum.answer"}='';
                   5438: 		    $ansnum++;
                   5439: 
                   5440: 		}
1.239     albertel 5441: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5442: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5443: 		}
1.447     foxr     5444: 	    } elsif (scalar(@array) lt 2) {
                   5445: 
1.459     foxr     5446: 		my $location      = length($array[0]);
1.447     foxr     5447: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5448: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5449: 
                   5450: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5451: 		    if ($ans eq $line_num) {
                   5452: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5453: 		    } else {
                   5454: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5455: 		    }
                   5456: 		    $ansnum++;
                   5457: 		}
1.239     albertel 5458: 	    }
1.447     foxr     5459: 	    #  If there's more than one instance of a bubble character
                   5460: 	    #  That's a double bubble; with positional notation we can
                   5461: 	    #  record all the bubbles filled in as well as the 
                   5462: 	    #  fact this response consists of multiple bubbles.
                   5463: 	    #
                   5464: 	    else {
1.239     albertel 5465: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5466: 
                   5467: 		my $first_answer = $ansnum;
                   5468: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
1.462     foxr     5469: 		    my $item = $first_answer+$ans;
                   5470: 		    $record{"scantron.$item.answer"} = '';
1.447     foxr     5471: 		}
                   5472: 
1.239     albertel 5473: 		my @ans=@array;
1.462     foxr     5474: 		my $i=0;
                   5475: 		my $increment = 0;
1.239     albertel 5476: 		while ($#ans) {
1.462     foxr     5477: 		    $i+=length($ans[0]) + $increment;
                   5478: 		    my $line   = int($i/$$scantron_config{'Qlength'} + $first_answer);
1.447     foxr     5479: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5480: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5481: 		    shift(@ans);
1.462     foxr     5482: 		    $increment = 1;
1.239     albertel 5483: 		}
1.462     foxr     5484: 		$ansnum += $answers_needed;
1.239     albertel 5485: 	    }
1.82      albertel 5486: 	}
                   5487:     }
1.83      albertel 5488:     $record{'scantron.maxquest'}=$questnum;
                   5489:     return \%record;
1.82      albertel 5490: }
                   5491: 
1.423     albertel 5492: =pod
                   5493: 
                   5494: =item scantron_add_delay
                   5495: 
                   5496:    Adds an error message that occurred during the grading phase to a
                   5497:    queue of messages to be shown after grading pass is complete
                   5498: 
                   5499:  Arguments:
1.424     albertel 5500:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5501:    $scanline    - the scanline that caused the error
                   5502:    $errormesage - the error message
                   5503:    $errorcode   - a numeric code for the error
                   5504: 
                   5505:  Side Effects:
1.424     albertel 5506:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5507: 
                   5508: =cut
                   5509: 
1.82      albertel 5510: sub scantron_add_delay {
1.140     albertel 5511:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5512:     push(@$delayqueue,
                   5513: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5514: 	  'ecode' => $errorcode }
                   5515: 	 );
1.82      albertel 5516: }
                   5517: 
1.423     albertel 5518: =pod
                   5519: 
                   5520: =item scantron_find_student
                   5521: 
1.424     albertel 5522:    Finds the username for the current scanline
                   5523: 
                   5524:   Arguments:
                   5525:    $scantron_record - hash result from scantron_parse_scanline
                   5526:    $scan_data       - hash of correction information 
                   5527:                       (see &scantron_getfile() form more information)
                   5528:    $idmap           - hash from &username_to_idmap()
                   5529:    $line            - number of current scanline
                   5530:  
                   5531:   Returns:
                   5532:    Either 'username:domain' or undef if unknown
                   5533: 
1.423     albertel 5534: =cut
                   5535: 
1.82      albertel 5536: sub scantron_find_student {
1.157     albertel 5537:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5538:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5539:     if ($scanID =~ /^\s*$/) {
                   5540:  	return &scan_data($scan_data,"$line.user");
                   5541:     }
1.83      albertel 5542:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5543:  	if (lc($id) eq lc($scanID)) {
                   5544:  	    return $$idmap{$id};
                   5545:  	}
1.83      albertel 5546:     }
                   5547:     return undef;
                   5548: }
                   5549: 
1.423     albertel 5550: =pod
                   5551: 
                   5552: =item scantron_filter
                   5553: 
1.424     albertel 5554:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5555:    hidden resources was selected
                   5556: 
1.423     albertel 5557: =cut
                   5558: 
1.83      albertel 5559: sub scantron_filter {
                   5560:     my ($curres)=@_;
1.331     albertel 5561: 
                   5562:     if (ref($curres) && $curres->is_problem()) {
                   5563: 	# if the user has asked to not have either hidden
                   5564: 	# or 'randomout' controlled resources to be graded
                   5565: 	# don't include them
                   5566: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5567: 	    && $curres->randomout) {
                   5568: 	    return 0;
                   5569: 	}
1.83      albertel 5570: 	return 1;
                   5571:     }
                   5572:     return 0;
1.82      albertel 5573: }
                   5574: 
1.423     albertel 5575: =pod
                   5576: 
                   5577: =item scantron_process_corrections
                   5578: 
1.424     albertel 5579:    Gets correction information out of submitted form data and corrects
                   5580:    the scanline
                   5581: 
1.423     albertel 5582: =cut
                   5583: 
1.157     albertel 5584: sub scantron_process_corrections {
                   5585:     my ($r) = @_;
1.257     albertel 5586:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5587:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5588:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5589:     my $which=$env{'form.scantron_line'};
1.200     albertel 5590:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5591:     my ($skip,$err,$errmsg);
1.257     albertel 5592:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5593: 	$skip=1;
1.257     albertel 5594:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5595: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5596: 	    $env{'form.scantron_domain'};
1.157     albertel 5597: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5598: 	($line,$err,$errmsg)=
                   5599: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5600: 				     'ID',{'newid'=>$newid,
1.257     albertel 5601: 				    'username'=>$env{'form.scantron_username'},
                   5602: 				    'domain'=>$env{'form.scantron_domain'}});
                   5603:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5604: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5605: 	my $newCODE;
1.192     albertel 5606: 	my %args;
1.190     albertel 5607: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5608: 	    $newCODE='use_unfound';
1.190     albertel 5609: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5610: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5611: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5612: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5613: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5614: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5615: 	}
1.257     albertel 5616: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5617: 	    $args{'CODE_ignore_dup'}=1;
                   5618: 	}
                   5619: 	$args{'CODE'}=$newCODE;
1.186     albertel 5620: 	($line,$err,$errmsg)=
                   5621: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5622: 				     'CODE',\%args);
1.257     albertel 5623:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5624: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5625: 	    ($line,$err,$errmsg)=
                   5626: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5627: 					 $which,'answer',
                   5628: 					 { 'question'=>$question,
1.257     albertel 5629: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5630: 	    if ($err) { last; }
                   5631: 	}
                   5632:     }
                   5633:     if ($err) {
1.398     albertel 5634: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5635:     } else {
1.200     albertel 5636: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5637: 	&scantron_putfile($scanlines,$scan_data);
                   5638:     }
                   5639: }
                   5640: 
1.423     albertel 5641: =pod
                   5642: 
                   5643: =item reset_skipping_status
                   5644: 
1.424     albertel 5645:    Forgets the current set of remember skipped scanlines (and thus
                   5646:    reverts back to considering all lines in the
                   5647:    scantron_skipped_<filename> file)
                   5648: 
1.423     albertel 5649: =cut
                   5650: 
1.200     albertel 5651: sub reset_skipping_status {
                   5652:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5653:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5654:     &scantron_putfile(undef,$scan_data);
                   5655: }
                   5656: 
1.423     albertel 5657: =pod
                   5658: 
                   5659: =item start_skipping
                   5660: 
1.424     albertel 5661:    Marks a scanline to be skipped. 
                   5662: 
1.423     albertel 5663: =cut
                   5664: 
1.376     albertel 5665: sub start_skipping {
1.200     albertel 5666:     my ($scan_data,$i)=@_;
                   5667:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5668:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5669: 	$remembered{$i}=2;
                   5670:     } else {
                   5671: 	$remembered{$i}=1;
                   5672:     }
1.200     albertel 5673:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5674: }
                   5675: 
1.423     albertel 5676: =pod
                   5677: 
                   5678: =item should_be_skipped
                   5679: 
1.424     albertel 5680:    Checks whether a scanline should be skipped.
                   5681: 
1.423     albertel 5682: =cut
                   5683: 
1.200     albertel 5684: sub should_be_skipped {
1.376     albertel 5685:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5686:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5687: 	# not redoing old skips
1.376     albertel 5688: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5689: 	return 0;
                   5690:     }
                   5691:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5692: 
                   5693:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5694: 	return 0;
                   5695:     }
1.200     albertel 5696:     return 1;
                   5697: }
                   5698: 
1.423     albertel 5699: =pod
                   5700: 
                   5701: =item remember_current_skipped
                   5702: 
1.424     albertel 5703:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5704:    file and remembers them into scan_data for later use.
                   5705: 
1.423     albertel 5706: =cut
                   5707: 
1.200     albertel 5708: sub remember_current_skipped {
                   5709:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5710:     my %to_remember;
                   5711:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5712: 	if ($scanlines->{'skipped'}[$i]) {
                   5713: 	    $to_remember{$i}=1;
                   5714: 	}
                   5715:     }
1.376     albertel 5716: 
1.200     albertel 5717:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5718:     &scantron_putfile(undef,$scan_data);
                   5719: }
                   5720: 
1.423     albertel 5721: =pod
                   5722: 
                   5723: =item check_for_error
                   5724: 
1.424     albertel 5725:     Checks if there was an error when attempting to remove a specific
                   5726:     scantron_.. bubble sheet data file. Prints out an error if
                   5727:     something went wrong.
                   5728: 
1.423     albertel 5729: =cut
                   5730: 
1.200     albertel 5731: sub check_for_error {
                   5732:     my ($r,$result)=@_;
                   5733:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5734: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5735:     }
                   5736: }
1.157     albertel 5737: 
1.423     albertel 5738: =pod
                   5739: 
                   5740: =item scantron_warning_screen
                   5741: 
1.424     albertel 5742:    Interstitial screen to make sure the operator has selected the
                   5743:    correct options before we start the validation phase.
                   5744: 
1.423     albertel 5745: =cut
                   5746: 
1.203     albertel 5747: sub scantron_warning_screen {
                   5748:     my ($button_text)=@_;
1.257     albertel 5749:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5750:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5751:     my $CODElist;
1.284     albertel 5752:     if ($scantron_config{'CODElocation'} &&
                   5753: 	$scantron_config{'CODEstart'} &&
                   5754: 	$scantron_config{'CODElength'}) {
                   5755: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5756: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5757: 	$CODElist=
                   5758: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5759: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5760:     }
1.203     albertel 5761:     return (<<STUFF);
                   5762: <p>
1.398     albertel 5763: <span class="LC_warning">Please double check the information
                   5764:                  below before clicking on '$button_text'</span>
1.203     albertel 5765: </p>
                   5766: <table>
1.284     albertel 5767: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5768: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5769: $CODElist
1.203     albertel 5770: </table>
                   5771: <br />
                   5772: <p> If this information is correct, please click on '$button_text'.</p>
                   5773: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5774: 
                   5775: <br />
                   5776: STUFF
                   5777: }
                   5778: 
1.423     albertel 5779: =pod
                   5780: 
                   5781: =item scantron_do_warning
                   5782: 
1.424     albertel 5783:    Check if the operator has picked something for all required
                   5784:    fields. Error out if something is missing.
                   5785: 
1.423     albertel 5786: =cut
                   5787: 
1.203     albertel 5788: sub scantron_do_warning {
                   5789:     my ($r)=@_;
1.324     albertel 5790:     my ($symb)=&get_symb($r);
1.203     albertel 5791:     if (!$symb) {return '';}
1.324     albertel 5792:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5793:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5794:     if ( $env{'form.selectpage'} eq '' ||
                   5795: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5796: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5797: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5798: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5799: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5800: 	} 
1.257     albertel 5801: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5802: 	    $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 5803: 	} 
1.257     albertel 5804: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5805: 	    $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 5806: 	} 
                   5807:     } else {
1.265     www      5808: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5809: 	$r->print(<<STUFF);
1.203     albertel 5810: $warning
1.265     www      5811: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5812: <input type="hidden" name="command" value="scantron_validate" />
                   5813: STUFF
1.237     albertel 5814:     }
1.352     albertel 5815:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5816:     return '';
                   5817: }
                   5818: 
1.423     albertel 5819: =pod
                   5820: 
                   5821: =item scantron_form_start
                   5822: 
1.424     albertel 5823:     html hidden input for remembering all selected grading options
                   5824: 
1.423     albertel 5825: =cut
                   5826: 
1.203     albertel 5827: sub scantron_form_start {
                   5828:     my ($max_bubble)=@_;
                   5829:     my $result= <<SCANTRONFORM;
                   5830: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5831:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5832:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5833:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5834:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5835:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5836:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5837:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5838:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5839:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5840: SCANTRONFORM
1.447     foxr     5841: 
                   5842:   my $line = 0;
                   5843:     while (defined($env{"form.scantron.bubblelines.$line"})) {
                   5844:        my $chunk =
                   5845: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5846:        $chunk .=
                   5847: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5848:        $result .= $chunk;
                   5849:        $line++;
                   5850:    }
1.203     albertel 5851:     return $result;
                   5852: }
                   5853: 
1.423     albertel 5854: =pod
                   5855: 
                   5856: =item scantron_validate_file
                   5857: 
1.424     albertel 5858:     Dispatch routine for doing validation of a bubble sheet data file.
                   5859: 
                   5860:     Also processes any necessary information resets that need to
                   5861:     occur before validation begins (ignore previous corrections,
                   5862:     restarting the skipped records processing)
                   5863: 
1.423     albertel 5864: =cut
                   5865: 
1.157     albertel 5866: sub scantron_validate_file {
                   5867:     my ($r) = @_;
1.324     albertel 5868:     my ($symb)=&get_symb($r);
1.157     albertel 5869:     if (!$symb) {return '';}
1.324     albertel 5870:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5871:     
                   5872:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5873:     # them when doing the corrections reset
1.257     albertel 5874:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5875: 	&reset_skipping_status();
                   5876:     }
1.257     albertel 5877:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5878: 	&remember_current_skipped();
1.257     albertel 5879: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5880:     }
                   5881: 
1.257     albertel 5882:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5883: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5884: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5885: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5886: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5887:     }
1.200     albertel 5888: 
1.257     albertel 5889:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5890: 	&scantron_process_corrections($r);
                   5891:     }
1.424     albertel 5892:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5893:     #get the student pick code ready
                   5894:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5895:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5896:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5897:     $r->print($result);
                   5898:     
1.334     albertel 5899:     my @validate_phases=( 'sequence',
                   5900: 			  'ID',
1.157     albertel 5901: 			  'CODE',
                   5902: 			  'doublebubble',
                   5903: 			  'missingbubbles');
1.257     albertel 5904:     if (!$env{'form.validatepass'}) {
                   5905: 	$env{'form.validatepass'} = 0;
1.157     albertel 5906:     }
1.257     albertel 5907:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5908: 
1.448     foxr     5909: 
1.157     albertel 5910:     my $stop=0;
                   5911:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5912: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5913: 	$r->rflush();
                   5914: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5915: 	{
                   5916: 	    no strict 'refs';
                   5917: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5918: 	}
                   5919:     }
                   5920:     if (!$stop) {
1.203     albertel 5921: 	my $warning=&scantron_warning_screen('Start Grading');
                   5922: 	$r->print(<<STUFF);
                   5923: Validation process complete.<br />
                   5924: $warning
                   5925: <input type="submit" name="submit" value="Start Grading" />
                   5926: <input type="hidden" name="command" value="scantron_process" />
                   5927: STUFF
                   5928: 
1.157     albertel 5929:     } else {
                   5930: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5931: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5932:     }
                   5933:     if ($stop) {
1.334     albertel 5934: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5935: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5936: 	    $r->print(' this error <br />');
                   5937: 
                   5938: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5939: 	} else {
                   5940: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5941: 	    $r->print(' using corrected info <br />');
                   5942: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5943: 	    $r->print(" this scanline saving it for later.");
                   5944: 	}
1.157     albertel 5945:     }
1.352     albertel 5946:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5947:     return '';
                   5948: }
                   5949: 
1.423     albertel 5950: 
                   5951: =pod
                   5952: 
                   5953: =item scantron_remove_file
                   5954: 
1.424     albertel 5955:    Removes the requested bubble sheet data file, makes sure that
                   5956:    scantron_original_<filename> is never removed
                   5957: 
                   5958: 
1.423     albertel 5959: =cut
                   5960: 
1.200     albertel 5961: sub scantron_remove_file {
1.192     albertel 5962:     my ($which)=@_;
1.257     albertel 5963:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5964:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5965:     my $file='scantron_';
1.200     albertel 5966:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5967: 	$file.=$which.'_';
1.192     albertel 5968:     } else {
                   5969: 	return 'refused';
                   5970:     }
1.257     albertel 5971:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5972:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5973: }
                   5974: 
1.423     albertel 5975: 
                   5976: =pod
                   5977: 
                   5978: =item scantron_remove_scan_data
                   5979: 
1.424     albertel 5980:    Removes all scan_data correction for the requested bubble sheet
                   5981:    data file.  (In the case that both the are doing skipped records we need
                   5982:    to remember the old skipped lines for the time being so that element
                   5983:    persists for a while.)
                   5984: 
1.423     albertel 5985: =cut
                   5986: 
1.200     albertel 5987: sub scantron_remove_scan_data {
1.257     albertel 5988:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5989:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5990:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5991:     my @todelete;
1.257     albertel 5992:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5993:     foreach my $key (@keys) {
                   5994: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5995: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5996: 		$key=~/remember_skipping/) {
                   5997: 		next;
                   5998: 	    }
1.192     albertel 5999: 	    push(@todelete,$key);
                   6000: 	}
                   6001:     }
1.200     albertel 6002:     my $result;
1.192     albertel 6003:     if (@todelete) {
1.200     albertel 6004: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 6005:     }
                   6006:     return $result;
                   6007: }
                   6008: 
1.423     albertel 6009: 
                   6010: =pod
                   6011: 
                   6012: =item scantron_getfile
                   6013: 
1.424     albertel 6014:     Fetches the requested bubble sheet data file (all 3 versions), and
                   6015:     the scan_data hash
                   6016:   
                   6017:   Arguments:
                   6018:     None
                   6019: 
                   6020:   Returns:
                   6021:     2 hash references
                   6022: 
                   6023:      - first one has 
                   6024:          orig      -
                   6025:          corrected -
                   6026:          skipped   -  each of which points to an array ref of the specified
                   6027:                       file broken up into individual lines
                   6028:          count     - number of scanlines
                   6029:  
                   6030:      - second is the scan_data hash possible keys are
1.425     albertel 6031:        ($number refers to scanline numbered $number and thus the key affects
                   6032:         only that scanline
                   6033:         $bubline refers to the specific bubble line element and the aspects
                   6034:         refers to that specific bubble line element)
                   6035: 
                   6036:        $number.user - username:domain to use
                   6037:        $number.CODE_ignore_dup 
                   6038:                     - ignore the duplicate CODE error 
                   6039:        $number.useCODE
                   6040:                     - use the CODE in the scanline as is
                   6041:        $number.no_bubble.$bubline
                   6042:                     - it is valid that there is no bubbled in bubble
                   6043:                       at $number $bubline
                   6044:        remember_skipping
                   6045:                     - a frozen hash containing keys of $number and values
                   6046:                       of either 
                   6047:                         1 - we are on a 'do skipped records pass' and plan
                   6048:                             on processing this line
                   6049:                         2 - we are on a 'do skipped records pass' and this
                   6050:                             scanline has been marked to skip yet again
1.424     albertel 6051: 
1.423     albertel 6052: =cut
                   6053: 
1.157     albertel 6054: sub scantron_getfile {
1.200     albertel 6055:     #FIXME really would prefer a scantron directory
1.257     albertel 6056:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6057:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 6058:     my $lines;
                   6059:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6060: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 6061:     my %scanlines;
                   6062:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   6063:     my $temp=$scanlines{'orig'};
                   6064:     $scanlines{'count'}=$#$temp;
                   6065: 
                   6066:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6067: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 6068:     if ($lines eq '-1') {
                   6069: 	$scanlines{'corrected'}=[];
                   6070:     } else {
                   6071: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   6072:     }
                   6073:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 6074: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 6075:     if ($lines eq '-1') {
                   6076: 	$scanlines{'skipped'}=[];
                   6077:     } else {
                   6078: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   6079:     }
1.175     albertel 6080:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 6081:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   6082:     my %scan_data = @tmp;
                   6083:     return (\%scanlines,\%scan_data);
                   6084: }
                   6085: 
1.423     albertel 6086: =pod
                   6087: 
                   6088: =item lonnet_putfile
                   6089: 
1.424     albertel 6090:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6091: 
                   6092:  Arguments:
                   6093:    $contents - data to store
                   6094:    $filename - filename to store $contents into
                   6095: 
                   6096:  Returns:
                   6097:    result value from &Apache::lonnet::finishuserfileupload
                   6098: 
1.423     albertel 6099: =cut
                   6100: 
1.157     albertel 6101: sub lonnet_putfile {
                   6102:     my ($contents,$filename)=@_;
1.257     albertel 6103:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6104:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6105:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6106:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6107: 
                   6108: }
                   6109: 
1.423     albertel 6110: =pod
                   6111: 
                   6112: =item scantron_putfile
                   6113: 
1.424     albertel 6114:     Stores the current version of the bubble sheet data files, and the
                   6115:     scan_data hash. (Does not modify the original version only the
                   6116:     corrected and skipped versions.
                   6117: 
                   6118:  Arguments:
                   6119:     $scanlines - hash ref that looks like the first return value from
                   6120:                  &scantron_getfile()
                   6121:     $scan_data - hash ref that looks like the second return value from
                   6122:                  &scantron_getfile()
                   6123: 
1.423     albertel 6124: =cut
                   6125: 
1.157     albertel 6126: sub scantron_putfile {
                   6127:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6128:     #FIXME really would prefer a scantron directory
1.257     albertel 6129:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6130:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6131:     if ($scanlines) {
                   6132: 	my $prefix='scantron_';
1.157     albertel 6133: # no need to update orig, shouldn't change
                   6134: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6135: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6136: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6137: 			$prefix.'corrected_'.
1.257     albertel 6138: 			$env{'form.scantron_selectfile'});
1.200     albertel 6139: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6140: 			$prefix.'skipped_'.
1.257     albertel 6141: 			$env{'form.scantron_selectfile'});
1.200     albertel 6142:     }
1.175     albertel 6143:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6144: }
                   6145: 
1.423     albertel 6146: =pod
                   6147: 
                   6148: =item scantron_get_line
                   6149: 
1.424     albertel 6150:    Returns the correct version of the scanline
                   6151: 
                   6152:  Arguments:
                   6153:     $scanlines - hash ref that looks like the first return value from
                   6154:                  &scantron_getfile()
                   6155:     $scan_data - hash ref that looks like the second return value from
                   6156:                  &scantron_getfile()
                   6157:     $i         - number of the requested line (starts at 0)
                   6158: 
                   6159:  Returns:
                   6160:    A scanline, (either the original or the corrected one if it
                   6161:    exists), or undef if the requested scanline should be
                   6162:    skipped. (Either because it's an skipped scanline, or it's an
                   6163:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6164:    pass.
                   6165: 
1.423     albertel 6166: =cut
                   6167: 
1.157     albertel 6168: sub scantron_get_line {
1.200     albertel 6169:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6170:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6171:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6172:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6173:     return $scanlines->{'orig'}[$i]; 
                   6174: }
                   6175: 
1.423     albertel 6176: =pod
                   6177: 
                   6178: =item scantron_todo_count
                   6179: 
1.424     albertel 6180:     Counts the number of scanlines that need processing.
                   6181: 
                   6182:  Arguments:
                   6183:     $scanlines - hash ref that looks like the first return value from
                   6184:                  &scantron_getfile()
                   6185:     $scan_data - hash ref that looks like the second return value from
                   6186:                  &scantron_getfile()
                   6187: 
                   6188:  Returns:
                   6189:     $count - number of scanlines to process
                   6190: 
1.423     albertel 6191: =cut
                   6192: 
1.200     albertel 6193: sub get_todo_count {
                   6194:     my ($scanlines,$scan_data)=@_;
                   6195:     my $count=0;
                   6196:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6197: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6198: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6199: 	$count++;
                   6200:     }
                   6201:     return $count;
                   6202: }
                   6203: 
1.423     albertel 6204: =pod
                   6205: 
                   6206: =item scantron_put_line
                   6207: 
1.424     albertel 6208:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6209:     data file.
                   6210: 
                   6211:  Arguments:
                   6212:     $scanlines - hash ref that looks like the first return value from
                   6213:                  &scantron_getfile()
                   6214:     $scan_data - hash ref that looks like the second return value from
                   6215:                  &scantron_getfile()
                   6216:     $i         - line number to update
                   6217:     $newline   - contents of the updated scanline
                   6218:     $skip      - if true make the line for skipping and update the
                   6219:                  'skipped' file
                   6220: 
1.423     albertel 6221: =cut
                   6222: 
1.157     albertel 6223: sub scantron_put_line {
1.200     albertel 6224:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6225:     if ($skip) {
                   6226: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6227: 	&start_skipping($scan_data,$i);
1.157     albertel 6228: 	return;
                   6229:     }
                   6230:     $scanlines->{'corrected'}[$i]=$newline;
                   6231: }
                   6232: 
1.423     albertel 6233: =pod
                   6234: 
                   6235: =item scantron_clear_skip
                   6236: 
1.424     albertel 6237:    Remove a line from the 'skipped' file
                   6238: 
                   6239:  Arguments:
                   6240:     $scanlines - hash ref that looks like the first return value from
                   6241:                  &scantron_getfile()
                   6242:     $scan_data - hash ref that looks like the second return value from
                   6243:                  &scantron_getfile()
                   6244:     $i         - line number to update
                   6245: 
1.423     albertel 6246: =cut
                   6247: 
1.376     albertel 6248: sub scantron_clear_skip {
                   6249:     my ($scanlines,$scan_data,$i)=@_;
                   6250:     if (exists($scanlines->{'skipped'}[$i])) {
                   6251: 	undef($scanlines->{'skipped'}[$i]);
                   6252: 	return 1;
                   6253:     }
                   6254:     return 0;
                   6255: }
                   6256: 
1.423     albertel 6257: =pod
                   6258: 
                   6259: =item scantron_filter_not_exam
                   6260: 
1.424     albertel 6261:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6262:    filter out resources that are not marked as 'exam' mode
                   6263: 
1.423     albertel 6264: =cut
                   6265: 
1.334     albertel 6266: sub scantron_filter_not_exam {
                   6267:     my ($curres)=@_;
                   6268:     
                   6269:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6270: 	# if the user has asked to not have either hidden
                   6271: 	# or 'randomout' controlled resources to be graded
                   6272: 	# don't include them
                   6273: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6274: 	    && $curres->randomout) {
                   6275: 	    return 0;
                   6276: 	}
                   6277: 	return 1;
                   6278:     }
                   6279:     return 0;
                   6280: }
                   6281: 
1.423     albertel 6282: =pod
                   6283: 
                   6284: =item scantron_validate_sequence
                   6285: 
1.424     albertel 6286:     Validates the selected sequence, checking for resource that are
                   6287:     not set to exam mode.
                   6288: 
1.423     albertel 6289: =cut
                   6290: 
1.334     albertel 6291: sub scantron_validate_sequence {
                   6292:     my ($r,$currentphase) = @_;
                   6293: 
                   6294:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6295:     my (undef,undef,$sequence)=
                   6296: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6297: 
                   6298:     my $map=$navmap->getResourceByUrl($sequence);
                   6299: 
                   6300:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6301:                                     value="ignore" />');
                   6302:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6303: 	my @resources=
                   6304: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6305: 	if (@resources) {
1.357     banghart 6306: 	    $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 6307: 	    return (1,$currentphase);
                   6308: 	}
                   6309:     }
                   6310: 
                   6311:     return (0,$currentphase+1);
                   6312: }
                   6313: 
1.423     albertel 6314: =pod
                   6315: 
                   6316: =item scantron_validate_ID
                   6317: 
1.424     albertel 6318:    Validates all scanlines in the selected file to not have any
                   6319:    invalid or underspecified student IDs
                   6320: 
1.423     albertel 6321: =cut
                   6322: 
1.157     albertel 6323: sub scantron_validate_ID {
                   6324:     my ($r,$currentphase) = @_;
                   6325:     
                   6326:     #get student info
                   6327:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6328:     my %idmap=&username_to_idmap($classlist);
                   6329: 
                   6330:     #get scantron line setup
1.257     albertel 6331:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6332:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6333:     
                   6334:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6335: 
                   6336:     my %found=('ids'=>{},'usernames'=>{});
                   6337:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6338: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6339: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6340: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6341: 						 $scan_data);
                   6342: 	my $id=$$scan_record{'scantron.ID'};
                   6343: 	my $found;
                   6344: 	foreach my $checkid (keys(%idmap)) {
                   6345: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6346: 	}
                   6347: 	if ($found) {
                   6348: 	    my $username=$idmap{$found};
                   6349: 	    if ($found{'ids'}{$found}) {
                   6350: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6351: 					 $line,'duplicateID',$found);
1.194     albertel 6352: 		return(1,$currentphase);
1.157     albertel 6353: 	    } elsif ($found{'usernames'}{$username}) {
                   6354: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6355: 					 $line,'duplicateID',$username);
1.194     albertel 6356: 		return(1,$currentphase);
1.157     albertel 6357: 	    }
1.186     albertel 6358: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6359: 	    $found{'ids'}{$found}++;
                   6360: 	    $found{'usernames'}{$username}++;
                   6361: 	} else {
                   6362: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6363: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6364: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6365: 		    &scantron_get_correction($r,$i,$scan_record,
                   6366: 					     \%scantron_config,
                   6367: 					     $line,'duplicateID',$username);
1.194     albertel 6368: 		    return(1,$currentphase);
1.157     albertel 6369: 		} elsif (!defined($username)) {
                   6370: 		    &scantron_get_correction($r,$i,$scan_record,
                   6371: 					     \%scantron_config,
                   6372: 					     $line,'incorrectID');
1.194     albertel 6373: 		    return(1,$currentphase);
1.157     albertel 6374: 		}
                   6375: 		$found{'usernames'}{$username}++;
                   6376: 	    } else {
                   6377: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6378: 					 $line,'incorrectID');
1.194     albertel 6379: 		return(1,$currentphase);
1.157     albertel 6380: 	    }
                   6381: 	}
                   6382:     }
                   6383: 
                   6384:     return (0,$currentphase+1);
                   6385: }
                   6386: 
1.423     albertel 6387: =pod
                   6388: 
                   6389: =item scantron_get_correction
                   6390: 
1.424     albertel 6391:    Builds the interface screen to interact with the operator to fix a
                   6392:    specific error condition in a specific scanline
                   6393: 
                   6394:  Arguments:
                   6395:     $r           - Apache request object
                   6396:     $i           - number of the current scanline
                   6397:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6398:     $scan_config - hash ref as returned from &get_scantron_config()
                   6399:     $line        - full contents of the current scanline
                   6400:     $error       - error condition, valid values are
                   6401:                    'incorrectCODE', 'duplicateCODE',
                   6402:                    'doublebubble', 'missingbubble',
                   6403:                    'duplicateID', 'incorrectID'
                   6404:     $arg         - extra information needed
                   6405:        For errors:
                   6406:          - duplicateID   - paper number that this studentID was seen before on
                   6407:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6408:                            seen on before
                   6409:          - incorrectCODE - current incorrect CODE 
                   6410:          - doublebubble  - array ref of the bubble lines that have double
                   6411:                            bubble errors
                   6412:          - missingbubble - array ref of the bubble lines that have missing
                   6413:                            bubble errors
                   6414: 
1.423     albertel 6415: =cut
                   6416: 
1.157     albertel 6417: sub scantron_get_correction {
                   6418:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6419: 
1.454     banghart 6420: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6421: #to show both the current line and the previous one and allow skipping
                   6422: #the previous one or the current one
                   6423: 
1.161     albertel 6424:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6425:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6426: 	$r->print(" for PaperID <tt>".
                   6427: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6428:     } else {
                   6429: 	$r->print(" in scanline $i <pre>".
                   6430: 		  $line."</pre> \n");
                   6431:     }
1.242     albertel 6432:     my $message="<p>The ID on the form is  <tt>".
                   6433: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6434: 	"The name on the paper is ".
                   6435: 	$$scan_record{'scantron.LastName'}.",".
                   6436: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6437: 
1.157     albertel 6438:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6439:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6440:     if ($error =~ /ID$/) {
1.186     albertel 6441: 	if ($error eq 'incorrectID') {
1.157     albertel 6442: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6443: 	} elsif ($error eq 'duplicateID') {
                   6444: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6445: 	}
1.242     albertel 6446: 	$r->print($message);
1.157     albertel 6447: 	$r->print("<p>How should I handle this? <br /> \n");
                   6448: 	$r->print("\n<ul><li> ");
                   6449: 	#FIXME it would be nice if this sent back the user ID and
                   6450: 	#could do partial userID matches
                   6451: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6452: 				       'scantron_username','scantron_domain'));
                   6453: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6454: 	$r->print("\n@".
1.257     albertel 6455: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6456: 
                   6457: 	$r->print('</li>');
1.186     albertel 6458:     } elsif ($error =~ /CODE$/) {
                   6459: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6460: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6461: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6462: 	    $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 6463: 	}
1.224     albertel 6464: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6465: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6466: 	$r->print($message);
1.186     albertel 6467: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6468: 	$r->print("\n<br /> ");
1.194     albertel 6469: 	my $i=0;
1.273     albertel 6470: 	if ($error eq 'incorrectCODE' 
                   6471: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6472: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6473: 	    if ($closest > 0) {
                   6474: 		foreach my $testcode (@{$closest}) {
                   6475: 		    my $checked='';
1.401     albertel 6476: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6477: 		    $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' />");
                   6478: 		    $r->print("\n<br />");
                   6479: 		    $i++;
                   6480: 		}
1.194     albertel 6481: 	    }
                   6482: 	}
1.273     albertel 6483: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6484: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6485: 	    $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>");
                   6486: 	    $r->print("\n<br />");
                   6487: 	}
1.194     albertel 6488: 
1.188     albertel 6489: 	$r->print(<<ENDSCRIPT);
                   6490: <script type="text/javascript">
                   6491: function change_radio(field) {
1.190     albertel 6492:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6493:     var i;
                   6494:     for (i=0;i<slct.length;i++) {
                   6495:         if (slct[i].value==field) { slct[i].checked=true; }
                   6496:     }
                   6497: }
                   6498: </script>
                   6499: ENDSCRIPT
1.187     albertel 6500: 	my $href="/adm/pickcode?".
1.359     www      6501: 	   "form=".&escape("scantronupload").
                   6502: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6503: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6504: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6505: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6506: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6507: 	    $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')\" />");
                   6508: 	    $r->print("\n<br />");
                   6509: 	}
1.272     albertel 6510: 	$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 6511: 	$r->print("\n<br /><br />");
1.157     albertel 6512:     } elsif ($error eq 'doublebubble') {
                   6513: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6514: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6515: 		  join(',',@{$arg}).'" />');
1.242     albertel 6516: 	$r->print($message);
1.157     albertel 6517: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6518: 	foreach my $question (@{$arg}) {
1.447     foxr     6519: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.461     foxr     6520: 	    my @select_array = split(/:/,$selected);
1.422     foxr     6521: 	    &scantron_bubble_selector($r,$scan_config,$question,
1.460     foxr     6522: 				      @select_array);
1.157     albertel 6523: 	}
                   6524:     } elsif ($error eq 'missingbubble') {
                   6525: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6526: 	$r->print($message);
1.157     albertel 6527: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6528: 	$r->print("Some questions have no scanned bubbles\n");
                   6529: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6530: 		  join(',',@{$arg}).'" />');
                   6531: 	foreach my $question (@{$arg}) {
1.448     foxr     6532: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.470     foxr     6533: 	    my @select_array = split(/:/,$selected); # ought to be an array of empties.
                   6534: 	    &scantron_bubble_selector($r,$scan_config,$question, @select_array);
1.157     albertel 6535: 	}
                   6536:     } else {
                   6537: 	$r->print("\n<ul>");
                   6538:     }
                   6539:     $r->print("\n</li></ul>");
                   6540: 
                   6541: }
1.423     albertel 6542: 
                   6543: =pod
                   6544: 
                   6545: =item scantron_bubble_selector
                   6546:   
                   6547:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6548:    possibly showing the existing the selected bubbles if known
1.423     albertel 6549: 
                   6550:  Arguments:
                   6551:     $r           - Apache request object
                   6552:     $scan_config - hash from &get_scantron_config()
                   6553:     $quest       - number of the bubble line to make a corrector for
1.470     foxr     6554:     @lines       - array of answer lines.
1.423     albertel 6555: 
                   6556: =cut
                   6557: 
1.157     albertel 6558: sub scantron_bubble_selector {
1.461     foxr     6559:     my ($r,$scan_config,$quest,@lines)=@_;
1.157     albertel 6560:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6561: 
1.461     foxr     6562: 
1.274     albertel 6563:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6564: 
1.461     foxr     6565:     my $bubble_length = scalar(@lines);
1.460     foxr     6566: 
1.447     foxr     6567: 
1.274     albertel 6568:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6569: 
1.448     foxr     6570:     my $response = $quest-1;
                   6571:     my $lines = $bubble_lines_per_response{$response};
1.447     foxr     6572: 
1.422     foxr     6573:     my $total_lines = $lines*2;
1.157     albertel 6574:     my @alphabet=('A'..'Z');
1.479     foxr     6575: 
1.422     foxr     6576:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6577: 
                   6578:     for (my $l = 0; $l < $lines; $l++) {
                   6579: 	if ($l != 0) {
                   6580: 	    $r->print('<tr>');
                   6581: 	}
1.462     foxr     6582: 	my @selected = split(//,$lines[$l]);
1.422     foxr     6583: 	for (my $i=0;$i<$max;$i++) {
                   6584: 	    $r->print("\n".'<td align="center">');
                   6585: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6586: 		$r->print('X'); 
                   6587: 		shift(@selected) ;
                   6588: 	    } else { 
                   6589: 		$r->print('&nbsp;'); 
                   6590: 	    }
                   6591: 	    $r->print('</td>');
                   6592: 	    
                   6593: 	}
                   6594: 
                   6595: 	if ($l == 0) {
                   6596: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6597: 
                   6598: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6599: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6600: 	
                   6601: 	}
                   6602: 
                   6603: 	$r->print('</tr><tr>');
                   6604: 
                   6605: 	# FIXME: This may have to be a bit more clever for
                   6606: 	#        multiline questions (different values e.g..).
                   6607: 
                   6608: 	for (my $i=0;$i<$max;$i++) {
1.479     foxr     6609: 	    my $value = "$l:$i";	# Relative bubble line #: Bubble in line.
1.422     foxr     6610: 	    $r->print("\n".
                   6611: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
1.479     foxr     6612: 		      $quest.'" value="'.$value.'" />'.$alphabet[$i]."</label></td>");
1.422     foxr     6613: 	}
                   6614: 	$r->print('</tr>');
                   6615: 
                   6616: 	    
1.157     albertel 6617:     }
1.422     foxr     6618:     $r->print('</table>');
1.157     albertel 6619: }
                   6620: 
1.423     albertel 6621: =pod
                   6622: 
                   6623: =item num_matches
                   6624: 
1.424     albertel 6625:    Counts the number of characters that are the same between the two arguments.
                   6626: 
                   6627:  Arguments:
                   6628:    $orig - CODE from the scanline
                   6629:    $code - CODE to match against
                   6630: 
                   6631:  Returns:
                   6632:    $count - integer count of the number of same characters between the
                   6633:             two arguments
                   6634: 
1.423     albertel 6635: =cut
                   6636: 
1.194     albertel 6637: sub num_matches {
                   6638:     my ($orig,$code) = @_;
                   6639:     my @code=split(//,$code);
                   6640:     my @orig=split(//,$orig);
                   6641:     my $same=0;
                   6642:     for (my $i=0;$i<scalar(@code);$i++) {
                   6643: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6644:     }
                   6645:     return $same;
                   6646: }
                   6647: 
1.423     albertel 6648: =pod
                   6649: 
                   6650: =item scantron_get_closely_matching_CODEs
                   6651: 
1.424     albertel 6652:    Cycles through all CODEs and finds the set that has the greatest
                   6653:    number of same characters as the provided CODE
                   6654: 
                   6655:  Arguments:
                   6656:    $allcodes - hash ref returned by &get_codes()
                   6657:    $CODE     - CODE from the current scanline
                   6658: 
                   6659:  Returns:
                   6660:    2 element list
                   6661:     - first elements is number of how closely matching the best fit is 
                   6662:       (5 means best set has 5 matching characters)
                   6663:     - second element is an arrary ref containing the set of valid CODEs
                   6664:       that best fit the passed in CODE
                   6665: 
1.423     albertel 6666: =cut
                   6667: 
1.194     albertel 6668: sub scantron_get_closely_matching_CODEs {
                   6669:     my ($allcodes,$CODE)=@_;
                   6670:     my @CODEs;
                   6671:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6672: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6673:     }
                   6674: 
                   6675:     return ($#CODEs,$CODEs[-1]);
                   6676: }
                   6677: 
1.423     albertel 6678: =pod
                   6679: 
                   6680: =item get_codes
                   6681: 
1.424     albertel 6682:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6683:    set of remembered CODEs.
                   6684: 
                   6685:  Arguments:
                   6686:   $old_name - name of the set of remembered CODEs
                   6687:   $cdom     - domain of the course
                   6688:   $cnum     - internal course name
                   6689: 
                   6690:  Returns:
                   6691:   %allcodes - keys are the valid CODEs, values are all 1
                   6692: 
1.423     albertel 6693: =cut
                   6694: 
1.194     albertel 6695: sub get_codes {
1.280     foxr     6696:     my ($old_name, $cdom, $cnum) = @_;
                   6697:     if (!$old_name) {
                   6698: 	$old_name=$env{'form.scantron_CODElist'};
                   6699:     }
                   6700:     if (!$cdom) {
                   6701: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6702:     }
                   6703:     if (!$cnum) {
                   6704: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6705:     }
1.278     albertel 6706:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6707: 				    $cdom,$cnum);
                   6708:     my %allcodes;
                   6709:     if ($result{"type\0$old_name"} eq 'number') {
                   6710: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6711:     } else {
                   6712: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6713:     }
1.194     albertel 6714:     return %allcodes;
                   6715: }
                   6716: 
1.423     albertel 6717: =pod
                   6718: 
                   6719: =item scantron_validate_CODE
                   6720: 
1.424     albertel 6721:    Validates all scanlines in the selected file to not have any
                   6722:    invalid or underspecified CODEs and that none of the codes are
                   6723:    duplicated if this was requested.
                   6724: 
1.423     albertel 6725: =cut
                   6726: 
1.157     albertel 6727: sub scantron_validate_CODE {
                   6728:     my ($r,$currentphase) = @_;
1.257     albertel 6729:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6730:     if ($scantron_config{'CODElocation'} &&
                   6731: 	$scantron_config{'CODEstart'} &&
                   6732: 	$scantron_config{'CODElength'}) {
1.257     albertel 6733: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6734: 	    &FIXME_blow_up()
                   6735: 	}
                   6736:     } else {
                   6737: 	return (0,$currentphase+1);
                   6738:     }
                   6739:     
                   6740:     my %usedCODEs;
                   6741: 
1.194     albertel 6742:     my %allcodes=&get_codes();
1.186     albertel 6743: 
1.447     foxr     6744:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6745: 
1.186     albertel 6746:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6747:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6748: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6749: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6750: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6751: 						 $scan_data);
                   6752: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6753: 	my $error=0;
1.224     albertel 6754: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6755: 	    &scantron_get_correction($r,$i,$scan_record,
                   6756: 				     \%scantron_config,
                   6757: 				     $line,'incorrectCODE',\%allcodes);
                   6758: 	    return(1,$currentphase);
                   6759: 	}
1.221     albertel 6760: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6761: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6762: 	    &scantron_get_correction($r,$i,$scan_record,
                   6763: 				     \%scantron_config,
1.194     albertel 6764: 				     $line,'incorrectCODE',\%allcodes);
                   6765: 	    return(1,$currentphase);
1.186     albertel 6766: 	}
1.214     albertel 6767: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6768: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6769: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6770: 	    &scantron_get_correction($r,$i,$scan_record,
                   6771: 				     \%scantron_config,
1.194     albertel 6772: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6773: 	    return(1,$currentphase);
1.186     albertel 6774: 	}
1.194     albertel 6775: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6776:     }
1.157     albertel 6777:     return (0,$currentphase+1);
                   6778: }
                   6779: 
1.423     albertel 6780: =pod
                   6781: 
                   6782: =item scantron_validate_doublebubble
                   6783: 
1.424     albertel 6784:    Validates all scanlines in the selected file to not have any
                   6785:    bubble lines with multiple bubbles marked.
                   6786: 
1.423     albertel 6787: =cut
                   6788: 
1.157     albertel 6789: sub scantron_validate_doublebubble {
                   6790:     my ($r,$currentphase) = @_;
                   6791:     #get student info
                   6792:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6793:     my %idmap=&username_to_idmap($classlist);
                   6794: 
                   6795:     #get scantron line setup
1.257     albertel 6796:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6797:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6798: 
                   6799:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6800: 
1.157     albertel 6801:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6802: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6803: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6804: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6805: 						 $scan_data);
                   6806: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6807: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6808: 				 'doublebubble',
                   6809: 				 $$scan_record{'scantron.doubleerror'});
                   6810:     	return (1,$currentphase);
                   6811:     }
                   6812:     return (0,$currentphase+1);
                   6813: }
                   6814: 
1.423     albertel 6815: =pod
                   6816: 
                   6817: =item scantron_get_maxbubble
                   6818: 
1.424     albertel 6819:    Returns the maximum number of bubble lines that are expected to
                   6820:    occur. Does this by walking the selected sequence rendering the
                   6821:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6822:    for what the current value of the problem counter is.
                   6823: 
1.447     foxr     6824:    Caches the results to $env{'form.scantron_maxbubble'},
                   6825:    $env{'form.scantron.bubble_lines.n'} and 
                   6826:    $env{'form.scantron.first_bubble_line.n'}
                   6827:    which are the total number of bubble, lines, the number of bubble
                   6828:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6829: 
1.423     albertel 6830: =cut
                   6831: 
1.330     albertel 6832: sub scantron_get_maxbubble {    
1.257     albertel 6833:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6834: 	$env{'form.scantron_maxbubble'}) {
1.447     foxr     6835: 	&restore_bubble_lines();
1.257     albertel 6836: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6837:     }
1.330     albertel 6838: 
1.447     foxr     6839:     my (undef, undef, $sequence) =
1.257     albertel 6840: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6841: 
1.447     foxr     6842:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6843:     my $map=$navmap->getResourceByUrl($sequence);
                   6844:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6845: 
                   6846:     &Apache::lonxml::clear_problem_counter();
                   6847: 
1.435     foxr     6848:     my $uname       = $env{'form.student'};
                   6849:     my $udom        = $env{'form.userdom'};
                   6850:     my $cid         = $env{'request.course.id'};
                   6851:     my $total_lines = 0;
                   6852:     %bubble_lines_per_response = ();
1.447     foxr     6853:     %first_bubble_line         = ();
1.435     foxr     6854: 
1.447     foxr     6855:   
                   6856:     my $response_number = 0;
                   6857:     my $bubble_line     = 0;
1.191     albertel 6858:     foreach my $resource (@resources) {
1.435     foxr     6859: 	my $symb = $resource->symb();
1.447     foxr     6860: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6861: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6862: 					('symb' => $resource->symb()),
                   6863: 					('grade_target' => 'analyze'),
                   6864: 					('grade_courseid' => $cid),
                   6865: 					('grade_domain' => $udom),
                   6866: 					('grade_username' => $uname));
1.436     albertel 6867: 	my (undef, $an) =
1.435     foxr     6868: 	    split(/_HASH_REF__/,$result, 2);
                   6869: 
                   6870: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6871: 
                   6872: 
                   6873: 
                   6874: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6875: 
1.460     foxr     6876: 
                   6877: 	    my $lines = $analysis{"$part_id.bubble_lines"};;
1.447     foxr     6878: 
                   6879: 	    # TODO - make this a persistent hash not an array.
                   6880: 
                   6881: 
                   6882: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6883: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6884: 	    $response_number++;
                   6885: 
                   6886: 	    $bubble_line +=  $lines;
                   6887: 	    $total_lines +=  $lines;
1.435     foxr     6888: 	}
                   6889: 
1.191     albertel 6890:     }
                   6891:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6892: 
                   6893:     &save_bubble_lines();
1.330     albertel 6894:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6895: 	$total_lines;
1.257     albertel 6896:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6897: }
                   6898: 
1.423     albertel 6899: =pod
                   6900: 
                   6901: =item scantron_validate_missingbubbles
                   6902: 
1.424     albertel 6903:    Validates all scanlines in the selected file to not have any
1.447     foxr     6904:     answers that don't have bubbles that have not been verified
                   6905:     to be bubble free.
1.424     albertel 6906: 
1.423     albertel 6907: =cut
                   6908: 
1.157     albertel 6909: sub scantron_validate_missingbubbles {
                   6910:     my ($r,$currentphase) = @_;
                   6911:     #get student info
                   6912:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6913:     my %idmap=&username_to_idmap($classlist);
                   6914: 
                   6915:     #get scantron line setup
1.257     albertel 6916:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6917:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6918:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6919:     if (!$max_bubble) { $max_bubble=2**31; }
                   6920:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6921: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6922: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6923: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6924: 						 $scan_data);
                   6925: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6926: 	my @to_correct;
1.470     foxr     6927: 	
                   6928: 	# Probably here's where the error is...
                   6929: 
1.157     albertel 6930: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6931: 	    if ($missing > $max_bubble) { next; }
                   6932: 	    push(@to_correct,$missing);
                   6933: 	}
                   6934: 	if (@to_correct) {
                   6935: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6936: 				     $line,'missingbubble',\@to_correct);
                   6937: 	    return (1,$currentphase);
                   6938: 	}
                   6939: 
                   6940:     }
                   6941:     return (0,$currentphase+1);
                   6942: }
                   6943: 
1.423     albertel 6944: =pod
                   6945: 
                   6946: =item scantron_process_students
                   6947: 
                   6948:    Routine that does the actual grading of the bubble sheet information.
                   6949: 
                   6950:    The parsed scanline hash is added to %env 
                   6951: 
                   6952:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6953:    foreach resource , with the form data of
                   6954: 
                   6955: 	'submitted'     =>'scantron' 
                   6956: 	'grade_target'  =>'grade',
                   6957: 	'grade_username'=> username of student
                   6958: 	'grade_domain'  => domain of student
                   6959: 	'grade_courseid'=> of course
                   6960: 	'grade_symb'    => symb of resource to grade
                   6961: 
                   6962:     This triggers a grading pass. The problem grading code takes care
                   6963:     of converting the bubbled letter information (now in %env) into a
                   6964:     valid submission.
                   6965: 
                   6966: =cut
                   6967: 
1.82      albertel 6968: sub scantron_process_students {
1.75      albertel 6969:     my ($r) = @_;
1.257     albertel 6970:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6971:     my ($symb)=&get_symb($r);
1.81      albertel 6972:     if (!$symb) {return '';}
1.324     albertel 6973:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6974: 
1.257     albertel 6975:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6976:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6977:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6978:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6979:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6980:     my $map=$navmap->getResourceByUrl($sequence);
                   6981:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6982: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6983:     my $result= <<SCANTRONFORM;
1.81      albertel 6984: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6985:   <input type="hidden" name="command" value="scantron_configphase" />
                   6986:   $default_form_data
                   6987: SCANTRONFORM
1.82      albertel 6988:     $r->print($result);
                   6989: 
                   6990:     my @delayqueue;
1.140     albertel 6991:     my %completedstudents;
                   6992:     
1.200     albertel 6993:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6994:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6995:  				    'Scantron Progress',$count,
1.195     albertel 6996: 				    'inline',undef,'scantronupload');
1.140     albertel 6997:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6998: 					  'Processing first student');
                   6999:     my $start=&Time::HiRes::time();
1.158     albertel 7000:     my $i=-1;
1.200     albertel 7001:     my ($uname,$udom,$started);
1.447     foxr     7002: 
                   7003:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   7004: 
1.157     albertel 7005:     while ($i<$scanlines->{'count'}) {
                   7006:  	($uname,$udom)=('','');
                   7007:  	$i++;
1.200     albertel 7008:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 7009:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 7010: 	if ($started) {
                   7011: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   7012: 						     'last student');
                   7013: 	}
                   7014: 	$started=1;
1.157     albertel 7015:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   7016:  						 $scan_data);
                   7017:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   7018:  					      \%idmap,$i)) {
                   7019:   	    &scantron_add_delay(\@delayqueue,$line,
                   7020:  				'Unable to find a student that matches',1);
                   7021:  	    next;
                   7022:   	}
                   7023:  	if (exists $completedstudents{$uname}) {
                   7024:  	    &scantron_add_delay(\@delayqueue,$line,
                   7025:  				'Student '.$uname.' has multiple sheets',2);
                   7026:  	    next;
                   7027:  	}
                   7028:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 7029: 
                   7030: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 7031:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 7032: 
                   7033: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   7034: 	    &scantron_putfile($scanlines,$scan_data);
                   7035: 	}
1.161     albertel 7036: 	
                   7037: 	my $i=0;
1.83      albertel 7038: 	foreach my $resource (@resources) {
1.85      albertel 7039: 	    $i++;
1.193     albertel 7040: 	    my %form=('submitted'     =>'scantron',
                   7041: 		      'grade_target'  =>'grade',
                   7042: 		      'grade_username'=>$uname,
                   7043: 		      'grade_domain'  =>$udom,
1.257     albertel 7044: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 7045: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 7046: 	    if (exists($scan_record->{'scantron.CODE'})
                   7047: 		&& 
                   7048: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 7049: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 7050: 	    } else {
                   7051: 		$form{'CODE'}='';
1.193     albertel 7052: 	    }
                   7053: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 7054: 	    if ($result ne '') {
                   7055: 	    }
1.213     albertel 7056: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 7057: 	}
1.140     albertel 7058: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 7059: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 7060:     } continue {
1.330     albertel 7061: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 7062: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 7063:     }
1.140     albertel 7064:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 7065: #    my $lasttime = &Time::HiRes::time()-$start;
                   7066: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 7067: 
1.200     albertel 7068:     $r->print("</form>");
1.324     albertel 7069:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 7070:     return '';
1.75      albertel 7071: }
1.157     albertel 7072: 
1.423     albertel 7073: =pod
                   7074: 
                   7075: =item scantron_upload_scantron_data
                   7076: 
                   7077:     Creates the screen for adding a new bubble sheet data file to a course.
                   7078: 
                   7079: =cut
                   7080: 
1.157     albertel 7081: sub scantron_upload_scantron_data {
                   7082:     my ($r)=@_;
1.257     albertel 7083:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 7084:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 7085: 							  'domainid',
                   7086: 							  'coursename');
1.257     albertel 7087:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 7088: 						   'domainid');
1.324     albertel 7089:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 7090:     $r->print(<<UPLOAD);
                   7091: <script type="text/javascript" language="javascript">
                   7092:     function checkUpload(formname) {
                   7093: 	if (formname.upfile.value == "") {
                   7094: 	    alert("Please use the browse button to select a file from your local directory.");
                   7095: 	    return false;
                   7096: 	}
                   7097: 	formname.submit();
                   7098:     }
                   7099: </script>
                   7100: 
                   7101: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7102: $default_form_data
1.181     albertel 7103: <table>
                   7104: <tr><td>$select_link </td></tr>
                   7105: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7106: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7107: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7108: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7109: </table>
1.157     albertel 7110: <input name='command' value='scantronupload_save' type='hidden' />
                   7111: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7112: </form>
                   7113: UPLOAD
                   7114:     return '';
                   7115: }
                   7116: 
1.423     albertel 7117: =pod
                   7118: 
                   7119: =item scantron_upload_scantron_data_save
                   7120: 
                   7121:    Adds a provided bubble information data file to the course if user
                   7122:    has the correct privileges to do so.  
                   7123: 
                   7124: =cut
                   7125: 
1.157     albertel 7126: sub scantron_upload_scantron_data_save {
                   7127:     my($r)=@_;
1.324     albertel 7128:     my ($symb)=&get_symb($r,1);
1.182     albertel 7129:     my $doanotherupload=
                   7130: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7131: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7132: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7133: 	'</form>'."\n";
1.257     albertel 7134:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7135: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7136: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7137: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7138: 	if ($symb) {
1.324     albertel 7139: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7140: 	} else {
                   7141: 	    $r->print($doanotherupload);
                   7142: 	}
1.162     albertel 7143: 	return '';
                   7144:     }
1.257     albertel 7145:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7146:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7147:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7148:     #FIXME
                   7149:     #copied from lonnet::userfileupload()
                   7150:     #make that function able to target a specified course
                   7151:     # Replace Windows backslashes by forward slashes
                   7152:     $fname=~s/\\/\//g;
                   7153:     # Get rid of everything but the actual filename
                   7154:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7155:     # Replace spaces by underscores
                   7156:     $fname=~s/\s+/\_/g;
                   7157:     # Replace all other weird characters by nothing
                   7158:     $fname=~s/[^\w\.\-]//g;
                   7159:     # See if there is anything left
                   7160:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7161:     my $uploadedfile=$fname;
1.157     albertel 7162:     $fname='scantron_orig_'.$fname;
1.257     albertel 7163:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7164: 	$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 7165:     } else {
1.275     albertel 7166: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7167: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7168: 	    $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 7169: 	} else {
1.398     albertel 7170: 	    $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 7171: 	}
                   7172:     }
1.174     albertel 7173:     if ($symb) {
1.209     ng       7174: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7175:     } else {
1.182     albertel 7176: 	$r->print($doanotherupload);
1.174     albertel 7177:     }
1.157     albertel 7178:     return '';
                   7179: }
                   7180: 
1.423     albertel 7181: =pod
                   7182: 
                   7183: =item valid_file
                   7184: 
1.424     albertel 7185:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7186: 
                   7187: =cut
                   7188: 
1.202     albertel 7189: sub valid_file {
                   7190:     my ($requested_file)=@_;
                   7191:     foreach my $filename (sort(&scantron_filenames())) {
                   7192: 	if ($requested_file eq $filename) { return 1; }
                   7193:     }
                   7194:     return 0;
                   7195: }
                   7196: 
1.423     albertel 7197: =pod
                   7198: 
                   7199: =item scantron_download_scantron_data
                   7200: 
                   7201:    Shows a list of the three internal files (original, corrected,
                   7202:    skipped) for a specific bubble sheet data file that exists in the
                   7203:    course.
                   7204: 
                   7205: =cut
                   7206: 
1.202     albertel 7207: sub scantron_download_scantron_data {
                   7208:     my ($r)=@_;
1.324     albertel 7209:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7210:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7211:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7212:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7213:     if (! &valid_file($file)) {
                   7214: 	$r->print(<<ERROR);
                   7215: 	<p>
                   7216: 	    The requested file name was invalid.
                   7217:         </p>
                   7218: ERROR
1.324     albertel 7219: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7220: 	return;
                   7221:     }
                   7222:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7223:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7224:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7225:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7226:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7227:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7228:     $r->print(<<DOWNLOAD);
                   7229:     <p>
                   7230: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7231:     </p>
                   7232:     <p>
                   7233: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7234:     </p>
                   7235:     <p>
                   7236: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7237:     </p>
                   7238: DOWNLOAD
1.324     albertel 7239:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7240:     return '';
                   7241: }
1.157     albertel 7242: 
1.423     albertel 7243: =pod
                   7244: 
                   7245: =back
                   7246: 
                   7247: =cut
                   7248: 
1.75      albertel 7249: #-------- end of section for handling grading scantron forms -------
                   7250: #
                   7251: #-------------------------------------------------------------------
                   7252: 
1.72      ng       7253: #-------------------------- Menu interface -------------------------
                   7254: #
                   7255: #--- Show a Grading Menu button - Calls the next routine ---
                   7256: sub show_grading_menu_form {
1.324     albertel 7257:     my ($symb)=@_;
1.125     ng       7258:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7259: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7260: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7261: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
1.478     albertel 7262: 	'<input type="submit" name="submit" value="'.&mt('Grading Menu').'" />'."\n".
1.72      ng       7263: 	'</form>'."\n";
                   7264:     return $result;
                   7265: }
                   7266: 
1.77      ng       7267: # -- Retrieve choices for grading form
                   7268: sub savedState {
                   7269:     my %savedState = ();
1.257     albertel 7270:     if ($env{'form.saveState'}) {
                   7271: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7272: 	    my ($key,$value) = split(/=/,$_,2);
                   7273: 	    $savedState{$key} = $value;
                   7274: 	}
                   7275:     }
                   7276:     return \%savedState;
                   7277: }
1.76      ng       7278: 
1.443     banghart 7279: sub grading_menu {
                   7280:     my ($request) = @_;
                   7281:     my ($symb)=&get_symb($request);
                   7282:     if (!$symb) {return '';}
                   7283:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7284:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7285: 
1.444     banghart 7286:     $request->print($table);
1.443     banghart 7287:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7288:                   'handgrade'=>$hdgrade,
                   7289:                   'probTitle'=>$probTitle,
                   7290:                   'command'=>'submit_options',
                   7291:                   'saveState'=>"",
                   7292:                   'gradingMenu'=>1,
                   7293:                   'showgrading'=>"yes");
                   7294:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7295:     my @menu = ({ url => $url,
                   7296:                      name => &mt('Manual Grading/View Submissions'),
                   7297:                      short_description => 
                   7298:     &mt('Start the process of hand grading submissions.'),
                   7299:                  });
                   7300:     $fields{'command'} = 'csvform';
                   7301:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7302:     push (@menu, { url => $url,
                   7303:                    name => &mt('Upload Scores'),
                   7304:                    short_description => 
                   7305:             &mt('Specify a file containing the class scores for current resource.')});
                   7306:     $fields{'command'} = 'processclicker';
                   7307:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7308:     push (@menu, { url => $url,
                   7309:                    name => &mt('Process Clicker'),
                   7310:                    short_description => 
                   7311:             &mt('Specify a file containing the clicker information for this resource.')});
                   7312:     $fields{'command'} = 'scantron_selectphase';
                   7313:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7314:     push (@menu, { url => $url,
1.454     banghart 7315:                    name => &mt('Grade/Manage Scantron Forms'),
                   7316:                    short_description => 
                   7317:             &mt('')});
1.443     banghart 7318:     $fields{'command'} = 'verify';
                   7319:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7320:     push (@menu, { url => "",
1.443     banghart 7321:                    name => &mt('Verify Receipt'),
                   7322:                    short_description => 
                   7323:             &mt('')});
                   7324:     #
                   7325:     # Create the menu
                   7326:     my $Str;
1.444     banghart 7327:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7328:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7329:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7330:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7331: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
1.476     albertel 7332: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.445     banghart 7333: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7334: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7335: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7336: 
1.443     banghart 7337:     foreach my $menudata (@menu) {
1.445     banghart 7338:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7339:             $Str .='    <h3><a '.
                   7340:                 $menudata->{'jscript'}.
                   7341:                 ' href="'.
                   7342:                 $menudata->{'url'}.'" >'.
                   7343:                 $menudata->{'name'}."</a></h3>\n";
                   7344:         } else {
1.458     banghart 7345:             $Str .='    <h3><input type="button" value="Verify Receipt" '.
1.445     banghart 7346:                 $menudata->{'jscript'}.
1.458     banghart 7347:                 ' onClick="javascript:checkChoice(document.forms.gradingMenu,\'5\',\'verify\')" '.
                   7348:                 ' /></h3>';
1.446     banghart 7349:             $Str .= ('&nbsp;'x8).
                   7350:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7351:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7352:         }
1.443     banghart 7353:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7354:             "\n";
                   7355:     }
1.444     banghart 7356:     $Str .="</form>\n";
1.443     banghart 7357:     $request->print(<<GRADINGMENUJS);
                   7358: <script type="text/javascript" language="javascript">
                   7359:     function checkChoice(formname,val,cmdx) {
                   7360: 	if (val <= 2) {
                   7361: 	    var cmd = radioSelection(formname.radioChoice);
                   7362: 	    var cmdsave = cmd;
                   7363: 	} else {
                   7364: 	    cmd = cmdx;
                   7365: 	    cmdsave = 'submission';
                   7366: 	}
                   7367: 	formname.command.value = cmd;
                   7368: 	if (val < 5) formname.submit();
                   7369: 	if (val == 5) {
1.458     banghart 7370: 	    if (!checkReceiptNo(formname,'notOK')) { 
                   7371: 	        return false;
                   7372: 	    } else {
                   7373: 	        formname.submit();
                   7374: 	    }
1.445     banghart 7375: 	}
                   7376:     }
1.443     banghart 7377: 
                   7378:     function checkReceiptNo(formname,nospace) {
                   7379: 	var receiptNo = formname.receipt.value;
                   7380: 	var checkOpt = false;
                   7381: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7382: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7383: 	if (checkOpt) {
                   7384: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7385: 	    formname.receipt.value = "";
                   7386: 	    formname.receipt.focus();
                   7387: 	    return false;
                   7388: 	}
                   7389: 	return true;
                   7390:     }
                   7391: </script>
                   7392: GRADINGMENUJS
                   7393:     &commonJSfunctions($request);
                   7394:     return $Str;    
                   7395: }
                   7396: 
                   7397: 
                   7398: #--- Displays the submissions first page -------
                   7399: sub submit_options {
1.72      ng       7400:     my ($request) = @_;
1.324     albertel 7401:     my ($symb)=&get_symb($request);
1.72      ng       7402:     if (!$symb) {return '';}
1.76      ng       7403:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7404: 
                   7405:     $request->print(<<GRADINGMENUJS);
                   7406: <script type="text/javascript" language="javascript">
1.116     ng       7407:     function checkChoice(formname,val,cmdx) {
                   7408: 	if (val <= 2) {
                   7409: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7410: 	    var cmdsave = cmd;
1.116     ng       7411: 	} else {
                   7412: 	    cmd = cmdx;
1.118     ng       7413: 	    cmdsave = 'submission';
1.116     ng       7414: 	}
                   7415: 	formname.command.value = cmd;
1.118     ng       7416: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7417: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7418: 	if (val < 5) formname.submit();
                   7419: 	if (val == 5) {
1.72      ng       7420: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7421: 	    formname.submit();
                   7422: 	}
1.238     albertel 7423: 	if (val < 7) formname.submit();
1.72      ng       7424:     }
                   7425: 
                   7426:     function checkReceiptNo(formname,nospace) {
                   7427: 	var receiptNo = formname.receipt.value;
                   7428: 	var checkOpt = false;
                   7429: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7430: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7431: 	if (checkOpt) {
                   7432: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7433: 	    formname.receipt.value = "";
                   7434: 	    formname.receipt.focus();
                   7435: 	    return false;
                   7436: 	}
                   7437: 	return true;
                   7438:     }
                   7439: </script>
                   7440: GRADINGMENUJS
1.118     ng       7441:     &commonJSfunctions($request);
1.324     albertel 7442:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.473     albertel 7443:     my $result;
1.76      ng       7444:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7445:     my $savedState = &savedState();
1.118     ng       7446:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7447:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7448:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7449:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7450: 
                   7451:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7452: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7453: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7454: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7455: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7456: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7457: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7458: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7459: 
1.472     albertel 7460:     $result.='
                   7461:     <div class="LC_grade_select_mode">
1.473     albertel 7462:       <div class="LC_grade_select_mode_current">
                   7463:         <h2>
                   7464:           '.&mt('Grade Current Resource').'
                   7465:         </h2>
                   7466:         <div class="LC_grade_select_mode_body">
                   7467:           <div class="LC_grades_resource_info">
                   7468:            '.$table.'
                   7469:           </div>
                   7470:           <div class="LC_grade_select_mode_selector">
                   7471:              <div class="LC_grade_select_mode_selector_header">
                   7472:                 '.&mt('Sections').'
                   7473:              </div>
                   7474:              <div class="LC_grade_select_mode_selector_body">
                   7475: 	       <select name="section" multiple="multiple" size="5">'."\n";
1.116     ng       7476:     if (ref($sections)) {
1.472     albertel 7477: 	foreach my $section (sort (@$sections)) {
                   7478: 	    $result.='<option value="'.$section.'" '.
                   7479: 		($saveSec eq $section ? 'selected="selected"':'').'>'.$section.'</option>'."\n";
1.155     albertel 7480: 	}
1.116     ng       7481:     }
1.401     albertel 7482:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.472     albertel 7483:     $result.='
1.473     albertel 7484:              </div>
                   7485:           </div>
                   7486:           <div class="LC_grade_select_mode_selector">
                   7487:              <div class="LC_grade_select_mode_selector_header">
                   7488:                 '.&mt('Groups').'
                   7489:              </div>
                   7490:              <div class="LC_grade_select_mode_selector_body">
                   7491:                 '.&Apache::lonstatistics::GroupSelect('group','multiple',5).'
                   7492:              </div>
1.472     albertel 7493:           </div>
1.473     albertel 7494:           <div class="LC_grade_select_mode_selector">
                   7495:              <div class="LC_grade_select_mode_selector_header">
                   7496:                 '.&mt('Access Status').'
                   7497:              </div>
                   7498:              <div class="LC_grade_select_mode_selector_body">
                   7499:                 '.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,5,undef,'mult').'
                   7500:              </div>
1.472     albertel 7501:           </div>
1.473     albertel 7502:           <div class="LC_grade_select_mode_selector">
                   7503:              <div class="LC_grade_select_mode_selector_header">
                   7504:                 '.&mt('Submission Status').'
                   7505:              </div>
                   7506:              <div class="LC_grade_select_mode_selector_body">
                   7507:                <select name="submitonly" size="5">
                   7508: 	         <option value="yes" '.      ($saveSub eq 'yes'       ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>
                   7509: 	         <option value="queued" '.   ($saveSub eq 'queued'    ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>
                   7510: 	         <option value="graded" '.   ($saveSub eq 'graded'    ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>
                   7511: 	         <option value="incorrect" '.($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>
                   7512:                  <option value="all" '.      ($saveSub eq 'all'       ? 'selected="selected"' : '').'>'.&mt('with any status').'</option>
                   7513:                </select>
                   7514:              </div>
1.472     albertel 7515:           </div>
1.473     albertel 7516:           <div class="LC_grade_select_mode_type_body">
                   7517:             <div class="LC_grade_select_mode_type">
                   7518:               <label>
                   7519:                 <input type="radio" name="radioChoice" value="submission" '.
                   7520:                   ($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.
                   7521:              &mt('Select individual students to grade and view submissions.').'
                   7522: 	      </label> 
                   7523:             </div>
                   7524:             <div class="LC_grade_select_mode_type">
                   7525: 	      <label>
                   7526:                 <input type="radio" name="radioChoice" value="viewgrades" '.
                   7527:                   ($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
                   7528:                     &mt('Grade all selected students in a grading table.').'
                   7529:               </label>
                   7530:             </div>
                   7531:             <div class="LC_grade_select_mode_type">
                   7532: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7533:             </div>
1.472     albertel 7534:           </div>
1.473     albertel 7535:         </div>
                   7536:       </div>
                   7537:       <div class="LC_grade_select_mode_page">
                   7538:         <h2>
                   7539:          '.&mt('Grade Complete Folder for One Student').'
                   7540:         </h2>
                   7541:         <div class="LC_grades_select_mode_body">
                   7542:           <div class="LC_grade_select_mode_type_body">
                   7543:             <div class="LC_grade_select_mode_type">
                   7544:               <label>
                   7545:                 <input type="radio" name="radioChoice" value="pickStudentPage" '.
                   7546: 	  ($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
                   7547:   &mt('The <b>complete</b> page/sequence/folder: For one student').'
                   7548:               </label>
                   7549:             </div>
                   7550:             <div class="LC_grade_select_mode_type">
                   7551: 	      <input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="'.&mt('Next-&gt;').'" />
                   7552:             </div>
1.472     albertel 7553:           </div>
                   7554:         </div>
                   7555:       </div>
                   7556:     </div>
                   7557:   </form>';
1.44      ng       7558:     return $result;
1.2       albertel 7559: }
                   7560: 
1.285     albertel 7561: sub reset_perm {
                   7562:     undef(%perm);
                   7563: }
                   7564: 
                   7565: sub init_perm {
                   7566:     &reset_perm();
1.300     albertel 7567:     foreach my $test_perm ('vgr','mgr','opa') {
                   7568: 
                   7569: 	my $scope = $env{'request.course.id'};
                   7570: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7571: 
                   7572: 	    $scope .= '/'.$env{'request.course.sec'};
                   7573: 	    if ( $perm{$test_perm}=
                   7574: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7575: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7576: 	    } else {
                   7577: 		delete($perm{$test_perm});
                   7578: 	    }
1.285     albertel 7579: 	}
                   7580:     }
                   7581: }
                   7582: 
1.400     www      7583: sub gather_clicker_ids {
1.408     albertel 7584:     my %clicker_ids;
1.400     www      7585: 
                   7586:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7587: 
                   7588:     # Set up a couple variables.
1.407     albertel 7589:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7590:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7591:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7592: 
1.407     albertel 7593:     foreach my $student (keys(%$classlist)) {
1.438     www      7594:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7595:         my $username = $classlist->{$student}->[$username_idx];
                   7596:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7597:         my $clickers =
1.408     albertel 7598: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7599:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7600:             $id=~s/^[\#0]+//;
1.421     www      7601:             $id=~s/[\-\:]//g;
1.407     albertel 7602:             if (exists($clicker_ids{$id})) {
1.408     albertel 7603: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7604:             } else {
1.408     albertel 7605: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7606:             }
                   7607:         }
                   7608:     }
1.407     albertel 7609:     return %clicker_ids;
1.400     www      7610: }
                   7611: 
1.402     www      7612: sub gather_adv_clicker_ids {
1.408     albertel 7613:     my %clicker_ids;
1.402     www      7614:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7615:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7616:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7617:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7618:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7619:             my ($puname,$pudom)=split(/\:/,$person);
                   7620:             my $clickers =
1.408     albertel 7621: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7622:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7623: 		$id=~s/^[\#0]+//;
1.421     www      7624:                 $id=~s/[\-\:]//g;
1.408     albertel 7625: 		if (exists($clicker_ids{$id})) {
                   7626: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7627: 		} else {
                   7628: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7629: 		}
1.405     www      7630:             }
1.402     www      7631:         }
                   7632:     }
1.407     albertel 7633:     return %clicker_ids;
1.402     www      7634: }
                   7635: 
1.413     www      7636: sub clicker_grading_parameters {
                   7637:     return ('gradingmechanism' => 'scalar',
                   7638:             'upfiletype' => 'scalar',
                   7639:             'specificid' => 'scalar',
                   7640:             'pcorrect' => 'scalar',
                   7641:             'pincorrect' => 'scalar');
                   7642: }
                   7643: 
1.400     www      7644: sub process_clicker {
                   7645:     my ($r)=@_;
                   7646:     my ($symb)=&get_symb($r);
                   7647:     if (!$symb) {return '';}
                   7648:     my $result=&checkforfile_js();
                   7649:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7650:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7651:     $result.=$table;
                   7652:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7653:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7654:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7655:         '.</b></td></tr>'."\n";
                   7656:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7657: # Attempt to restore parameters from last session, set defaults if not present
                   7658:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7659:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7660:                                                  \%Saveable_Parameters);
                   7661:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7662:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7663:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7664:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7665: 
                   7666:     my %checked;
                   7667:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7668:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7669:           $checked{$gradingmechanism}="checked='checked'";
                   7670:        }
                   7671:     }
                   7672: 
1.400     www      7673:     my $upload=&mt("Upload File");
                   7674:     my $type=&mt("Type");
1.402     www      7675:     my $attendance=&mt("Award points just for participation");
                   7676:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7677:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7678:     my $pcorrect=&mt("Percentage points for correct solution");
                   7679:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7680:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7681: 						   ('iclicker' => 'i>clicker',
                   7682:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7683:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7684:     $result.=<<ENDUPFORM;
1.402     www      7685: <script type="text/javascript">
                   7686: function sanitycheck() {
                   7687: // Accept only integer percentages
                   7688:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7689:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7690: // Find out grading choice
                   7691:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7692:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7693:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7694:       }
                   7695:    }
                   7696: // By default, new choice equals user selection
                   7697:    newgradingchoice=gradingchoice;
                   7698: // Not good to give more points for false answers than correct ones
                   7699:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7700:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7701:    }
                   7702: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7703:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7704:       document.forms.gradesupload.pcorrect.value=100;
                   7705:       document.forms.gradesupload.pincorrect.value=100;
                   7706:    }
                   7707: // If the values are different, cannot be attendance only
                   7708:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7709:        (gradingchoice=='attendance')) {
                   7710:        newgradingchoice='personnel';
                   7711:    }
                   7712: // Change grading choice to new one
                   7713:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7714:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7715:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7716:       } else {
                   7717:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7718:       }
                   7719:    }
                   7720: // Remember the old state
                   7721:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7722: }
                   7723: </script>
1.400     www      7724: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7725: <input type="hidden" name="symb" value="$symb" />
                   7726: <input type="hidden" name="command" value="processclickerfile" />
                   7727: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7728: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7729: <input type="file" name="upfile" size="50" />
                   7730: <br /><label>$type: $selectform</label>
1.451     albertel 7731: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7732: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7733: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7734: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7735: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7736: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7737: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7738: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7739: </form>
                   7740: ENDUPFORM
                   7741:     $result.='</td></tr></table>'."\n".
                   7742:              '</td></tr></table><br /><br />'."\n";
                   7743:     $result.=&show_grading_menu_form($symb);
                   7744:     return $result;
                   7745: }
                   7746: 
                   7747: sub process_clicker_file {
                   7748:     my ($r)=@_;
                   7749:     my ($symb)=&get_symb($r);
                   7750:     if (!$symb) {return '';}
1.413     www      7751: 
                   7752:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7753:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7754:                                               \%Saveable_Parameters);
                   7755: 
1.400     www      7756:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7757:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7758: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7759: 	return $result.&show_grading_menu_form($symb);
1.404     www      7760:     }
1.407     albertel 7761:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7762:     my %correct_ids;
1.404     www      7763:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7764: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7765:     }
                   7766:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7767: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7768: 	   $correct_id=~tr/a-z/A-Z/;
                   7769: 	   $correct_id=~s/\s//gs;
                   7770: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7771:            $correct_id=~s/[\-\:]//g;
1.414     www      7772:            if ($correct_id) {
                   7773: 	      $correct_ids{$correct_id}='specified';
                   7774:            }
                   7775:         }
1.400     www      7776:     }
1.404     www      7777:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7778: 	$result.=&mt('Score based on attendance only');
1.404     www      7779:     } else {
1.408     albertel 7780: 	my $number=0;
1.411     www      7781: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7782: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7783: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7784: 	    if ($correct_ids{$id} eq 'specified') {
                   7785: 		$result.=&mt('specified');
                   7786: 	    } else {
                   7787: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7788: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7789: 	    }
                   7790: 	    $number++;
                   7791: 	}
1.411     www      7792:         $result.="</p>\n";
1.408     albertel 7793: 	if ($number==0) {
                   7794: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7795: 	    return $result.&show_grading_menu_form($symb);
                   7796: 	}
1.404     www      7797:     }
1.405     www      7798:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7799:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7800: 		     '<span class="LC_error">',
                   7801: 		     '</span>',
                   7802: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7803:         return $result.&show_grading_menu_form($symb);
                   7804:     }
1.410     www      7805: 
                   7806: # Were able to get all the info needed, now analyze the file
                   7807: 
1.411     www      7808:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7809:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7810:     my $heading=&mt('Scanning clicker file');
                   7811:     $result.=(<<ENDHEADER);
                   7812: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7813: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7814: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7815: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7816: <input type="hidden" name="symb" value="$symb" />
                   7817: <input type="hidden" name="command" value="assignclickergrades" />
                   7818: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7819: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7820: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7821: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7822: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7823: ENDHEADER
1.408     albertel 7824:     my %responses;
                   7825:     my @questiontitles;
1.405     www      7826:     my $errormsg='';
                   7827:     my $number=0;
                   7828:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7829: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7830:     }
1.419     www      7831:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7832:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7833:     }
1.411     www      7834:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7835:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7836:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7837:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7838:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7839:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7840:              '<br />';
1.414     www      7841: # Remember Question Titles
                   7842: # FIXME: Possibly need delimiter other than ":"
                   7843:     for (my $i=0;$i<$number;$i++) {
                   7844:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7845:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7846:     }
1.411     www      7847:     my $correct_count=0;
                   7848:     my $student_count=0;
                   7849:     my $unknown_count=0;
1.414     www      7850: # Match answers with usernames
                   7851: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7852:     foreach my $id (keys(%responses)) {
1.410     www      7853:        if ($correct_ids{$id}) {
1.414     www      7854:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7855:           $correct_count++;
1.410     www      7856:        } elsif ($clicker_ids{$id}) {
1.437     www      7857:           if ($clicker_ids{$id}=~/\,/) {
                   7858: # More than one user with the same clicker!
                   7859:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7860:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7861:                            "<select name='multi".$id."'>";
                   7862:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7863:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7864:              }
                   7865:              $result.='</select>';
                   7866:              $unknown_count++;
                   7867:           } else {
                   7868: # Good: found one and only one user with the right clicker
                   7869:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7870:              $student_count++;
                   7871:           }
1.410     www      7872:        } else {
1.411     www      7873:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7874:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7875:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7876:                    "\n".&mt("Domain").": ".
                   7877:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7878:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7879:           $unknown_count++;
1.410     www      7880:        }
1.405     www      7881:     }
1.412     www      7882:     $result.='<hr />'.
                   7883:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7884:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7885:        if ($correct_count==0) {
                   7886:           $errormsg.="Found no correct answers answers for grading!";
                   7887:        } elsif ($correct_count>1) {
1.414     www      7888:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7889:        }
                   7890:     }
1.428     www      7891:     if ($number<1) {
                   7892:        $errormsg.="Found no questions.";
                   7893:     }
1.412     www      7894:     if ($errormsg) {
                   7895:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7896:     } else {
                   7897:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7898:     }
                   7899:     $result.='</form></td></tr></table>'."\n".
1.410     www      7900:              '</td></tr></table><br /><br />'."\n";
1.404     www      7901:     return $result.&show_grading_menu_form($symb);
1.400     www      7902: }
                   7903: 
1.405     www      7904: sub iclicker_eval {
1.406     www      7905:     my ($questiontitles,$responses)=@_;
1.405     www      7906:     my $number=0;
                   7907:     my $errormsg='';
                   7908:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7909:         my %components=&Apache::loncommon::record_sep($line);
                   7910:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7911: 	if ($entries[0] eq 'Question') {
                   7912: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7913: 		$$questiontitles[$number]=$entries[$i];
                   7914: 		$number++;
                   7915: 	    }
                   7916: 	}
                   7917: 	if ($entries[0]=~/^\#/) {
                   7918: 	    my $id=$entries[0];
                   7919: 	    my @idresponses;
                   7920: 	    $id=~s/^[\#0]+//;
                   7921: 	    for (my $i=0;$i<$number;$i++) {
                   7922: 		my $idx=3+$i*6;
                   7923: 		push(@idresponses,$entries[$idx]);
                   7924: 	    }
                   7925: 	    $$responses{$id}=join(',',@idresponses);
                   7926: 	}
1.405     www      7927:     }
                   7928:     return ($errormsg,$number);
                   7929: }
                   7930: 
1.419     www      7931: sub interwrite_eval {
                   7932:     my ($questiontitles,$responses)=@_;
                   7933:     my $number=0;
                   7934:     my $errormsg='';
1.420     www      7935:     my $skipline=1;
                   7936:     my $questionnumber=0;
                   7937:     my %idresponses=();
1.419     www      7938:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7939:         my %components=&Apache::loncommon::record_sep($line);
                   7940:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7941:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7942:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7943:         next if $skipline;
                   7944:         if ($entries[0]!=$questionnumber) {
                   7945:            $questionnumber=$entries[0];
                   7946:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7947:            $number++;
1.419     www      7948:         }
1.420     www      7949:         my $id=$entries[4];
                   7950:         $id=~s/^[\#0]+//;
1.421     www      7951:         $id=~s/^v\d*\://i;
                   7952:         $id=~s/[\-\:]//g;
1.420     www      7953:         $idresponses{$id}[$number]=$entries[6];
                   7954:     }
                   7955:     foreach my $id (keys %idresponses) {
                   7956:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7957:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7958:     }
                   7959:     return ($errormsg,$number);
                   7960: }
                   7961: 
1.414     www      7962: sub assign_clicker_grades {
                   7963:     my ($r)=@_;
                   7964:     my ($symb)=&get_symb($r);
                   7965:     if (!$symb) {return '';}
1.416     www      7966: # See which part we are saving to
                   7967:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7968: # FIXME: This should probably look for the first handgradeable part
                   7969:     my $part=$$partlist[0];
                   7970: # Start screen output
1.414     www      7971:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7972: 
1.414     www      7973:     my $heading=&mt('Assigning grades based on clicker file');
                   7974:     $result.=(<<ENDHEADER);
                   7975: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7976: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7977: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7978: ENDHEADER
                   7979: # Get correct result
                   7980: # FIXME: Possibly need delimiter other than ":"
                   7981:     my @correct=();
1.415     www      7982:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7983:     my $number=$env{'form.number'};
                   7984:     if ($gradingmechanism ne 'attendance') {
1.414     www      7985:        foreach my $key (keys(%env)) {
                   7986:           if ($key=~/^form\.correct\:/) {
                   7987:              my @input=split(/\,/,$env{$key});
                   7988:              for (my $i=0;$i<=$#input;$i++) {
                   7989:                  if (($correct[$i]) && ($input[$i]) &&
                   7990:                      ($correct[$i] ne $input[$i])) {
                   7991:                     $result.='<br /><span class="LC_warning">'.
                   7992:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7993:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7994:                  } elsif ($input[$i]) {
                   7995:                     $correct[$i]=$input[$i];
                   7996:                  }
                   7997:              }
                   7998:           }
                   7999:        }
1.415     www      8000:        for (my $i=0;$i<$number;$i++) {
1.414     www      8001:           if (!$correct[$i]) {
                   8002:              $result.='<br /><span class="LC_error">'.
                   8003:                       &mt('No correct result given for question "[_1]"!',
                   8004:                           $env{'form.question:'.$i}).'</span>';
                   8005:           }
                   8006:        }
                   8007:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   8008:     }
                   8009: # Start grading
1.415     www      8010:     my $pcorrect=$env{'form.pcorrect'};
                   8011:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      8012:     my $storecount=0;
1.415     www      8013:     foreach my $key (keys(%env)) {
1.420     www      8014:        my $user='';
1.415     www      8015:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      8016:           $user=$1;
                   8017:        }
                   8018:        if ($key=~/^form\.unknown\:(.*)$/) {
                   8019:           my $id=$1;
                   8020:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   8021:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      8022:           } elsif ($env{'form.multi'.$id}) {
                   8023:              $user=$env{'form.multi'.$id};
1.420     www      8024:           }
                   8025:        }
                   8026:        if ($user) { 
1.415     www      8027:           my @answer=split(/\,/,$env{$key});
                   8028:           my $sum=0;
                   8029:           for (my $i=0;$i<$number;$i++) {
                   8030:              if ($answer[$i]) {
                   8031:                 if ($gradingmechanism eq 'attendance') {
                   8032:                    $sum+=$pcorrect;
                   8033:                 } else {
                   8034:                    if ($answer[$i] eq $correct[$i]) {
                   8035:                       $sum+=$pcorrect;
                   8036:                    } else {
                   8037:                       $sum+=$pincorrect;
                   8038:                    }
                   8039:                 }
                   8040:              }
                   8041:           }
1.416     www      8042:           my $ave=$sum/(100*$number);
                   8043: # Store
                   8044:           my ($username,$domain)=split(/\:/,$user);
                   8045:           my %grades=();
                   8046:           $grades{"resource.$part.solved"}='correct_by_override';
                   8047:           $grades{"resource.$part.awarded"}=$ave;
                   8048:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8049:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8050:                                                  $env{'request.course.id'},
                   8051:                                                  $domain,$username);
                   8052:           if ($returncode ne 'ok') {
                   8053:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8054:           } else {
                   8055:              $storecount++;
                   8056:           }
1.415     www      8057:        }
                   8058:     }
                   8059: # We are done
1.416     www      8060:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8061:              '</td></tr></table>'."\n".
1.414     www      8062:              '</td></tr></table><br /><br />'."\n";
                   8063:     return $result.&show_grading_menu_form($symb);
                   8064: }
                   8065: 
1.1       albertel 8066: sub handler {
1.41      ng       8067:     my $request=$_[0];
1.434     albertel 8068:     &reset_caches();
1.257     albertel 8069:     if ($env{'browser.mathml'}) {
1.141     www      8070: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8071:     } else {
1.141     www      8072: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8073:     }
                   8074:     $request->send_http_header;
1.44      ng       8075:     return '' if $request->header_only;
1.41      ng       8076:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8077:     my $symb=&get_symb($request,1);
1.160     albertel 8078:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8079:     my $command=$commands[0];
1.447     foxr     8080: 
1.160     albertel 8081:     if ($#commands > 0) {
                   8082: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8083:     }
1.447     foxr     8084: 
                   8085: 
1.353     albertel 8086:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8087:     if ($symb eq '' && $command eq '') {
1.257     albertel 8088: 	if ($env{'user.adv'}) {
                   8089: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8090: 		($env{'form.codethree'})) {
                   8091: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8092: 		    $env{'form.codethree'};
1.41      ng       8093: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8094: 		    &Apache::lonnet::checkin($token);
                   8095: 		if ($tsymb) {
1.137     albertel 8096: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8097: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8098: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8099: 					  ('grade_username' => $tuname,
                   8100: 					   'grade_domain' => $tudom,
                   8101: 					   'grade_courseid' => $tcrsid,
                   8102: 					   'grade_symb' => $tsymb)));
1.41      ng       8103: 		    } else {
1.45      ng       8104: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8105: 		    }
1.41      ng       8106: 		} else {
1.45      ng       8107: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8108: 		}
1.14      www      8109: 	    } else {
1.41      ng       8110: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8111: 	    }
                   8112: 	}
                   8113:     } else {
1.285     albertel 8114: 	&init_perm();
1.104     albertel 8115: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8116: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8117: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8118: 	    &pickStudentPage($request);
1.103     albertel 8119: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8120: 	    &displayPage($request);
1.104     albertel 8121: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8122: 	    &updateGradeByPage($request);
1.104     albertel 8123: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8124: 	    &processGroup($request);
1.104     albertel 8125: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8126: 	    $request->print(&grading_menu($request));
                   8127: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8128: 	    $request->print(&submit_options($request));
1.104     albertel 8129: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8130: 	    $request->print(&viewgrades($request));
1.104     albertel 8131: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8132: 	    $request->print(&processHandGrade($request));
1.106     albertel 8133: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8134: 	    $request->print(&editgrades($request));
1.106     albertel 8135: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8136: 	    $request->print(&verifyreceipt($request));
1.400     www      8137:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8138:             $request->print(&process_clicker($request));
                   8139:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8140:             $request->print(&process_clicker_file($request));
1.414     www      8141:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8142:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8143: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8144: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8145: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8146: 	    $request->print(&csvupload($request));
1.106     albertel 8147: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8148: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8149: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8150: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8151: 		$request->print(&csvuploadoptions($request));
1.41      ng       8152: 	    } else {
1.257     albertel 8153: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8154: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8155: 		} else {
1.257     albertel 8156: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8157: 		}
                   8158: 		$request->print(&csvuploadmap($request));
                   8159: 	    }
1.246     albertel 8160: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8161: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8162: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 8163: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8164:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8165:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8166: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8167: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8168: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8169: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8170:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8171:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8172: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8173:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8174:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8175:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8176: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8177:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8178:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8179: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8180:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8181: 	} elsif ($command) {
1.157     albertel 8182: 	    $request->print("Access Denied ($command)");
1.26      albertel 8183: 	}
1.2       albertel 8184:     }
1.353     albertel 8185:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8186:     &reset_caches();
1.44      ng       8187:     return '';
                   8188: }
                   8189: 
1.1       albertel 8190: 1;
                   8191: 
1.13      albertel 8192: __END__;

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