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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.456   ! banghart    4: # $Id: grades.pm,v 1.455 2007/10/11 23:18:46 banghart Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.456   ! banghart   38: use Apache::lonpickcode;
1.55      matthew    39: use Apache::loncoursedata;
1.362     albertel   40: use Apache::lonmsg();
1.1       albertel   41: use Apache::Constants qw(:common);
1.167     sakharuk   42: use Apache::lonlocal;
1.386     raeburn    43: use Apache::lonenc;
1.170     albertel   44: use String::Similarity;
1.359     www        45: use LONCAPA;
                     46: 
1.315     bowersj2   47: use POSIX qw(floor);
1.87      www        48: 
1.435     foxr       49: 
                     50: my %perm=();
1.447     foxr       51: my %bubble_lines_per_response = ();     # no. bubble lines for each response.
1.435     foxr       52:                                    # index is "symb.part_id"
                     53: 
1.447     foxr       54: my %first_bubble_line = ();	# First bubble line no. for each bubble.
                     55: 
                     56: # Save and restore the bubble lines array to the form env.
                     57: 
                     58: 
                     59: sub save_bubble_lines {
1.448     foxr       60:     &Apache::lonnet::logthis("Saving bubble_lines...");
1.447     foxr       61:     foreach my $line (keys(%bubble_lines_per_response)) {
1.448     foxr       62: 	&Apache::lonnet::logthis("Saving form.scantron.bubblelines.$line value: $bubble_lines_per_response{$line}");
1.447     foxr       63: 	$env{"form.scantron.bubblelines.$line"}  = $bubble_lines_per_response{$line};
                     64: 	$env{"form.scantron.first_bubble_line.$line"} =
                     65: 	    $first_bubble_line{$line};
                     66:     }
                     67: }
                     68: 
                     69: 
                     70: sub restore_bubble_lines {
                     71:     my $line = 0;
                     72:     %bubble_lines_per_response = ();
                     73:     while ($env{"form.scantron.bubblelines.$line"}) {
                     74: 	my $value = $env{"form.scantron.bubblelines.$line"};
1.448     foxr       75: 	&Apache::lonnet::logthis("Restoring form.scantron.bubblelines.$line value: $value");
1.447     foxr       76: 	$bubble_lines_per_response{$line} = $value;
                     77: 	$first_bubble_line{$line}  =
                     78: 	    $env{"form.scantron.first_bubble_line.$line"};
                     79: 	$line++;
                     80:     }
                     81: 
                     82: }
                     83: 
                     84: #  Given the parsed scanline, get the response for 
                     85: #  'answer' number n:
                     86: 
                     87: sub get_response_bubbles {
                     88:     my ($parsed_line, $response)  = @_;
                     89: 
                     90:     my $bubble_line = $first_bubble_line{$response};
1.448     foxr       91:     my $bubble_lines= $bubble_lines_per_response{$response};
1.447     foxr       92:     my $selected = "";
                     93: 
                     94:     for (my $bline = 0; $bline < $bubble_lines; $bline++) {
                     95: 	$selected .= $$parsed_line{"scantron.$bubble_line.answer"};
                     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">'.
                    336: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  337: 	    '<tr valign="top"><td>'.$grayFont.'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.148     albertel  356: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  357: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  358: 	    $middlerow.'</tr>'.
1.398     albertel  359: 	    '<tr valign="top"><td>'.$grayFont.'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.148     albertel  369: 		    $toprow.='<td><b>true</b></td>';
                    370: 		} else {
                    371: 		    $toprow.='<td><i>true</i></td>';
                    372: 		}
                    373: 	    } else {
                    374: 		$toprow.='<td>false</td>';
                    375: 	    }
1.398     albertel  376: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  377: 	}
                    378: 	return '<blockquote><table border="1">'.
                    379: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  380: 	    '<tr valign="top"><td>'.$grayFont.'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".
                    869: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    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.45      ng        906:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        907: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    908:     my $loop = 0;
                    909:     while ($loop < 2) {
1.126     ng        910: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  911: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
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.207     albertel  917: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    918: 		    ' Status&nbsp;</b></td>';
1.110     ng        919: 	    }
1.301     albertel  920: 	} elsif ($submitonly eq 'queued') {
                    921: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        922: 	}
                    923: 	$loop++;
1.126     ng        924: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        925:     }
1.45      ng        926:     $gradeTable.='</tr>'."\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.110     ng        982: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        983: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  984:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    985:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    986: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    987: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
1.452     banghart  988: 	       '&nbsp;'.$section.'/'.$group.'</td>'."\n";
1.110     ng        989: 
1.257     albertel  990: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        991: 		foreach (sort keys(%status)) {
                    992: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  993: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        994: 		}
1.41      ng        995: 	    }
1.126     ng        996: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        997: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        998: 	}
                    999:     }
1.110     ng       1000:     if ($ctr%2 ==1) {
1.126     ng       1001: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel 1002: 	    if ($env{'form.showgrading'} eq 'yes' 
                   1003: 		&& $submitonly ne 'queued'
                   1004: 		&& $submitonly ne 'all') {
1.110     ng       1005: 		foreach (@$partlist) {
                   1006: 		    $gradeTable.='<td>&nbsp;</td>';
                   1007: 		}
1.301     albertel 1008: 	    } elsif ($submitonly eq 'queued') {
                   1009: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng       1010: 	    }
                   1011: 	$gradeTable.='</tr>';
                   1012:     }
                   1013: 
1.249     albertel 1014:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng       1015: 	'<input type="button" '.
                   1016: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng       1017: 	'value="Next->" /></form>'."\n";
1.45      ng       1018:     if ($ctr == 0) {
1.96      albertel 1019: 	my $num_students=(scalar(keys(%$fullname)));
                   1020: 	if ($num_students eq 0) {
1.398     albertel 1021: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel 1022: 	} else {
1.171     albertel 1023: 	    my $submissions='submissions';
                   1024: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                   1025: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel 1026: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel 1027: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel 1028: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel 1029: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel 1030: 	}
1.46      ng       1031:     } elsif ($ctr == 1) {
                   1032: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng       1033:     }
1.324     albertel 1034:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng       1035:     $request->print($gradeTable);
1.44      ng       1036:     return '';
1.10      ng       1037: }
                   1038: 
1.44      ng       1039: #---- Called from the listStudents routine
1.249     albertel 1040: 
                   1041: sub check_script {
                   1042:     my ($form, $type)=@_;
                   1043:     my $chkallscript='<script type="text/javascript">
                   1044:     function checkall() {
                   1045:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1046:             ele = document.forms.'.$form.'.elements[i];
                   1047:             if (ele.name == "'.$type.'") {
                   1048:             document.forms.'.$form.'.elements[i].checked=true;
                   1049:                                        }
                   1050:         }
                   1051:     }
                   1052: 
                   1053:     function checksec() {
                   1054:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1055:             ele = document.forms.'.$form.'.elements[i];
                   1056:            string = document.forms.'.$form.'.chksec.value;
                   1057:            if
                   1058:           (ele.value.indexOf(":::SECTION"+string)>0) {
                   1059:               document.forms.'.$form.'.elements[i].checked=true;
                   1060:             }
                   1061:         }
                   1062:     }
                   1063: 
                   1064: 
                   1065:     function uncheckall() {
                   1066:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                   1067:             ele = document.forms.'.$form.'.elements[i];
                   1068:             if (ele.name == "'.$type.'") {
                   1069:             document.forms.'.$form.'.elements[i].checked=false;
                   1070:                                        }
                   1071:         }
                   1072:     }
                   1073: 
                   1074: </script>'."\n";
                   1075:     return $chkallscript;
                   1076: }
                   1077: 
                   1078: sub check_buttons {
                   1079:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                   1080:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                   1081:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                   1082:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                   1083:     return $buttons;
                   1084: }
                   1085: 
1.44      ng       1086: #     Displays the submissions for one student or a group of students
1.34      ng       1087: sub processGroup {
1.41      ng       1088:     my ($request)  = shift;
                   1089:     my $ctr        = 0;
1.155     albertel 1090:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng       1091:     my $total      = scalar(@stuchecked)-1;
1.45      ng       1092: 
1.396     banghart 1093:     foreach my $student (@stuchecked) {
                   1094: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel 1095: 	$env{'form.student'}        = $uname;
                   1096: 	$env{'form.userdom'}        = $udom;
                   1097: 	$env{'form.fullname'}       = $fullname;
1.41      ng       1098: 	&submission($request,$ctr,$total);
                   1099: 	$ctr++;
                   1100:     }
                   1101:     return '';
1.35      ng       1102: }
1.34      ng       1103: 
1.44      ng       1104: #------------------------------------------------------------------------------------
                   1105: #
                   1106: #-------------------------- Next few routines handles grading by student, essentially
                   1107: #                           handles essay response type problem/part
                   1108: #
                   1109: #--- Javascript to handle the submission page functionality ---
                   1110: sub sub_page_js {
                   1111:     my $request = shift;
                   1112:     $request->print(<<SUBJAVASCRIPT);
                   1113: <script type="text/javascript" language="javascript">
1.71      ng       1114:     function updateRadio(formname,id,weight) {
1.125     ng       1115: 	var gradeBox = formname["GD_BOX"+id];
                   1116: 	var radioButton = formname["RADVAL"+id];
                   1117: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1118: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1119: 	gradeBox.value = pts;
                   1120: 	var resetbox = false;
                   1121: 	if (isNaN(pts) || pts < 0) {
                   1122: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1123: 	    for (var i=0; i<radioButton.length; i++) {
                   1124: 		if (radioButton[i].checked) {
                   1125: 		    gradeBox.value = i;
                   1126: 		    resetbox = true;
                   1127: 		}
                   1128: 	    }
                   1129: 	    if (!resetbox) {
                   1130: 		formtextbox.value = "";
                   1131: 	    }
                   1132: 	    return;
1.44      ng       1133: 	}
1.71      ng       1134: 
                   1135: 	if (pts > weight) {
                   1136: 	    var resp = confirm("You entered a value ("+pts+
                   1137: 			       ") greater than the weight for the part. Accept?");
                   1138: 	    if (resp == false) {
1.125     ng       1139: 		gradeBox.value = oldpts;
1.71      ng       1140: 		return;
                   1141: 	    }
1.44      ng       1142: 	}
1.13      albertel 1143: 
1.71      ng       1144: 	for (var i=0; i<radioButton.length; i++) {
                   1145: 	    radioButton[i].checked=false;
                   1146: 	    if (pts == i && pts != "") {
                   1147: 		radioButton[i].checked=true;
                   1148: 	    }
                   1149: 	}
                   1150: 	updateSelect(formname,id);
1.125     ng       1151: 	formname["stores"+id].value = "0";
1.41      ng       1152:     }
1.5       albertel 1153: 
1.72      ng       1154:     function writeBox(formname,id,pts) {
1.125     ng       1155: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1156: 	if (checkSolved(formname,id) == 'update') {
                   1157: 	    gradeBox.value = pts;
                   1158: 	} else {
1.125     ng       1159: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1160: 	    gradeBox.value = oldpts;
1.125     ng       1161: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1162: 	    for (var i=0; i<radioButton.length; i++) {
                   1163: 		radioButton[i].checked=false;
1.72      ng       1164: 		if (i == oldpts) {
1.71      ng       1165: 		    radioButton[i].checked=true;
                   1166: 		}
                   1167: 	    }
1.41      ng       1168: 	}
1.125     ng       1169: 	formname["stores"+id].value = "0";
1.71      ng       1170: 	updateSelect(formname,id);
                   1171: 	return;
1.41      ng       1172:     }
1.44      ng       1173: 
1.71      ng       1174:     function clearRadBox(formname,id) {
                   1175: 	if (checkSolved(formname,id) == 'noupdate') {
                   1176: 	    updateSelect(formname,id);
                   1177: 	    return;
                   1178: 	}
1.125     ng       1179: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1180: 	for (var i=0; i<gradeSelect.length; i++) {
                   1181: 	    if (gradeSelect[i].selected) {
                   1182: 		var selectx=i;
                   1183: 	    }
                   1184: 	}
1.125     ng       1185: 	var stores = formname["stores"+id];
1.71      ng       1186: 	if (selectx == stores.value) { return };
1.125     ng       1187: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1188: 	gradeBox.value = "";
1.125     ng       1189: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1190: 	for (var i=0; i<radioButton.length; i++) {
                   1191: 	    radioButton[i].checked=false;
                   1192: 	}
                   1193: 	stores.value = selectx;
                   1194:     }
1.5       albertel 1195: 
1.71      ng       1196:     function checkSolved(formname,id) {
1.125     ng       1197: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1198: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1199: 	    if (!reply) {return "noupdate";}
1.120     ng       1200: 	    formname.overRideScore.value = 'yes';
1.41      ng       1201: 	}
1.71      ng       1202: 	return "update";
1.13      albertel 1203:     }
1.71      ng       1204: 
                   1205:     function updateSelect(formname,id) {
1.125     ng       1206: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1207: 	return;
1.41      ng       1208:     }
1.33      ng       1209: 
1.121     ng       1210: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1211:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1212: 	formname.gradeOpt.value = val;
1.71      ng       1213: 	if (val == "Save & Next") {
                   1214: 	    for (i=0;i<=total;i++) {
                   1215: 		for (j=0;j<parttot;j++) {
1.125     ng       1216: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1217: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1218: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1219: 			if (points == "") {
1.125     ng       1220: 			    var name = formname["name"+i].value;
1.129     ng       1221: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1222: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1223: 					       ", part "+partid+". Continue?");
1.71      ng       1224: 			    if (resp == false) {
1.125     ng       1225: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1226: 				return false;
                   1227: 			    }
                   1228: 			}
                   1229: 		    }
                   1230: 		    
                   1231: 		}
                   1232: 	    }
                   1233: 	    
                   1234: 	}
1.121     ng       1235: 	if (val == "Grade Student") {
                   1236: 	    formname.showgrading.value = "yes";
                   1237: 	    if (formname.Status.value == "") {
                   1238: 		formname.Status.value = "Active";
                   1239: 	    }
                   1240: 	    formname.studentNo.value = total;
                   1241: 	}
1.120     ng       1242: 	formname.submit();
                   1243:     }
                   1244: 
1.71      ng       1245: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1246:     function checkSubmitPage(formname,total) {
                   1247: 	noscore = new Array(100);
                   1248: 	var ptr = 0;
                   1249: 	for (i=1;i<total;i++) {
1.125     ng       1250: 	    var partid = formname["q_"+i].value;
1.127     ng       1251: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1252: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1253: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1254: 		if (points == "" && status != "correct_by_student") {
                   1255: 		    noscore[ptr] = i;
                   1256: 		    ptr++;
                   1257: 		}
                   1258: 	    }
                   1259: 	}
                   1260: 	if (ptr != 0) {
                   1261: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1262: 	    var prolist = "";
                   1263: 	    if (ptr == 1) {
                   1264: 		prolist = noscore[0];
                   1265: 	    } else {
                   1266: 		var i = 0;
                   1267: 		while (i < ptr-1) {
                   1268: 		    prolist += noscore[i]+", ";
                   1269: 		    i++;
                   1270: 		}
                   1271: 		prolist += "and "+noscore[i];
                   1272: 	    }
                   1273: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1274: 	    if (resp == false) {
                   1275: 		return false;
                   1276: 	    }
                   1277: 	}
1.45      ng       1278: 
1.71      ng       1279: 	formname.submit();
                   1280:     }
                   1281: </script>
                   1282: SUBJAVASCRIPT
                   1283: }
1.45      ng       1284: 
1.71      ng       1285: #--- javascript for essay type problem --
                   1286: sub sub_page_kw_js {
                   1287:     my $request = shift;
1.80      ng       1288:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1289:     &commonJSfunctions($request);
1.350     albertel 1290: 
1.351     albertel 1291:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1292:     <script text="text/javascript">
                   1293:     function checkInput() {
                   1294:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1295:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1296:       var usrctr = document.msgcenter.usrctr.value;
                   1297:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1298:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1299: 
                   1300:       var msgchk = "";
                   1301:       if (document.msgcenter.subchk.checked) {
                   1302:          msgchk = "msgsub,";
                   1303:       }
                   1304:       var includemsg = 0;
                   1305:       for (var i=1; i<=nmsg; i++) {
                   1306:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1307:           var frmmsg = document.msgcenter["msg"+i];
                   1308:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1309:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1310:           showflg.value = "1";
                   1311:           var chkbox = document.msgcenter["msgn"+i];
                   1312:           if (chkbox.checked) {
                   1313:              msgchk += "savemsg"+i+",";
                   1314:              includemsg = 1;
                   1315:           }
                   1316:       }
                   1317:       if (document.msgcenter.newmsgchk.checked) {
                   1318:          msgchk += "newmsg"+usrctr;
                   1319:          includemsg = 1;
                   1320:       }
                   1321:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1322:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1323:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1324:       includemsg.value = msgchk;
                   1325: 
                   1326:       self.close()
                   1327: 
                   1328:     }
                   1329:     </script>
                   1330: INNERJS
                   1331: 
1.351     albertel 1332:     my $inner_js_highlight_central=<<INNERJS;
                   1333:  <script type="text/javascript">
                   1334:     function updateChoice(flag) {
                   1335:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1336:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1337:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1338:       opener.document.SCORE.refresh.value = "on";
                   1339:       if (opener.document.SCORE.keywords.value!=""){
                   1340:          opener.document.SCORE.submit();
                   1341:       }
                   1342:       self.close()
                   1343:     }
                   1344: </script>
                   1345: INNERJS
                   1346: 
                   1347:     my $start_page_msg_central = 
                   1348:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1349: 				       {'js_ready'  => 1,
                   1350: 					'only_body' => 1,
                   1351: 					'bgcolor'   =>'#FFFFFF',});
                   1352:     my $end_page_msg_central = 
                   1353: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1354: 
                   1355: 
                   1356:     my $start_page_highlight_central = 
                   1357:         &Apache::loncommon::start_page('Highlight Central',
                   1358: 				       $inner_js_highlight_central,
1.350     albertel 1359: 				       {'js_ready'  => 1,
                   1360: 					'only_body' => 1,
                   1361: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1362:     my $end_page_highlight_central = 
1.350     albertel 1363: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1364: 
1.219     www      1365:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1366:     $docopen=~s/^document\.//;
1.71      ng       1367:     $request->print(<<SUBJAVASCRIPT);
                   1368: <script type="text/javascript" language="javascript">
1.45      ng       1369: 
1.44      ng       1370: //===================== Show list of keywords ====================
1.122     ng       1371:   function keywords(formname) {
                   1372:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1373:     if (nret==null) return;
1.122     ng       1374:     formname.keywords.value = nret;
1.44      ng       1375: 
1.122     ng       1376:     if (formname.keywords.value != "") {
1.128     ng       1377: 	formname.refresh.value = "on";
1.122     ng       1378: 	formname.submit();
1.44      ng       1379:     }
                   1380:     return;
                   1381:   }
                   1382: 
                   1383: //===================== Script to view submitted by ==================
                   1384:   function viewSubmitter(submitter) {
                   1385:     document.SCORE.refresh.value = "on";
                   1386:     document.SCORE.NCT.value = "1";
                   1387:     document.SCORE.unamedom0.value = submitter;
                   1388:     document.SCORE.submit();
                   1389:     return;
                   1390:   }
                   1391: 
                   1392: //===================== Script to add keyword(s) ==================
                   1393:   function getSel() {
                   1394:     if (document.getSelection) txt = document.getSelection();
                   1395:     else if (document.selection) txt = document.selection.createRange().text;
                   1396:     else return;
                   1397:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1398:     if (cleantxt=="") {
1.46      ng       1399: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1400: 	return;
                   1401:     }
                   1402:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1403:     if (nret==null) return;
1.127     ng       1404:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1405:     if (document.SCORE.keywords.value != "") {
1.127     ng       1406: 	document.SCORE.refresh.value = "on";
1.44      ng       1407: 	document.SCORE.submit();
                   1408:     }
                   1409:     return;
                   1410:   }
                   1411: 
                   1412: //====================== Script for composing message ==============
1.80      ng       1413:    // preload images
                   1414:    img1 = new Image();
                   1415:    img1.src = "$iconpath/mailbkgrd.gif";
                   1416:    img2 = new Image();
                   1417:    img2.src = "$iconpath/mailto.gif";
                   1418: 
1.44      ng       1419:   function msgCenter(msgform,usrctr,fullname) {
                   1420:     var Nmsg  = msgform.savemsgN.value;
                   1421:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1422:     var subject = msgform.msgsub.value;
1.127     ng       1423:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1424:     re = /msgsub/;
                   1425:     var shwsel = "";
                   1426:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1427:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1428:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1429:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1430: 	var testmsg = "savemsg"+i+",";
                   1431: 	re = new RegExp(testmsg,"g");
1.44      ng       1432: 	shwsel = "";
                   1433: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1434: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1435: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1436: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1437: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1438:     }
1.125     ng       1439:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1440:     shwsel = "";
                   1441:     re = /newmsg/;
                   1442:     if (re.test(msgchk)) { shwsel = "checked" }
                   1443:     newMsg(newmsg,shwsel);
                   1444:     msgTail(); 
                   1445:     return;
                   1446:   }
                   1447: 
1.123     ng       1448:   function checkEntities(strx) {
                   1449:     if (strx.length == 0) return strx;
                   1450:     var orgStr = ["&", "<", ">", '"']; 
                   1451:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1452:     var counter = 0;
                   1453:     while (counter < 4) {
                   1454: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1455: 	counter++;
                   1456:     }
                   1457:     return strx;
                   1458:   }
                   1459: 
                   1460:   function strReplace(strx, orgStr, newStr) {
                   1461:     return strx.split(orgStr).join(newStr);
                   1462:   }
                   1463: 
1.44      ng       1464:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1465:     var height = 70*Nmsg+250;
1.44      ng       1466:     var scrollbar = "no";
                   1467:     if (height > 600) {
                   1468: 	height = 600;
                   1469: 	scrollbar = "yes";
                   1470:     }
1.118     ng       1471:     var xpos = (screen.width-600)/2;
                   1472:     xpos = (xpos < 0) ? '0' : xpos;
                   1473:     var ypos = (screen.height-height)/2-30;
                   1474:     ypos = (ypos < 0) ? '0' : ypos;
                   1475: 
1.206     albertel 1476:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1477:     pWin.focus();
                   1478:     pDoc = pWin.document;
1.219     www      1479:     pDoc.$docopen;
1.351     albertel 1480:     pDoc.write('$start_page_msg_central');
1.76      ng       1481: 
                   1482:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1483:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1484:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1485: 
                   1486:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1487:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1488:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1489: }
                   1490:     function displaySubject(msg,shwsel) {
1.76      ng       1491:     pDoc = pWin.document;
                   1492:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1493:     pDoc.write("<td>Subject</td>");
                   1494:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1495:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1496: }
                   1497: 
1.72      ng       1498:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1499:     pDoc = pWin.document;
                   1500:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1501:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1502:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1503:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1504: }
                   1505: 
                   1506:   function newMsg(newmsg,shwsel) {
1.76      ng       1507:     pDoc = pWin.document;
                   1508:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1509:     pDoc.write("<td align=\\"center\\">New</td>");
                   1510:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1511:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1512: }
                   1513: 
                   1514:   function msgTail() {
1.76      ng       1515:     pDoc = pWin.document;
                   1516:     pDoc.write("</table>");
                   1517:     pDoc.write("</td></tr></table>&nbsp;");
                   1518:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1519:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1520:     pDoc.write("</form>");
1.351     albertel 1521:     pDoc.write('$end_page_msg_central');
1.128     ng       1522:     pDoc.close();
1.44      ng       1523: }
                   1524: 
                   1525: //====================== Script for keyword highlight options ==============
                   1526:   function kwhighlight() {
                   1527:     var kwclr    = document.SCORE.kwclr.value;
                   1528:     var kwsize   = document.SCORE.kwsize.value;
                   1529:     var kwstyle  = document.SCORE.kwstyle.value;
                   1530:     var redsel = "";
                   1531:     var grnsel = "";
                   1532:     var blusel = "";
                   1533:     if (kwclr=="red")   {var redsel="checked"};
                   1534:     if (kwclr=="green") {var grnsel="checked"};
                   1535:     if (kwclr=="blue")  {var blusel="checked"};
                   1536:     var sznsel = "";
                   1537:     var sz1sel = "";
                   1538:     var sz2sel = "";
                   1539:     if (kwsize=="0")  {var sznsel="checked"};
                   1540:     if (kwsize=="+1") {var sz1sel="checked"};
                   1541:     if (kwsize=="+2") {var sz2sel="checked"};
                   1542:     var synsel = "";
                   1543:     var syisel = "";
                   1544:     var sybsel = "";
                   1545:     if (kwstyle=="")    {var synsel="checked"};
                   1546:     if (kwstyle=="<i>") {var syisel="checked"};
                   1547:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1548:     highlightCentral();
                   1549:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1550:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1551:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1552:     highlightend();
                   1553:     return;
                   1554:   }
                   1555: 
                   1556:   function highlightCentral() {
1.76      ng       1557: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1558:     var xpos = (screen.width-400)/2;
                   1559:     xpos = (xpos < 0) ? '0' : xpos;
                   1560:     var ypos = (screen.height-330)/2-30;
                   1561:     ypos = (ypos < 0) ? '0' : ypos;
                   1562: 
1.206     albertel 1563:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1564:     hwdWin.focus();
                   1565:     var hDoc = hwdWin.document;
1.219     www      1566:     hDoc.$docopen;
1.351     albertel 1567:     hDoc.write('$start_page_highlight_central');
1.76      ng       1568:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1569:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1570: 
                   1571:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1572:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1573:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1574:   }
                   1575: 
                   1576:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1577:     var hDoc = hwdWin.document;
                   1578:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1579:     hDoc.write("<td align=\\"left\\">");
                   1580:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1581:     hDoc.write("<td align=\\"left\\">");
                   1582:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1583:     hDoc.write("<td align=\\"left\\">");
                   1584:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1585:     hDoc.write("</tr>");
1.44      ng       1586:   }
                   1587: 
                   1588:   function highlightend() { 
1.76      ng       1589:     var hDoc = hwdWin.document;
                   1590:     hDoc.write("</table>");
                   1591:     hDoc.write("</td></tr></table>&nbsp;");
                   1592:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1593:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1594:     hDoc.write("</form>");
1.351     albertel 1595:     hDoc.write('$end_page_highlight_central');
1.128     ng       1596:     hDoc.close();
1.44      ng       1597:   }
                   1598: 
                   1599: </script>
                   1600: SUBJAVASCRIPT
                   1601: }
                   1602: 
1.349     albertel 1603: sub get_increment {
1.348     bowersj2 1604:     my $increment = $env{'form.increment'};
                   1605:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1606:         $increment != .1) {
                   1607:         $increment = 1;
                   1608:     }
                   1609:     return $increment;
                   1610: }
                   1611: 
1.71      ng       1612: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1613: sub gradeBox {
1.322     albertel 1614:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1615:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1616: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1617: 	'/check.gif" height="16" border="0" />';
                   1618:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1619:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1620: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1621:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1622:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1623: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1624:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1625:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1626:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1627: 				       [$partid]);
                   1628:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1629:     if ($last_resets{$partid}) {
                   1630:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1631:     }
1.71      ng       1632:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1633: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1634:     my $ctr = 0;
1.348     bowersj2 1635:     my $thisweight = 0;
1.349     albertel 1636:     my $increment = &get_increment();
1.71      ng       1637:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1638:     while ($thisweight<=$wgt) {
1.381     albertel 1639: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1640: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1641: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1642: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1643: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1644:         $thisweight += $increment;
1.71      ng       1645: 	$ctr++;
                   1646:     }
                   1647:     $result.='</tr></table>';
                   1648:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1649:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1650: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1651: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1652: 	$wgt.')" /></td>'."\n";
                   1653:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1654: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1655: 	' </td><td>'."\n";
                   1656:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1657: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1658:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1659: 	$result.='<option></option>'.
1.401     albertel 1660: 	    '<option selected="selected">excused</option>';
1.71      ng       1661:     } else {
1.401     albertel 1662: 	$result.='<option selected="selected"></option>'.
1.125     ng       1663: 	    '<option>excused</option>';
1.71      ng       1664:     }
1.125     ng       1665:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1666:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1667:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1668: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1669: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1670: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1671:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1672:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1673:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1674:         $aggtries.'" />'."\n";
1.71      ng       1675:     $result.='</td></tr></table>'."\n";
1.323     banghart 1676:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1677:     return $result;
                   1678: }
1.322     albertel 1679: 
                   1680: sub handback_box {
1.323     banghart 1681:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1682:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1683:     my (@respids);
1.375     albertel 1684:      my @part_response_id = &flatten_responseType($responseType);
                   1685:     foreach my $part_response_id (@part_response_id) {
                   1686:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1687:         if ($part eq $partid) {
1.375     albertel 1688:             push(@respids,$resp);
1.323     banghart 1689:         }
                   1690:     }
1.318     banghart 1691:     my $result;
1.323     banghart 1692:     foreach my $respid (@respids) {
1.322     albertel 1693: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1694: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1695: 	next if (!@$files);
                   1696: 	my $file_counter = 1;
1.313     banghart 1697: 	foreach my $file (@$files) {
1.368     banghart 1698: 	    if ($file =~ /\/portfolio\//) {
                   1699:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1700:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1701:     	        $file_disp = "$name.$ext";
                   1702:     	        $file = $file_path.$file_disp;
                   1703:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1704:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1705:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1706:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1707:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1708:     	        $file_counter++;
                   1709: 	    }
1.322     albertel 1710: 	}
1.313     banghart 1711:     }
1.318     banghart 1712:     return $result;    
1.71      ng       1713: }
1.44      ng       1714: 
1.58      albertel 1715: sub show_problem {
1.382     albertel 1716:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1717:     my $rendered;
1.382     albertel 1718:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1719:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1720:     if ($mode eq 'both' or $mode eq 'text') {
                   1721: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1722: 						       $env{'request.course.id'},
                   1723: 						       undef,\%form);
1.144     albertel 1724:     }
1.58      albertel 1725:     if ($removeform) {
                   1726: 	$rendered=~s|<form(.*?)>||g;
                   1727: 	$rendered=~s|</form>||g;
1.374     albertel 1728: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1729:     }
1.144     albertel 1730:     my $companswer;
                   1731:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1732: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1733: 	$companswer=
                   1734: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1735: 						    $env{'request.course.id'},
                   1736: 						    %form);
1.144     albertel 1737:     }
1.58      albertel 1738:     if ($removeform) {
                   1739: 	$companswer=~s|<form(.*?)>||g;
                   1740: 	$companswer=~s|</form>||g;
1.144     albertel 1741: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1742:     }
                   1743:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1744:     $result.='<table border="0" width="100%">';
1.144     albertel 1745:     if ($viewon) {
                   1746: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1747: 	if ($mode eq 'both' or $mode eq 'text') {
                   1748: 	    $result.='View of the problem - ';
                   1749: 	} else {
                   1750: 	    $result.='Correct answer: ';
                   1751: 	}
1.257     albertel 1752: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1753:     }
                   1754:     if ($mode eq 'both') {
                   1755: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1756: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1757:     } elsif ($mode eq 'text') {
                   1758: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1759:     } elsif ($mode eq 'answer') {
                   1760: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1761:     }
1.58      albertel 1762:     $result.='</td></tr></table>';
                   1763:     $result.='</td></tr></table><br />';
1.71      ng       1764:     return $result;
1.58      albertel 1765: }
1.397     albertel 1766: 
1.396     banghart 1767: sub files_exist {
                   1768:     my ($r, $symb) = @_;
                   1769:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1770: 
1.396     banghart 1771:     foreach my $student (@students) {
                   1772:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1773:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1774: 					      $udom,$uname);
1.396     banghart 1775:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1776:         foreach my $submission (@$string) {
                   1777:             my ($partid,$respid) =
                   1778: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1779:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1780: 					   \%record);
                   1781:             return 1 if (@$files);
1.396     banghart 1782:         }
                   1783:     }
1.397     albertel 1784:     return 0;
1.396     banghart 1785: }
1.397     albertel 1786: 
1.394     banghart 1787: sub download_all_link {
                   1788:     my ($r,$symb) = @_;
1.395     albertel 1789:     my $all_students = 
                   1790: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1791: 
                   1792:     my $parts =
                   1793: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1794: 
1.394     banghart 1795:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1796:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1797:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1798:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1799:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1800: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1801:     return
                   1802: }
1.395     albertel 1803: 
1.432     banghart 1804: sub build_section_inputs {
                   1805:     my $section_inputs;
                   1806:     if ($env{'form.section'} eq '') {
                   1807:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1808:     } else {
                   1809:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1810:         foreach my $section (@sections) {
1.432     banghart 1811:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1812:         }
                   1813:     }
                   1814:     return $section_inputs;
                   1815: }
                   1816: 
1.44      ng       1817: # --------------------------- show submissions of a student, option to grade 
                   1818: sub submission {
                   1819:     my ($request,$counter,$total) = @_;
1.257     albertel 1820:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1821:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1822:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1823:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1824:     my $symb = &get_symb($request); 
                   1825:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1826: 
                   1827:     if (!&canview($usec)) {
1.398     albertel 1828: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1829: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1830: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1831: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1832: 	return;
                   1833:     }
                   1834: 
1.257     albertel 1835:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1836:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1837:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1838:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1839:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1840: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1841: 	'/check.gif" height="16" border="0" />';
1.41      ng       1842: 
1.426     albertel 1843:     my %old_essays;
1.41      ng       1844:     # header info
                   1845:     if ($counter == 0) {
                   1846: 	&sub_page_js($request);
1.257     albertel 1847: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1848: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1849: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1850: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1851: 	    &download_all_link($request, $symb);
                   1852: 	}
1.398     albertel 1853: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1854: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1855: 
1.257     albertel 1856: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1857: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1858: 		$checkIcon.' symbol.'."\n";
                   1859: 	    $request->print($checkMark);
                   1860: 	}
1.41      ng       1861: 
1.44      ng       1862: 	# option to display problem, only once else it cause problems 
                   1863:         # with the form later since the problem has a form.
1.257     albertel 1864: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1865: 	    my $mode;
1.257     albertel 1866: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1867: 		$mode='both';
1.257     albertel 1868: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1869: 		$mode='text';
1.257     albertel 1870: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1871: 		$mode='answer';
                   1872: 	    }
1.329     albertel 1873: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1874: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1875: 	}
1.441     www      1876: 
1.44      ng       1877: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1878:         # if this subroutine has been called once.
1.41      ng       1879: 	my %keyhash = ();
1.257     albertel 1880: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1881: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1882: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1883: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1884: 
1.257     albertel 1885: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1886: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1887: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1888: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1889: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1890: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1891: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1892: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1893: 	}
1.257     albertel 1894: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1895: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1896: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1897: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1898: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1899: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1900: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1901: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1902: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1903: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1904: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1905: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1906: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1907: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1908: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1909: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1910: 			&build_section_inputs().
1.326     albertel 1911: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1912: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1913: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1914: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1915: 	if ($env{'form.handgrade'} eq 'yes') {
                   1916: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1917: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1918: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1919: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1920: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1921: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1922: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1923: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1924: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1925: 	    }
1.123     ng       1926: 	}
1.41      ng       1927: 	
                   1928: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1929: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1930: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1931: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1932: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1933: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1934: 		'" />'."\n".
                   1935: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1936: 	    $cts++;
                   1937: 	}
                   1938: 	$request->print($prnmsg);
1.32      ng       1939: 
1.257     albertel 1940: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1941: #
                   1942: # Print out the keyword options line
                   1943: #
1.41      ng       1944: 	    $request->print(<<KEYWORDS);
1.38      ng       1945: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1946: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1947: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1948:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1949: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1950: KEYWORDS
1.88      www      1951: #
                   1952: # Load the other essays for similarity check
                   1953: #
1.324     albertel 1954:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1955: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1956: 	    $apath=&escape($apath);
1.88      www      1957: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1958: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1959:         }
                   1960:     }
1.44      ng       1961: 
1.441     www      1962: # This is where output for one specific student would start
                   1963:     my $bgcolor='#DDEEDD';
                   1964:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1965:     $request->print("\n\n".
                   1966:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1967: 
1.257     albertel 1968:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1969: 	my $mode;
1.257     albertel 1970: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1971: 	    $mode='both';
1.257     albertel 1972: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1973: 	    $mode='text';
1.257     albertel 1974: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1975: 	    $mode='answer';
                   1976: 	}
1.329     albertel 1977: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1978: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1979:     }
1.144     albertel 1980: 
1.257     albertel 1981:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1982:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1983: 
1.44      ng       1984:     # Display student info
1.41      ng       1985:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1986:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1987: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1988: 
1.257     albertel 1989:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1990:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1991: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1992: 
1.118     ng       1993:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1994:     my @col_fullnames;
1.56      matthew  1995:     my ($classlist,$fullname);
1.257     albertel 1996:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1997: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1998: 	for (keys (%$handgrade)) {
1.44      ng       1999: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  2000: 					    '.maxcollaborators',
                   2001:                                             $symb,$udom,$uname);
                   2002: 	    next if ($ncol <= 0);
                   2003:             s/\_/\./g;
                   2004:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       2005:             my @goodcollaborators = ();
                   2006:             my @badcollaborators  = ();
                   2007: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   2008: 		$_ =~ s/[\$\^\(\)]//g;
                   2009: 		next if ($_ eq '');
1.80      ng       2010: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       2011: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       2012: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       2013: 		# Doing this grep allows 'fuzzy' specification
                   2014: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   2015: 		if (! scalar(@Matches)) {
                   2016: 		    push @badcollaborators,$_;
                   2017: 		} else {
                   2018: 		    push @goodcollaborators, @Matches;
                   2019: 		}
1.80      ng       2020: 	    }
1.86      ng       2021:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  2022:                 $result.='<b>Collaborators: </b>';
1.86      ng       2023:                 foreach (@goodcollaborators) {
                   2024: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   2025: 		    push @col_fullnames, $givenn.' '.$lastname;
                   2026: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   2027: 		}
1.57      matthew  2028:                 $result.='<br />'."\n";
1.150     albertel 2029: 		my ($part)=split(/\./,$_);
1.86      ng       2030: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 2031: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   2032: 		    "\n";
1.86      ng       2033: 	    }
                   2034: 	    if (scalar(@badcollaborators) > 0) {
                   2035: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2036: 		$result.='This student has submitted ';
                   2037: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   2038: 		$result .= ': '.join(', ',@badcollaborators);
                   2039: 		$result .= '</td></tr></table>';
                   2040: 	    }         
                   2041: 	    if (scalar(@badcollaborators > $ncol)) {
                   2042: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   2043: 		$result .= 'This student has submitted too many '.
                   2044: 		    'collaborators.  Maximum is '.$ncol.'.';
                   2045: 		$result .= '</td></tr></table>';
                   2046: 	    }
1.41      ng       2047: 	}
                   2048:     }
1.44      ng       2049:     $request->print($result."\n");
1.33      ng       2050: 
1.44      ng       2051:     # print student answer/submission
                   2052:     # Options are (1) Handgaded submission only
                   2053:     #             (2) Last submission, includes submission that is not handgraded 
                   2054:     #                  (for multi-response type part)
                   2055:     #             (3) Last submission plus the parts info
                   2056:     #             (4) The whole record for this student
1.257     albertel 2057:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 2058: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   2059: 	my $lastsubonly=''.
                   2060: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   2061: 	     $$timestamp)."</td></tr>\n";
                   2062: 	if ($$timestamp eq '') {
                   2063: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   2064: 	} else {
                   2065: 	    my %seenparts;
1.375     albertel 2066: 	    my @part_response_id = &flatten_responseType($responseType);
                   2067: 	    foreach my $part (@part_response_id) {
1.393     albertel 2068: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   2069: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   2070: 
1.375     albertel 2071: 		my ($partid,$respid) = @{ $part };
1.324     albertel 2072: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 2073: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 2074: 		    if (exists($seenparts{$partid})) { next; }
                   2075: 		    $seenparts{$partid}=1;
1.207     albertel 2076: 		    my $submitby='<b>Part:</b> '.$display_part.
                   2077: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 2078: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 2079: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 2080: 			'\');" target="_self">'.
1.257     albertel 2081: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 2082: 		    $request->print($submitby);
                   2083: 		    next;
                   2084: 		}
                   2085: 		my $responsetype = $responseType->{$partid}->{$respid};
                   2086: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 2087: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 2088: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   2089: 			' )</span>&nbsp; &nbsp;'.
                   2090: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 2091: 		    next;
                   2092: 		}
                   2093: 		foreach (@$string) {
                   2094: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 2095: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 2096: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   2097: 		    # Similarity check
                   2098: 		    my $similar='';
1.257     albertel 2099: 		    if($env{'form.checkPlag'}){
1.151     albertel 2100: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 2101: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 2102: 			if ($osim) {
                   2103: 			    $osim=int($osim*100.0);
1.426     albertel 2104: 			    my %old_course_desc = 
                   2105: 				&Apache::lonnet::coursedescription($ocrsid,
                   2106: 								   {'one_time' => 1});
                   2107: 
                   2108: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 2109: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 2110: 				    $osim,
                   2111: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 2112: 				    $oname,$odom,
1.426     albertel 2113: 				    $old_course_desc{'description'},
1.427     albertel 2114: 				    $old_course_desc{'num'},
1.426     albertel 2115: 				    $old_course_desc{'domain'}).
1.398     albertel 2116: 				'</span></h3><blockquote><i>'.
1.151     albertel 2117: 				&keywords_highlight($oessay).
                   2118: 				'</i></blockquote><hr />';
                   2119: 			}
1.150     albertel 2120: 		    }
1.151     albertel 2121: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2122: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2123: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2124: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2125: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2126: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2127: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2128: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2129: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2130: 			if (@$files) {
1.398     albertel 2131: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2132: 			    my $file_counter = 0;
1.313     banghart 2133: 			    foreach my $file (@$files) {
1.303     banghart 2134: 			        $file_counter ++;
1.232     albertel 2135: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2136: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2137: 			    }
1.236     albertel 2138: 			    $lastsubonly.='<br />';
1.41      ng       2139: 			}
1.151     albertel 2140: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2141: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2142: 					 $respid,\%record,$order);
                   2143: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2144: 		    }
                   2145: 		}
                   2146: 	    }
1.151     albertel 2147: 	}
                   2148: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2149: 	$request->print($lastsubonly);
1.257     albertel 2150:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2151: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2152: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2153:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2154: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2155: 								 $env{'request.course.id'},
1.44      ng       2156: 								 $last,'.submission',
                   2157: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2158:     }
1.120     ng       2159: 
1.121     ng       2160:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2161: 	.$udom.'" />'."\n");
1.41      ng       2162:     
1.44      ng       2163:     # return if view submission with no grading option
1.257     albertel 2164:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2165: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2166: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2167: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2168: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2169: 	if (($env{'form.command'} eq 'submission') || 
                   2170: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2171: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2172: 	}
1.180     albertel 2173: 	$request->print($toGrade);
1.41      ng       2174: 	return;
1.180     albertel 2175:     } else {
                   2176: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2177:     }
1.33      ng       2178: 
1.121     ng       2179:     # essay grading message center
1.257     albertel 2180:     if ($env{'form.handgrade'} eq 'yes') {
                   2181: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2182: 	my $msgfor = $givenn.' '.$lastname;
                   2183: 	if (scalar(@col_fullnames) > 0) {
                   2184: 	    my $lastone = pop @col_fullnames;
                   2185: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2186: 	}
                   2187: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2188: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2189: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2190: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2191: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2192: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2193: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2194: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2195: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2196: 	    '<br />&nbsp;('.
                   2197: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2198: 	$request->print($result);
1.118     ng       2199:     }
1.300     albertel 2200:     if ($perm{'vgr'}) {
1.297     www      2201: 	$request->print('<br />'.
1.300     albertel 2202: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2203: 						   $uname,$udom,'check'));
1.297     www      2204:     }
1.300     albertel 2205:     if ($perm{'opa'}) {
1.297     www      2206: 	$request->print('<br />'.
1.300     albertel 2207: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2208: 					 $uname,$udom,$symb,'check'));
1.297     www      2209:     }
1.41      ng       2210: 
                   2211:     my %seen = ();
                   2212:     my @partlist;
1.129     ng       2213:     my @gradePartRespid;
1.375     albertel 2214:     my @part_response_id = &flatten_responseType($responseType);
                   2215:     foreach my $part_response_id (@part_response_id) {
                   2216:     	my ($partid,$respid) = @{ $part_response_id };
                   2217: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2218: 	next if ($seen{$partid} > 0);
1.41      ng       2219: 	$seen{$partid}++;
1.393     albertel 2220: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2221: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2222: 	push @partlist,$partid;
1.129     ng       2223: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2224: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2225:     }
1.45      ng       2226:     $result='<input type="hidden" name="partlist'.$counter.
                   2227: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2228:     $result.='<input type="hidden" name="gradePartRespid'.
                   2229: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2230:     my $ctr = 0;
                   2231:     while ($ctr < scalar(@partlist)) {
                   2232: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2233: 	    $partlist[$ctr].'" />'."\n";
                   2234: 	$ctr++;
                   2235:     }
                   2236:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2237: 
1.441     www      2238: # Done with printing info for one student
                   2239: 
                   2240:     $request->print('</td></tr></table></p>');
                   2241: 
                   2242: 
1.41      ng       2243:     # print end of form
                   2244:     if ($counter == $total) {
1.297     www      2245: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2246: 	$endform.='<input type="button" value="Save & Next" '.
                   2247: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2248: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2249: 	my $ntstu ='<select name="NTSTU">'.
                   2250: 	    '<option>1</option><option>2</option>'.
                   2251: 	    '<option>3</option><option>5</option>'.
                   2252: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2253: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2254: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2255: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2256: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2257: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2258: 	    '<input type="button" value="Next" '.
1.417     albertel 2259: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2260: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2261:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2262:             "' name='increment' />";
1.45      ng       2263: 	$endform.='</td><tr></table></form>';
1.324     albertel 2264: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2265: 	$request->print($endform);
                   2266:     }
                   2267:     return '';
1.38      ng       2268: }
                   2269: 
1.44      ng       2270: #--- Retrieve the last submission for all the parts
1.38      ng       2271: sub get_last_submission {
1.119     ng       2272:     my ($returnhash)=@_;
1.46      ng       2273:     my (@string,$timestamp);
1.119     ng       2274:     if ($$returnhash{'version'}) {
1.46      ng       2275: 	my %lasthash=();
                   2276: 	my ($version);
1.119     ng       2277: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2278: 	    foreach my $key (sort(split(/\:/,
                   2279: 					$$returnhash{$version.':keys'}))) {
                   2280: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2281: 		$timestamp = 
                   2282: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2283: 	    }
                   2284: 	}
1.397     albertel 2285: 	foreach my $key (keys(%lasthash)) {
                   2286: 	    next if ($key !~ /\.submission$/);
                   2287: 
                   2288: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2289: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2290: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2291: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2292: 	}
                   2293:     }
1.397     albertel 2294:     if (!@string) {
                   2295: 	$string[0] =
1.398     albertel 2296: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2297:     }
                   2298:     return (\@string,\$timestamp);
1.38      ng       2299: }
1.35      ng       2300: 
1.44      ng       2301: #--- High light keywords, with style choosen by user.
1.38      ng       2302: sub keywords_highlight {
1.44      ng       2303:     my $string    = shift;
1.257     albertel 2304:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2305:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2306:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2307:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2308:     foreach my $keyword (@keylist) {
                   2309: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2310:     }
                   2311:     return $string;
1.38      ng       2312: }
1.36      ng       2313: 
1.44      ng       2314: #--- Called from submission routine
1.38      ng       2315: sub processHandGrade {
1.41      ng       2316:     my ($request) = shift;
1.324     albertel 2317:     my $symb   = &get_symb($request);
                   2318:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2319:     my $button = $env{'form.gradeOpt'};
                   2320:     my $ngrade = $env{'form.NCT'};
                   2321:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2322:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2323:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2324: 
1.44      ng       2325:     if ($button eq 'Save & Next') {
                   2326: 	my $ctr = 0;
                   2327: 	while ($ctr < $ngrade) {
1.257     albertel 2328: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2329: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2330: 	    if ($errorflag eq 'no_score') {
                   2331: 		$ctr++;
                   2332: 		next;
                   2333: 	    }
1.104     albertel 2334: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2335: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2336: 		$ctr++;
                   2337: 		next;
                   2338: 	    }
1.257     albertel 2339: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2340: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2341: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2342:             my ($feedurl,$showsymb) =
                   2343: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2344: 	    my $messagetail;
1.62      albertel 2345: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2346: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2347: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2348: 		$subject.=' ['.$restitle.']';
1.44      ng       2349: 		my (@msgnum) = split(/,/,$includemsg);
                   2350: 		foreach (@msgnum) {
1.257     albertel 2351: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2352: 		}
1.80      ng       2353: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2354: 		if ($env{'form.withgrades'.$ctr}) {
                   2355: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2356: 		    $messagetail = " for <a href=\"".
1.418     albertel 2357: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2358: 		}
                   2359: 		$msgstatus = 
                   2360:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2361: 						     $message.$messagetail,
1.418     albertel 2362:                                                      undef,$feedurl,undef,
1.386     raeburn  2363:                                                      undef,undef,$showsymb,
                   2364:                                                      $restitle);
                   2365: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2366: 				$msgstatus);
1.44      ng       2367: 	    }
1.257     albertel 2368: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2369: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2370: 		foreach my $collabstr (@collabstrs) {
                   2371: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2372: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2373: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2374: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2375: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2376: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2377: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2378: 			    next;
1.418     albertel 2379: 			} elsif ($message ne '') {
                   2380: 			    my ($baseurl,$showsymb) = 
                   2381: 				&get_feedurl_and_symb($symb,$collaborator,
                   2382: 						      $udom);
                   2383: 			    if ($env{'form.withgrades'.$ctr}) {
                   2384: 				$messagetail = " for <a href=\"".
1.386     raeburn  2385:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2386: 			    }
1.418     albertel 2387: 			    $msgstatus = 
                   2388: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2389: 			}
1.44      ng       2390: 		    }
                   2391: 		}
                   2392: 	    }
                   2393: 	    $ctr++;
                   2394: 	}
                   2395:     }
                   2396: 
1.257     albertel 2397:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2398: 	# Keywords sorted in alphabatical order
1.257     albertel 2399: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2400: 	my %keyhash = ();
1.257     albertel 2401: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2402: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2403: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2404: 	$env{'form.keywords'} = join(' ',@keywords);
                   2405: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2406: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2407: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2408: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2409: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2410: 
                   2411: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2412: 	# New messages are saved in env for the next student.
1.119     ng       2413: 	# All messages are saved in nohist_handgrade.db
                   2414: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2415: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2416: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2417: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2418: 		$idx++;
                   2419: 	    }
                   2420: 	    $ctr++;
1.41      ng       2421: 	}
1.119     ng       2422: 	$ctr = 0;
                   2423: 	while ($ctr < $ngrade) {
1.257     albertel 2424: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2425: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2426: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2427: 		$idx++;
                   2428: 	    }
                   2429: 	    $ctr++;
1.41      ng       2430: 	}
1.257     albertel 2431: 	$env{'form.savemsgN'} = --$idx;
                   2432: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2433: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2434: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2435:     }
1.44      ng       2436:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2437:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2438:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2439: 	my ($ctr,$total) = (0,0);
                   2440: 	while ($ctr < $ngrade) {
1.257     albertel 2441: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2442: 	    $ctr++;
                   2443: 	}
1.257     albertel 2444: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2445: 	$ctr = 0;
                   2446: 	while ($ctr < $total) {
1.257     albertel 2447: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2448: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2449: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2450: 	    &submission($request,$ctr,$total-1);
1.41      ng       2451: 	    $ctr++;
                   2452: 	}
                   2453: 	return '';
                   2454:     }
1.36      ng       2455: 
1.121     ng       2456: # Go directly to grade student - from submission or link from chart page
1.120     ng       2457:     if ($button eq 'Grade Student') {
1.324     albertel 2458: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2459: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2460: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2461: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2462: 	&submission($request,0,0);
                   2463: 	return '';
                   2464:     }
                   2465: 
1.44      ng       2466:     # Get the next/previous one or group of students
1.257     albertel 2467:     my $firststu = $env{'form.unamedom0'};
                   2468:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2469:     my $ctr = 2;
1.41      ng       2470:     while ($laststu eq '') {
1.257     albertel 2471: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2472: 	$ctr++;
                   2473: 	$laststu = $firststu if ($ctr > $ngrade);
                   2474:     }
1.44      ng       2475: 
1.41      ng       2476:     my (@parsedlist,@nextlist);
                   2477:     my ($nextflg) = 0;
1.294     albertel 2478:     foreach (sort 
                   2479: 	     {
                   2480: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2481: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2482: 		 }
                   2483: 		 return $a cmp $b;
                   2484: 	     } (keys(%$fullname))) {
1.41      ng       2485: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2486: 	    push @parsedlist,$_;
                   2487: 	}
                   2488: 	$nextflg = 1 if ($_ eq $laststu);
                   2489: 	if ($button eq 'Previous') {
                   2490: 	    last if ($_ eq $firststu);
                   2491: 	    push @parsedlist,$_;
                   2492: 	}
                   2493:     }
                   2494:     $ctr = 0;
                   2495:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2496:     my ($partlist) = &response_type($symb);
1.41      ng       2497:     foreach my $student (@parsedlist) {
1.257     albertel 2498: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2499: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2500: 	
                   2501: 	if ($submitonly eq 'queued') {
                   2502: 	    my %queue_status = 
                   2503: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2504: 							$udom,$uname);
                   2505: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2506: 	}
                   2507: 
1.156     albertel 2508: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2509: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2510: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2511: 	    my $submitted = 0;
1.248     albertel 2512: 	    my $ungraded = 0;
                   2513: 	    my $incorrect = 0;
1.145     albertel 2514: 	    foreach (keys(%status)) {
                   2515: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2516: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2517: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2518: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2519: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2520: 		    $submitted = 0;
                   2521: 		}
1.41      ng       2522: 	    }
1.156     albertel 2523: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2524: 				     $submitonly eq 'incorrect' ||
                   2525: 				     $submitonly eq 'graded'));
1.248     albertel 2526: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2527: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2528: 	}
                   2529: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2530: 	last if ($ctr == $ntstu);
1.41      ng       2531: 	$ctr++;
                   2532:     }
1.36      ng       2533: 
1.41      ng       2534:     $ctr = 0;
                   2535:     my $total = scalar(@nextlist)-1;
1.39      ng       2536: 
1.41      ng       2537:     foreach (sort @nextlist) {
                   2538: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2539: 	$env{'form.student'}  = $uname;
                   2540: 	$env{'form.userdom'}  = $udom;
                   2541: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2542: 	&submission($request,$ctr,$total);
                   2543: 	$ctr++;
                   2544:     }
                   2545:     if ($total < 0) {
1.398     albertel 2546: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2547: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2548: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2549: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2550: 	$request->print($the_end);
                   2551:     }
                   2552:     return '';
1.38      ng       2553: }
1.36      ng       2554: 
1.44      ng       2555: #---- Save the score and award for each student, if changed
1.38      ng       2556: sub saveHandGrade {
1.324     albertel 2557:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2558:     my @version_parts;
1.104     albertel 2559:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2560: 					   $env{'request.course.id'});
1.104     albertel 2561:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2562:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2563:     my @parts_graded;
1.77      ng       2564:     my %newrecord  = ();
                   2565:     my ($pts,$wgt) = ('','');
1.269     raeburn  2566:     my %aggregate = ();
                   2567:     my $aggregateflag = 0;
1.301     albertel 2568:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2569:     foreach my $new_part (@parts) {
1.337     banghart 2570: 	#collaborator ($submi may vary for different parts
1.259     banghart 2571: 	if ($submitter && $new_part ne $part) { next; }
                   2572: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2573: 	if ($dropMenu eq 'excused') {
1.259     banghart 2574: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2575: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2576: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2577: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2578: 		}
1.364     banghart 2579: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2580: 	    }
1.125     ng       2581: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2582: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2583: 	    foreach my $key (keys (%record)) {
1.259     banghart 2584: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2585: 	    }
1.259     banghart 2586: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2587: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2588:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2589: 
                   2590:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2591: 					       [$new_part]);
                   2592:             my $aggtries =$totaltries;
1.269     raeburn  2593:             if ($last_resets{$new_part}) {
1.270     albertel 2594:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2595: 					   $new_part);
1.269     raeburn  2596:             }
1.270     albertel 2597: 
                   2598:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2599:             if ($aggtries > 0) {
1.327     albertel 2600:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2601:                 $aggregateflag = 1;
                   2602:             }
1.125     ng       2603: 	} elsif ($dropMenu eq '') {
1.259     banghart 2604: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2605: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2606: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2607: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2608: 		next;
                   2609: 	    }
1.259     banghart 2610: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2611: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2612: 	    my $partial= $pts/$wgt;
1.259     banghart 2613: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2614: 		#do not update score for part if not changed.
1.346     banghart 2615:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2616: 		next;
1.251     banghart 2617: 	    } else {
1.259     banghart 2618: 	        push @parts_graded, $new_part;
1.153     albertel 2619: 	    }
1.259     banghart 2620: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2621: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2622: 	    }
1.259     banghart 2623: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2624: 	    if ($partial == 0) {
1.153     albertel 2625: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2626: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2627: 		}
1.41      ng       2628: 	    } else {
1.153     albertel 2629: 		if ($record{$reckey} ne 'correct_by_override') {
                   2630: 		    $newrecord{$reckey} = 'correct_by_override';
                   2631: 		}
                   2632: 	    }	    
                   2633: 	    if ($submitter && 
1.259     banghart 2634: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2635: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2636: 	    }
1.259     banghart 2637: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2638: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2639: 	}
1.259     banghart 2640: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2641: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2642: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2643: 	        $dropMenu eq 'reset status')
                   2644: 	   {
1.342     banghart 2645: 	    push (@version_parts,$new_part);
1.259     banghart 2646: 	}
1.41      ng       2647:     }
1.301     albertel 2648:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2649:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2650: 
1.344     albertel 2651:     if (%newrecord) {
                   2652:         if (@version_parts) {
1.364     banghart 2653:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2654:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2655: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2656: 	    foreach my $new_part (@version_parts) {
                   2657: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2658: 				$new_part,\%newrecord);
                   2659: 	    }
1.259     banghart 2660:         }
1.44      ng       2661: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2662: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2663: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2664: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2665:     }
1.269     raeburn  2666:     if ($aggregateflag) {
                   2667:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2668: 			      $cdom,$cnum);
1.269     raeburn  2669:     }
1.301     albertel 2670:     return ('',$pts,$wgt);
1.36      ng       2671: }
1.322     albertel 2672: 
1.380     albertel 2673: sub check_and_remove_from_queue {
                   2674:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2675:     my @ungraded_parts;
                   2676:     foreach my $part (@{$parts}) {
                   2677: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2678: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2679: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2680: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2681: 		) {
                   2682: 	    push(@ungraded_parts, $part);
                   2683: 	}
                   2684:     }
                   2685:     if ( !@ungraded_parts ) {
                   2686: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2687: 					       $cnum,$domain,$stuname);
                   2688:     }
                   2689: }
                   2690: 
1.337     banghart 2691: sub handback_files {
                   2692:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2693:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2694:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2695: 
                   2696:     my @part_response_id = &flatten_responseType($responseType);
                   2697:     foreach my $part_response_id (@part_response_id) {
                   2698:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2699: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2700:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2701:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2702:                 my $file_counter = 1;
1.367     albertel 2703: 		my $file_msg;
1.337     banghart 2704:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2705:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2706:                     my ($directory,$answer_file) = 
                   2707:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2708:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2709: 		        &file_name_version_ext($answer_file);
1.355     banghart 2710: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2711: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2712: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2713:                     # fix file name
                   2714:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2715:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2716:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2717:             	                                $save_file_name);
1.337     banghart 2718:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2719:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2720:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2721:                     } else {
1.360     banghart 2722:                         # mark the file as read only
                   2723:                         my @files = ($save_file_name);
1.372     albertel 2724:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2725:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2726: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2727: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2728: 			}
                   2729:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2730: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2731: 
1.337     banghart 2732:                     }
                   2733:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2734:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2735:                     $file_counter++;
                   2736:                 }
1.367     albertel 2737: 		my $subject = "File Handed Back by Instructor ";
                   2738: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2739: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2740: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2741: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2742: 		my ($feedurl,$showsymb) = 
                   2743: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2744:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2745: 		my $msgstatus = 
                   2746:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2747: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2748:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2749:             }
                   2750:         }
1.338     banghart 2751:     return;
1.337     banghart 2752: }
                   2753: 
1.418     albertel 2754: sub get_feedurl_and_symb {
                   2755:     my ($symb,$uname,$udom) = @_;
                   2756:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2757:     $url = &Apache::lonnet::clutter($url);
                   2758:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2759: 					$symb,$udom,$uname);
                   2760:     if ($encrypturl =~ /^yes$/i) {
                   2761: 	&Apache::lonenc::encrypted(\$url,1);
                   2762: 	&Apache::lonenc::encrypted(\$symb,1);
                   2763:     }
                   2764:     return ($url,$symb);
                   2765: }
                   2766: 
1.313     banghart 2767: sub get_submitted_files {
                   2768:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2769:     my @files;
                   2770:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2771:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2772:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2773:     	    push(@files,$file_url.$file);
                   2774:         }
                   2775:     }
                   2776:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2777:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2778:     }
                   2779:     return (\@files);
                   2780: }
1.322     albertel 2781: 
1.269     raeburn  2782: # ----------- Provides number of tries since last reset.
                   2783: sub get_num_tries {
                   2784:     my ($record,$last_reset,$part) = @_;
                   2785:     my $timestamp = '';
                   2786:     my $num_tries = 0;
                   2787:     if ($$record{'version'}) {
                   2788:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2789:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2790:                 $timestamp = $$record{$version.':timestamp'};
                   2791:                 if ($timestamp > $last_reset) {
                   2792:                     $num_tries ++;
                   2793:                 } else {
                   2794:                     last;
                   2795:                 }
                   2796:             }
                   2797:         }
                   2798:     }
                   2799:     return $num_tries;
                   2800: }
                   2801: 
                   2802: # ----------- Determine decrements required in aggregate totals 
                   2803: sub decrement_aggs {
                   2804:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2805:     my %decrement = (
                   2806:                         attempts => 0,
                   2807:                         users => 0,
                   2808:                         correct => 0
                   2809:                     );
                   2810:     $decrement{'attempts'} = $aggtries;
                   2811:     if ($solvedstatus =~ /^correct/) {
                   2812:         $decrement{'correct'} = 1;
                   2813:     }
                   2814:     if ($aggtries == $totaltries) {
                   2815:         $decrement{'users'} = 1;
                   2816:     }
                   2817:     foreach my $type (keys (%decrement)) {
                   2818:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2819:     }
                   2820:     return;
                   2821: }
                   2822: 
                   2823: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2824: sub get_last_resets {
1.270     albertel 2825:     my ($symb,$courseid,$partids) =@_;
                   2826:     my %last_resets;
1.269     raeburn  2827:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2828:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2829:     my @keys;
                   2830:     foreach my $part (@{$partids}) {
                   2831: 	push(@keys,"$symb\0$part\0resettime");
                   2832:     }
                   2833:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2834: 				     $cdom,$cname);
                   2835:     foreach my $part (@{$partids}) {
                   2836: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2837:     }
1.270     albertel 2838:     return %last_resets;
1.269     raeburn  2839: }
                   2840: 
1.251     banghart 2841: # ----------- Handles creating versions for portfolio files as answers
                   2842: sub version_portfiles {
1.343     banghart 2843:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2844:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2845:     my @returned_keys;
1.255     banghart 2846:     my $parts = join('|', @$parts_graded);
1.359     www      2847:     my $portfolio_root = &propath($domain,$stu_name).
                   2848: 	'/userfiles/portfolio';
1.277     albertel 2849:     foreach my $key (keys(%$record)) {
1.259     banghart 2850:         my $new_portfiles;
1.263     banghart 2851:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2852:             my @versioned_portfiles;
1.367     albertel 2853:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2854:             foreach my $file (@portfiles) {
1.306     banghart 2855:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2856:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2857: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2858: 		    &file_name_version_ext($answer_file);
1.306     banghart 2859:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2860:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2861:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2862:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2863:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2864:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2865:                         [$directory.$new_answer],
1.306     banghart 2866:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2867:                 }
1.252     banghart 2868:             }
1.343     banghart 2869:             $$record{$key} = join(',',@versioned_portfiles);
                   2870:             push(@returned_keys,$key);
1.251     banghart 2871:         }
                   2872:     } 
1.343     banghart 2873:     return (@returned_keys);   
1.305     banghart 2874: }
                   2875: 
1.307     banghart 2876: sub get_next_version {
1.341     banghart 2877:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2878:     my $version;
                   2879:     foreach my $row (@$dir_list) {
                   2880:         my ($file) = split(/\&/,$row,2);
                   2881:         my ($file_name,$file_version,$file_ext) =
                   2882: 	    &file_name_version_ext($file);
                   2883:         if (($file_name eq $answer_name) && 
                   2884: 	    ($file_ext eq $answer_ext)) {
                   2885:                 # gets here if filename and extension match, regardless of version
                   2886:                 if ($file_version ne '') {
                   2887:                 # a versioned file is found  so save it for later
                   2888:                 if ($file_version > $version) {
                   2889: 		    $version = $file_version;
                   2890: 	        }
                   2891:             }
                   2892:         }
                   2893:     } 
                   2894:     $version ++;
                   2895:     return($version);
                   2896: }
                   2897: 
1.305     banghart 2898: sub version_selected_portfile {
1.306     banghart 2899:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2900:     my ($answer_name,$answer_ver,$answer_ext) =
                   2901:         &file_name_version_ext($file_name);
                   2902:     my $new_answer;
                   2903:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2904:     if($env{'form.copy'} eq '-1') {
                   2905:         $new_answer = 'problem getting file';
                   2906:     } else {
                   2907:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2908:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2909:                             $stu_name,$domain,'copy',
                   2910: 		        '/portfolio'.$directory.$new_answer);
                   2911:     }    
                   2912:     return ($new_answer);
1.251     banghart 2913: }
                   2914: 
1.304     albertel 2915: sub file_name_version_ext {
                   2916:     my ($file)=@_;
                   2917:     my @file_parts = split(/\./, $file);
                   2918:     my ($name,$version,$ext);
                   2919:     if (@file_parts > 1) {
                   2920: 	$ext=pop(@file_parts);
                   2921: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2922: 	    $version=pop(@file_parts);
                   2923: 	}
                   2924: 	$name=join('.',@file_parts);
                   2925:     } else {
                   2926: 	$name=join('.',@file_parts);
                   2927:     }
                   2928:     return($name,$version,$ext);
                   2929: }
                   2930: 
1.44      ng       2931: #--------------------------------------------------------------------------------------
                   2932: #
                   2933: #-------------------------- Next few routines handles grading by section or whole class
                   2934: #
                   2935: #--- Javascript to handle grading by section or whole class
1.42      ng       2936: sub viewgrades_js {
                   2937:     my ($request) = shift;
                   2938: 
1.41      ng       2939:     $request->print(<<VIEWJAVASCRIPT);
                   2940: <script type="text/javascript" language="javascript">
1.45      ng       2941:    function writePoint(partid,weight,point) {
1.125     ng       2942: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2943: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2944: 	if (point == "textval") {
1.125     ng       2945: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2946: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2947: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2948: 		var resetbox = false;
                   2949: 		for (var i=0; i<radioButton.length; i++) {
                   2950: 		    if (radioButton[i].checked) {
                   2951: 			textbox.value = i;
                   2952: 			resetbox = true;
                   2953: 		    }
                   2954: 		}
                   2955: 		if (!resetbox) {
                   2956: 		    textbox.value = "";
                   2957: 		}
                   2958: 		return;
                   2959: 	    }
1.109     matthew  2960: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2961: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2962: 				   ") greater than the weight for the part. Accept?");
                   2963: 		if (resp == false) {
                   2964: 		    textbox.value = "";
                   2965: 		    return;
                   2966: 		}
                   2967: 	    }
1.42      ng       2968: 	    for (var i=0; i<radioButton.length; i++) {
                   2969: 		radioButton[i].checked=false;
1.109     matthew  2970: 		if (parseFloat(point) == i) {
1.42      ng       2971: 		    radioButton[i].checked=true;
                   2972: 		}
                   2973: 	    }
1.41      ng       2974: 
1.42      ng       2975: 	} else {
1.125     ng       2976: 	    textbox.value = parseFloat(point);
1.42      ng       2977: 	}
1.41      ng       2978: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2979: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2980: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2981: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2982: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2983: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2984: 	    if (saveval != "correct") {
                   2985: 		scorename.value = point;
1.43      ng       2986: 		if (selname[0].selected != true) {
                   2987: 		    selname[0].selected = true;
                   2988: 		}
1.42      ng       2989: 	    }
                   2990: 	}
1.125     ng       2991: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2992:     }
                   2993: 
                   2994:     function writeRadText(partid,weight) {
1.125     ng       2995: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2996: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2997:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2998: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2999: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       3000: 	    for (var i=0; i<radioButton.length; i++) {
                   3001: 		radioButton[i].checked=false;
                   3002: 
                   3003: 	    }
                   3004: 	    textbox.value = "";
                   3005: 
                   3006: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3007: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3008: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3009: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3010: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3011: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3012: 		if ((saveval != "correct") || override) {
1.42      ng       3013: 		    scorename.value = "";
1.125     ng       3014: 		    if (selval[1].selected) {
                   3015: 			selname[1].selected = true;
                   3016: 		    } else {
                   3017: 			selname[2].selected = true;
                   3018: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   3019: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   3020: 		    }
1.42      ng       3021: 		}
                   3022: 	    }
1.43      ng       3023: 	} else {
                   3024: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3025: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3026: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3027: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3028: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3029: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      3030: 		if ((saveval != "correct") || override) {
1.125     ng       3031: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       3032: 		    selname[0].selected = true;
                   3033: 		}
                   3034: 	    }
                   3035: 	}	    
1.42      ng       3036:     }
                   3037: 
                   3038:     function changeSelect(partid,user) {
1.125     ng       3039: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3040: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       3041: 	var point  = textbox.value;
1.125     ng       3042: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       3043: 
1.109     matthew  3044: 	if (isNaN(point) || parseFloat(point) < 0) {
                   3045: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       3046: 	    textbox.value = "";
                   3047: 	    return;
                   3048: 	}
1.109     matthew  3049: 	if (parseFloat(point) > parseFloat(weight)) {
                   3050: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       3051: 			       ") greater than the weight of the part. Accept?");
                   3052: 	    if (resp == false) {
                   3053: 		textbox.value = "";
                   3054: 		return;
                   3055: 	    }
                   3056: 	}
1.42      ng       3057: 	selval[0].selected = true;
                   3058:     }
                   3059: 
                   3060:     function changeOneScore(partid,user) {
1.125     ng       3061: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   3062: 	if (selval[1].selected || selval[2].selected) {
                   3063: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   3064: 	    if (selval[2].selected) {
                   3065: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   3066: 	    }
1.269     raeburn  3067:         }
1.42      ng       3068:     }
                   3069: 
                   3070:     function resetEntry(numpart) {
                   3071: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       3072: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   3073: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   3074: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   3075: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       3076: 	    for (var i=0; i<radioButton.length; i++) {
                   3077: 		radioButton[i].checked=false;
                   3078: 
                   3079: 	    }
                   3080: 	    textbox.value = "";
                   3081: 	    selval[0].selected = true;
                   3082: 
                   3083: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       3084: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 3085: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       3086: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   3087: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   3088: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   3089: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   3090: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   3091: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       3092: 		if (saveselval == "excused") {
1.43      ng       3093: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       3094: 		} else {
1.43      ng       3095: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       3096: 		}
                   3097: 	    }
1.41      ng       3098: 	}
1.42      ng       3099:     }
                   3100: 
1.41      ng       3101: </script>
                   3102: VIEWJAVASCRIPT
1.42      ng       3103: }
                   3104: 
1.44      ng       3105: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       3106: sub viewgrades {
                   3107:     my ($request) = shift;
                   3108:     &viewgrades_js($request);
1.41      ng       3109: 
1.324     albertel 3110:     my ($symb) = &get_symb($request);
1.168     albertel 3111:     #need to make sure we have the correct data for later EXT calls, 
                   3112:     #thus invalidate the cache
                   3113:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3114:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3115:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3116:     &Apache::lonnet::clear_EXT_cache_status();
                   3117: 
1.398     albertel 3118:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3119:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3120: 
                   3121:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3122:     $result.=&jscriptNform($symb);
1.41      ng       3123: 
1.44      ng       3124:     #beginning of class grading form
1.442     banghart 3125:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3126:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3127: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3128: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3129: 	&build_section_inputs().
1.257     albertel 3130: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3131: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3132: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3133: 
1.126     ng       3134:     my $sectionClass;
1.430     banghart 3135:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3136:     if ($env{'form.section'} eq 'all') {
1.126     ng       3137: 	$sectionClass='Class </h3>';
1.257     albertel 3138:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3139: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3140:     } else {
1.431     banghart 3141: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3142:     }
1.431     banghart 3143:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3144:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3145: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3146:     #radio buttons/text box for assigning points for a section or class.
                   3147:     #handles different parts of a problem
1.375     albertel 3148:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3149:     my %weight = ();
                   3150:     my $ctsparts = 0;
1.41      ng       3151:     $result.='<table border="0">';
1.45      ng       3152:     my %seen = ();
1.375     albertel 3153:     my @part_response_id = &flatten_responseType($responseType);
                   3154:     foreach my $part_response_id (@part_response_id) {
                   3155:     	my ($partid,$respid) = @{ $part_response_id };
                   3156: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3157: 	next if $seen{$partid};
                   3158: 	$seen{$partid}++;
1.375     albertel 3159: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3160: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3161: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3162: 
1.44      ng       3163: 	$result.='<input type="hidden" name="partid_'.
                   3164: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3165: 	$result.='<input type="hidden" name="weight_'.
                   3166: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3167: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3168: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3169: 	$result.='<table border="0"><tr>';  
1.41      ng       3170: 	my $ctr = 0;
1.42      ng       3171: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3172: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3173: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3174: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3175: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3176: 	    $ctr++;
                   3177: 	}
                   3178: 	$result.='</tr></table>';
1.44      ng       3179: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3180: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3181: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3182: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3183: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3184: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3185: 		$weight{$partid}.')"> '.
1.401     albertel 3186: 	    '<option selected="selected"> </option>'.
1.125     ng       3187: 	    '<option>excused</option>'.
1.265     www      3188: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3189:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3190: 	$ctsparts++;
1.41      ng       3191:     }
1.52      albertel 3192:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3193: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3194:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3195: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3196: 
1.44      ng       3197:     #table listing all the students in a section/class
                   3198:     #header of table
1.126     ng       3199:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3200:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3201: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3202: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3203:     my (@parts) = sort(&getpartlist($symb));
                   3204:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3205:     my @partids = ();
1.41      ng       3206:     foreach my $part (@parts) {
                   3207: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3208: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3209: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3210: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3211:         push(@partids, $partid);
1.324     albertel 3212: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3213: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3214: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3215: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3216: 	    next;
1.207     albertel 3217: 	} else {
                   3218: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3219: 	}
1.53      albertel 3220: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3221: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3222:     }
                   3223:     $result.='</tr>';
1.44      ng       3224: 
1.270     albertel 3225:     my %last_resets = 
                   3226: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3227: 
1.41      ng       3228:     #get info for each student
1.44      ng       3229:     #list all the students - with points and grade status
1.257     albertel 3230:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3231:     my $ctr = 0;
1.294     albertel 3232:     foreach (sort 
                   3233: 	     {
                   3234: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3235: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3236: 		 }
                   3237: 		 return $a cmp $b;
                   3238: 	     } (keys(%$fullname))) {
1.126     ng       3239: 	$ctr++;
1.324     albertel 3240: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3241: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3242:     }
                   3243:     $result.='</table></td></tr></table>';
                   3244:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3245:     $result.='<input type="button" value="Save" '.
1.417     albertel 3246: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3247:     if (scalar(%$fullname) eq 0) {
                   3248: 	my $colspan=3+scalar(@parts);
1.433     banghart 3249: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3250:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3251: 	$result='<span class="LC_warning">'.
                   3252: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3253: 	        $section_display, $stu_status).
1.433     banghart 3254: 	    '</span>';
1.96      albertel 3255:     }
1.324     albertel 3256:     $result.=&show_grading_menu_form($symb);
1.41      ng       3257:     return $result;
                   3258: }
                   3259: 
1.44      ng       3260: #--- call by previous routine to display each student
1.41      ng       3261: sub viewstudentgrade {
1.324     albertel 3262:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3263:     my ($uname,$udom) = split(/:/,$student);
                   3264:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3265:     my %aggregates = (); 
1.233     albertel 3266:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3267: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3268: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3269: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3270: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3271: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3272:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3273:     foreach my $apart (@$parts) {
                   3274: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3275: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3276:         $result.='<td align="center">';
1.269     raeburn  3277:         my ($aggtries,$totaltries);
                   3278:         unless (exists($aggregates{$part})) {
1.270     albertel 3279: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3280: 
                   3281: 	    $aggtries = $totaltries;
1.269     raeburn  3282:             if ($$last_resets{$part}) {  
1.270     albertel 3283:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3284: 					   $part);
                   3285:             }
1.269     raeburn  3286:             $result.='<input type="hidden" name="'.
                   3287:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3288:             $result.='<input type="hidden" name="'.
                   3289:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3290:             $aggregates{$part} = 1;
                   3291:         }
1.41      ng       3292: 	if ($type eq 'awarded') {
1.320     albertel 3293: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3294: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3295: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3296: 	    $result.='<input type="text" name="'.
1.89      albertel 3297: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3298: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3299: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3300: 	} elsif ($type eq 'solved') {
                   3301: 	    my ($status,$foo)=split(/_/,$score,2);
                   3302: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3303: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3304: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3305: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3306: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3307: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3308: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3309: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3310: 	    $result.='<option>reset status</option>';
1.126     ng       3311: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3312: 	} else {
                   3313: 	    $result.='<input type="hidden" name="'.
                   3314: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3315: 		    "\n";
1.233     albertel 3316: 	    $result.='<input type="text" name="'.
1.122     ng       3317: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3318: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3319: 	}
                   3320:     }
                   3321:     $result.='</tr>';
                   3322:     return $result;
1.38      ng       3323: }
                   3324: 
1.44      ng       3325: #--- change scores for all the students in a section/class
                   3326: #    record does not get update if unchanged
1.38      ng       3327: sub editgrades {
1.41      ng       3328:     my ($request) = @_;
                   3329: 
1.324     albertel 3330:     my $symb=&get_symb($request);
1.433     banghart 3331:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3332:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3333:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3334:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3335: 
1.44      ng       3336:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3337:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3338: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3339: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3340: 
                   3341:     my %scoreptr = (
                   3342: 		    'correct'  =>'correct_by_override',
                   3343: 		    'incorrect'=>'incorrect_by_override',
                   3344: 		    'excused'  =>'excused',
                   3345: 		    'ungraded' =>'ungraded_attempted',
                   3346: 		    'nothing'  => '',
                   3347: 		    );
1.257     albertel 3348:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3349: 
1.44      ng       3350:     my (@partid);
                   3351:     my %weight = ();
1.54      albertel 3352:     my %columns = ();
1.44      ng       3353:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3354: 
1.324     albertel 3355:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3356:     my $header;
1.257     albertel 3357:     while ($ctr < $env{'form.totalparts'}) {
                   3358: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3359: 	push @partid,$partid;
1.257     albertel 3360: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3361: 	$ctr++;
1.54      albertel 3362:     }
1.324     albertel 3363:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3364:     foreach my $partid (@partid) {
                   3365: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3366: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3367: 	$columns{$partid}=2;
                   3368: 	foreach my $stores (@parts) {
                   3369: 	    my ($part,$type) = &split_part_type($stores);
                   3370: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3371: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3372: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3373: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3374: 	    $display =~ s/Number of Attempts/Tries/;
                   3375: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3376: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3377: 	    $columns{$partid}+=2;
                   3378: 	}
                   3379:     }
                   3380:     foreach my $partid (@partid) {
1.324     albertel 3381: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3382: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3383: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3384: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3385: 
1.44      ng       3386:     }
                   3387:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3388:     $result .= $header;
1.44      ng       3389:     $result .= '</tr>'."\n";
1.93      albertel 3390:     my $noupdate;
1.126     ng       3391:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3392:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3393: 	my $line;
1.257     albertel 3394: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3395: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3396: 	my %newrecord;
                   3397: 	my $updateflag = 0;
1.281     albertel 3398: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3399: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3400: 	if (!&canmodify($usec)) {
1.126     ng       3401: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3402: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3403: 	    next;
                   3404: 	}
1.269     raeburn  3405:         my %aggregate = ();
                   3406:         my $aggregateflag = 0;
1.281     albertel 3407: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3408: 	foreach (@partid) {
1.257     albertel 3409: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3410: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3411: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3412: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3413: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3414: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3415: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3416: 	    my $score;
                   3417: 	    if ($partial eq '') {
1.257     albertel 3418: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3419: 	    } elsif ($partial > 0) {
                   3420: 		$score = 'correct_by_override';
                   3421: 	    } elsif ($partial == 0) {
                   3422: 		$score = 'incorrect_by_override';
                   3423: 	    }
1.257     albertel 3424: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3425: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3426: 
1.292     albertel 3427: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3428: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3429: 	    if ($dropMenu eq 'reset status' &&
                   3430: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3431: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3432: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3433: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3434: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3435: 		$updateflag = 1;
1.269     raeburn  3436:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3437:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3438:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3439:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3440:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3441:                     $aggregateflag = 1;
                   3442:                 }
1.139     albertel 3443: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3444: 		$updateflag = 1;
                   3445: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3446: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3447: 		$rec_update++;
1.125     ng       3448: 	    }
                   3449: 
1.93      albertel 3450: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3451: 		'<td align="center">'.$awarded.
                   3452: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3453: 
1.54      albertel 3454: 
                   3455: 	    my $partid=$_;
                   3456: 	    foreach my $stores (@parts) {
                   3457: 		my ($part,$type) = &split_part_type($stores);
                   3458: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3459: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3460: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3461: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3462: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3463: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3464: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3465: 		    $updateflag=1;
                   3466: 		}
1.93      albertel 3467: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3468: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3469: 	    }
1.44      ng       3470: 	}
1.93      albertel 3471: 	$line.='</tr>'."\n";
1.301     albertel 3472: 
                   3473: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3474: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3475: 
1.44      ng       3476: 	if ($updateflag) {
                   3477: 	    $count++;
1.257     albertel 3478: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3479: 				    $udom,$uname);
1.301     albertel 3480: 
                   3481: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3482: 					      $cnum,$udom,$uname)) {
                   3483: 		# need to figure out if should be in queue.
                   3484: 		my %record =  
                   3485: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3486: 					     $udom,$uname);
                   3487: 		my $all_graded = 1;
                   3488: 		my $none_graded = 1;
                   3489: 		foreach my $part (@parts) {
                   3490: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3491: 			$all_graded = 0;
                   3492: 		    } else {
                   3493: 			$none_graded = 0;
                   3494: 		    }
                   3495: 		}
                   3496: 
                   3497: 		if ($all_graded || $none_graded) {
                   3498: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3499: 							   $symb,$cdom,$cnum,
                   3500: 							   $udom,$uname);
                   3501: 		}
                   3502: 	    }
                   3503: 
1.126     ng       3504: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3505: 	    $updateCtr++;
1.93      albertel 3506: 	} else {
1.126     ng       3507: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3508: 	    $noupdateCtr++;
1.44      ng       3509: 	}
1.269     raeburn  3510:         if ($aggregateflag) {
                   3511:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3512: 				  $cdom,$cnum);
1.269     raeburn  3513:         }
1.93      albertel 3514:     }
                   3515:     if ($noupdate) {
1.126     ng       3516: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3517: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3518: 	$result .= '<tr bgcolor="#ffffff"><td align="center" colspan="'.$numcols.'">No Changes Occurred For the Students Below</td></tr><tr bgcolor="#ffffde">'.$noupdate;
1.44      ng       3519:     }
1.72      ng       3520:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3521: 	&show_grading_menu_form ($symb);
1.125     ng       3522:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3523: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3524: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3525:     return $title.$msg.$result;
1.5       albertel 3526: }
1.54      albertel 3527: 
                   3528: sub split_part_type {
                   3529:     my ($partstr) = @_;
                   3530:     my ($temp,@allparts)=split(/_/,$partstr);
                   3531:     my $type=pop(@allparts);
1.439     albertel 3532:     my $part=join('_',@allparts);
1.54      albertel 3533:     return ($part,$type);
                   3534: }
                   3535: 
1.44      ng       3536: #------------- end of section for handling grading by section/class ---------
                   3537: #
                   3538: #----------------------------------------------------------------------------
                   3539: 
1.5       albertel 3540: 
1.44      ng       3541: #----------------------------------------------------------------------------
                   3542: #
                   3543: #-------------------------- Next few routines handles grading by csv upload
                   3544: #
                   3545: #--- Javascript to handle csv upload
1.27      albertel 3546: sub csvupload_javascript_reverse_associate {
1.246     albertel 3547:     my $error1=&mt('You need to specify the username or ID');
                   3548:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3549:   return(<<ENDPICK);
                   3550:   function verify(vf) {
                   3551:     var foundsomething=0;
                   3552:     var founduname=0;
1.243     albertel 3553:     var foundID=0;
1.27      albertel 3554:     for (i=0;i<=vf.nfields.value;i++) {
                   3555:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3556:       if (i==0 && tw!=0) { foundID=1; }
                   3557:       if (i==1 && tw!=0) { founduname=1; }
                   3558:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3559:     }
1.246     albertel 3560:     if (founduname==0 && foundID==0) {
                   3561: 	alert('$error1');
                   3562: 	return;
1.27      albertel 3563:     }
                   3564:     if (foundsomething==0) {
1.246     albertel 3565: 	alert('$error2');
                   3566: 	return;
1.27      albertel 3567:     }
                   3568:     vf.submit();
                   3569:   }
                   3570:   function flip(vf,tf) {
                   3571:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3572:     var i;
                   3573:     for (i=0;i<=vf.nfields.value;i++) {
                   3574:       //can not pick the same destination field for both name and domain
                   3575:       if (((i ==0)||(i ==1)) && 
                   3576:           ((tf==0)||(tf==1)) && 
                   3577:           (i!=tf) &&
                   3578:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3579:         eval('vf.f'+i+'.selectedIndex=0;')
                   3580:       }
                   3581:     }
                   3582:   }
                   3583: ENDPICK
                   3584: }
                   3585: 
                   3586: sub csvupload_javascript_forward_associate {
1.246     albertel 3587:     my $error1=&mt('You need to specify the username or ID');
                   3588:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3589:   return(<<ENDPICK);
                   3590:   function verify(vf) {
                   3591:     var foundsomething=0;
                   3592:     var founduname=0;
1.243     albertel 3593:     var foundID=0;
1.27      albertel 3594:     for (i=0;i<=vf.nfields.value;i++) {
                   3595:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3596:       if (tw==1) { foundID=1; }
                   3597:       if (tw==2) { founduname=1; }
                   3598:       if (tw>3) { foundsomething=1; }
1.27      albertel 3599:     }
1.246     albertel 3600:     if (founduname==0 && foundID==0) {
                   3601: 	alert('$error1');
                   3602: 	return;
1.27      albertel 3603:     }
                   3604:     if (foundsomething==0) {
1.246     albertel 3605: 	alert('$error2');
                   3606: 	return;
1.27      albertel 3607:     }
                   3608:     vf.submit();
                   3609:   }
                   3610:   function flip(vf,tf) {
                   3611:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3612:     var i;
                   3613:     //can not pick the same destination field twice
                   3614:     for (i=0;i<=vf.nfields.value;i++) {
                   3615:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3616:         eval('vf.f'+i+'.selectedIndex=0;')
                   3617:       }
                   3618:     }
                   3619:   }
                   3620: ENDPICK
                   3621: }
                   3622: 
1.26      albertel 3623: sub csvuploadmap_header {
1.324     albertel 3624:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3625:     my $javascript;
1.257     albertel 3626:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3627: 	$javascript=&csvupload_javascript_reverse_associate();
                   3628:     } else {
                   3629: 	$javascript=&csvupload_javascript_forward_associate();
                   3630:     }
1.45      ng       3631: 
1.324     albertel 3632:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3633:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3634:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3635:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3636:     $request->print(<<ENDPICK);
1.26      albertel 3637: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3638: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3639: $result
1.326     albertel 3640: <hr />
1.26      albertel 3641: <h3>Identify fields</h3>
                   3642: Total number of records found in file: $distotal <hr />
                   3643: Enter as many fields as you can. The system will inform you and bring you back
                   3644: to this page if the data selected is insufficient to run your class.<hr />
                   3645: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3646: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3647: <input type="hidden" name="associate"  value="" />
                   3648: <input type="hidden" name="phase"      value="three" />
                   3649: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3650: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3651: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3652: <input type="hidden" name="upfile_associate" 
1.257     albertel 3653:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3654: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3655: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3656: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3657: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3658: <hr />
                   3659: <script type="text/javascript" language="Javascript">
                   3660: $javascript
                   3661: </script>
                   3662: ENDPICK
1.118     ng       3663:     return '';
1.26      albertel 3664: 
                   3665: }
                   3666: 
                   3667: sub csvupload_fields {
1.324     albertel 3668:     my ($symb) = @_;
                   3669:     my (@parts) = &getpartlist($symb);
1.243     albertel 3670:     my @fields=(['ID','Student ID'],
                   3671: 		['username','Student Username'],
                   3672: 		['domain','Student Domain']);
1.324     albertel 3673:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3674:     foreach my $part (sort(@parts)) {
                   3675: 	my @datum;
                   3676: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3677: 	my $name=$part;
                   3678: 	if  (!$display) { $display = $name; }
                   3679: 	@datum=($name,$display);
1.244     albertel 3680: 	if ($name=~/^stores_(.*)_awarded/) {
                   3681: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3682: 	}
1.41      ng       3683: 	push(@fields,\@datum);
                   3684:     }
                   3685:     return (@fields);
1.26      albertel 3686: }
                   3687: 
                   3688: sub csvuploadmap_footer {
1.41      ng       3689:     my ($request,$i,$keyfields) =@_;
                   3690:     $request->print(<<ENDPICK);
1.26      albertel 3691: </table>
                   3692: <input type="hidden" name="nfields" value="$i" />
                   3693: <input type="hidden" name="keyfields" value="$keyfields" />
                   3694: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3695: </form>
                   3696: ENDPICK
                   3697: }
                   3698: 
1.283     albertel 3699: sub checkforfile_js {
1.86      ng       3700:     my $result =<<CSVFORMJS;
                   3701: <script type="text/javascript" language="javascript">
                   3702:     function checkUpload(formname) {
                   3703: 	if (formname.upfile.value == "") {
                   3704: 	    alert("Please use the browse button to select a file from your local directory.");
                   3705: 	    return false;
                   3706: 	}
                   3707: 	formname.submit();
                   3708:     }
                   3709:     </script>
                   3710: CSVFORMJS
1.283     albertel 3711:     return $result;
                   3712: }
                   3713: 
                   3714: sub upcsvScores_form {
                   3715:     my ($request) = shift;
1.324     albertel 3716:     my ($symb)=&get_symb($request);
1.283     albertel 3717:     if (!$symb) {return '';}
                   3718:     my $result=&checkforfile_js();
1.257     albertel 3719:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3720:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3721:     $result.=$table;
1.326     albertel 3722:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3723:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3724:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3725: 	'.</b></td></tr>'."\n";
                   3726:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3727:     my $upload=&mt("Upload Scores");
1.86      ng       3728:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3729:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3730:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3731:     $result.=<<ENDUPFORM;
1.106     albertel 3732: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3733: <input type="hidden" name="symb" value="$symb" />
                   3734: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3735: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3736: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3737: $upfile_select
1.370     www      3738: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3739: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3740: </form>
                   3741: ENDUPFORM
1.370     www      3742:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3743:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3744:     .'</td></tr></table>'."\n";
1.86      ng       3745:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3746:     $result.=&show_grading_menu_form($symb);
1.86      ng       3747:     return $result;
                   3748: }
                   3749: 
                   3750: 
1.26      albertel 3751: sub csvuploadmap {
1.41      ng       3752:     my ($request)= @_;
1.324     albertel 3753:     my ($symb)=&get_symb($request);
1.41      ng       3754:     if (!$symb) {return '';}
1.72      ng       3755: 
1.41      ng       3756:     my $datatoken;
1.257     albertel 3757:     if (!$env{'form.datatoken'}) {
1.41      ng       3758: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3759:     } else {
1.257     albertel 3760: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3761: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3762:     }
1.41      ng       3763:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3764:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3765:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3766:     my ($i,$keyfields);
                   3767:     if (@records) {
1.324     albertel 3768: 	my @fields=&csvupload_fields($symb);
1.45      ng       3769: 
1.257     albertel 3770: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3771: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3772: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3773: 							  \@fields);
                   3774: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3775: 	    chop($keyfields);
                   3776: 	} else {
                   3777: 	    unshift(@fields,['none','']);
                   3778: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3779: 							    \@fields);
1.311     banghart 3780:             foreach my $rec (@records) {
                   3781:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3782:                 if (%temp) {
                   3783:                     $keyfields=join(',',sort(keys(%temp)));
                   3784:                     last;
                   3785:                 }
                   3786:             }
1.41      ng       3787: 	}
                   3788:     }
                   3789:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3790:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3791: 
1.41      ng       3792:     return '';
1.27      albertel 3793: }
                   3794: 
1.246     albertel 3795: sub csvuploadoptions {
1.41      ng       3796:     my ($request)= @_;
1.324     albertel 3797:     my ($symb)=&get_symb($request);
1.257     albertel 3798:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3799:     my $ignore=&mt('Ignore First Line');
                   3800:     $request->print(<<ENDPICK);
                   3801: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3802: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3803: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3804: <!--
1.246     albertel 3805: <p>
                   3806: <label>
                   3807:    <input type="checkbox" name="show_full_results" />
                   3808:    Show a table of all changes
                   3809: </label>
                   3810: </p>
1.302     albertel 3811: -->
1.246     albertel 3812: <p>
                   3813: <label>
                   3814:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3815:    Overwrite any existing score
                   3816: </label>
                   3817: </p>
                   3818: ENDPICK
                   3819:     my %fields=&get_fields();
                   3820:     if (!defined($fields{'domain'})) {
1.257     albertel 3821: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3822: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3823:     }
1.257     albertel 3824:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3825: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3826: 	my $cleankey=$1;
                   3827: 	if ($cleankey eq 'command') { next; }
                   3828: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3829: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3830:     }
                   3831:     # FIXME do a check for any duplicated user ids...
                   3832:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3833:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3834: <hr /></form>'."\n");
1.324     albertel 3835:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3836:     return '';
                   3837: }
                   3838: 
                   3839: sub get_fields {
                   3840:     my %fields;
1.257     albertel 3841:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3842:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3843: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3844: 	    if ($env{'form.f'.$i} ne 'none') {
                   3845: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3846: 	    }
                   3847: 	} else {
1.257     albertel 3848: 	    if ($env{'form.f'.$i} ne 'none') {
                   3849: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3850: 	    }
                   3851: 	}
1.27      albertel 3852:     }
1.246     albertel 3853:     return %fields;
                   3854: }
                   3855: 
                   3856: sub csvuploadassign {
                   3857:     my ($request)= @_;
1.324     albertel 3858:     my ($symb)=&get_symb($request);
1.246     albertel 3859:     if (!$symb) {return '';}
1.345     bowersj2 3860:     my $error_msg = '';
1.246     albertel 3861:     &Apache::loncommon::load_tmp_file($request);
                   3862:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3863:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3864:     my %fields=&get_fields();
1.41      ng       3865:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3866:     my $courseid=$env{'request.course.id'};
1.97      albertel 3867:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3868:     my @notallowed;
1.41      ng       3869:     my @skipped;
                   3870:     my $countdone=0;
                   3871:     foreach my $grade (@gradedata) {
                   3872: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3873: 	my $domain;
                   3874: 	if ($entries{$fields{'domain'}}) {
                   3875: 	    $domain=$entries{$fields{'domain'}};
                   3876: 	} else {
1.257     albertel 3877: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3878: 	}
1.243     albertel 3879: 	$domain=~s/\s//g;
1.41      ng       3880: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3881: 	$username=~s/\s//g;
1.243     albertel 3882: 	if (!$username) {
                   3883: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3884: 	    $id=~s/\s//g;
1.243     albertel 3885: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3886: 	    $username=$ids{$id};
                   3887: 	}
1.41      ng       3888: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3889: 	    my $id=$entries{$fields{'ID'}};
                   3890: 	    $id=~s/\s//g;
                   3891: 	    if ($id) {
                   3892: 		push(@skipped,"$id:$domain");
                   3893: 	    } else {
                   3894: 		push(@skipped,"$username:$domain");
                   3895: 	    }
1.41      ng       3896: 	    next;
                   3897: 	}
1.108     albertel 3898: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3899: 	if (!&canmodify($usec)) {
                   3900: 	    push(@notallowed,"$username:$domain");
                   3901: 	    next;
                   3902: 	}
1.244     albertel 3903: 	my %points;
1.41      ng       3904: 	my %grades;
                   3905: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3906: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3907: 		$dest eq 'domain') { next; }
                   3908: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3909: 	    if ($dest=~/stores_(.*)_points/) {
                   3910: 		my $part=$1;
                   3911: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3912: 					      $symb,$domain,$username);
1.345     bowersj2 3913:                 if ($wgt) {
                   3914:                     $entries{$fields{$dest}}=~s/\s//g;
                   3915:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3916:                     my $award='correct_by_override';
                   3917:                     $grades{"resource.$part.awarded"}=$pcr;
                   3918:                     $grades{"resource.$part.solved"}=$award;
                   3919:                     $points{$part}=1;
                   3920:                 } else {
                   3921:                     $error_msg = "<br />" .
                   3922:                         &mt("Some point values were assigned"
                   3923:                             ." for problems with a weight "
                   3924:                             ."of zero. These values were "
                   3925:                             ."ignored.");
                   3926:                 }
1.244     albertel 3927: 	    } else {
                   3928: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3929: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3930: 		my $store_key=$dest;
                   3931: 		$store_key=~s/^stores/resource/;
                   3932: 		$store_key=~s/_/\./g;
                   3933: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3934: 	    }
1.41      ng       3935: 	}
1.398     albertel 3936: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3937: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.302     albertel 3938: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3939: 					   $env{'request.course.id'},
                   3940: 					   $domain,$username);
                   3941: 	if ($result eq 'ok') {
                   3942: 	    $request->print('.');
                   3943: 	} else {
                   3944: 	    $request->print("<p>
1.398     albertel 3945:                               <span class=\"LC_error\">
                   3946:                                  Failed to save student $username:$domain.
                   3947:                                  Message when trying to save was ($result)
                   3948:                               </span>
1.302     albertel 3949:                              </p>" );
                   3950: 	}
1.41      ng       3951: 	$request->rflush();
                   3952: 	$countdone++;
                   3953:     }
1.398     albertel 3954:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3955:     if (@skipped) {
1.398     albertel 3956: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3957: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3958:     }
                   3959:     if (@notallowed) {
1.398     albertel 3960: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3961: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3962:     }
1.106     albertel 3963:     $request->print("<br />\n");
1.324     albertel 3964:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3965:     return $error_msg;
1.26      albertel 3966: }
1.44      ng       3967: #------------- end of section for handling csv file upload ---------
                   3968: #
                   3969: #-------------------------------------------------------------------
                   3970: #
1.122     ng       3971: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3972: #
                   3973: #--- Select a page/sequence and a student to grade
1.68      ng       3974: sub pickStudentPage {
                   3975:     my ($request) = shift;
                   3976: 
                   3977:     $request->print(<<LISTJAVASCRIPT);
                   3978: <script type="text/javascript" language="javascript">
                   3979: 
                   3980: function checkPickOne(formname) {
1.76      ng       3981:     if (radioSelection(formname.student) == null) {
1.68      ng       3982: 	alert("Please select the student you wish to grade.");
                   3983: 	return;
                   3984:     }
1.125     ng       3985:     ptr = pullDownSelection(formname.selectpage);
                   3986:     formname.page.value = formname["page"+ptr].value;
                   3987:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3988:     formname.submit();
                   3989: }
                   3990: 
                   3991: </script>
                   3992: LISTJAVASCRIPT
1.118     ng       3993:     &commonJSfunctions($request);
1.324     albertel 3994:     my ($symb) = &get_symb($request);
1.257     albertel 3995:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3996:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3997:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3998: 
1.398     albertel 3999:     my $result='<h3><span class="LC_info">&nbsp;'.
                   4000: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       4001: 
1.80      ng       4002:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       4003:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 4004:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4005:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   4006: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   4007: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       4008:     my $ctr=0;
1.68      ng       4009:     foreach (@$titles) {
                   4010: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       4011: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 4012: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       4013: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       4014: 	$ctr++;
1.68      ng       4015:     }
1.326     albertel 4016:     $result.= '</select>'."<br />\n";
1.70      ng       4017:     $ctr=0;
                   4018:     foreach (@$titles) {
                   4019: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4020: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   4021: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   4022: 	$ctr++;
                   4023:     }
1.72      ng       4024:     $result.='<input type="hidden" name="page" />'."\n".
                   4025: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       4026: 
1.401     albertel 4027:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 4028: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       4029: 
1.71      ng       4030:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 4031: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 4032: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 4033: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 4034:     
                   4035:     $result.=&build_section_inputs();
1.442     banghart 4036:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   4037:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       4038: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 4039: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4040: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       4041: 
1.382     albertel 4042:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   4043: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   4044: 
1.80      ng       4045:     $result.='&nbsp;<input type="button" '.
1.126     ng       4046: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       4047: 
1.68      ng       4048:     $request->print($result);
                   4049: 
1.326     albertel 4050:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       4051: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4052: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       4053: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4054: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       4055: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       4056: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       4057:  
1.76      ng       4058:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       4059:     my $ptr = 1;
1.294     albertel 4060:     foreach my $student (sort 
                   4061: 			 {
                   4062: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   4063: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   4064: 			     }
                   4065: 			     return $a cmp $b;
                   4066: 			 } (keys(%$fullname))) {
1.68      ng       4067: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       4068: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   4069: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 4070: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   4071: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       4072: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       4073: 	$ptr++;
                   4074:     }
1.381     albertel 4075:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   4076:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       4077:     $studentTable.='<input type="button" '.
                   4078: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       4079: 
1.324     albertel 4080:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       4081:     $request->print($studentTable);
                   4082: 
                   4083:     return '';
                   4084: }
                   4085: 
                   4086: sub getSymbMap {
1.132     bowersj2 4087:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       4088: 
                   4089:     my %symbx = ();
                   4090:     my @titles = ();
1.117     bowersj2 4091:     my $minder = 0;
                   4092: 
                   4093:     # Gather every sequence that has problems.
1.240     albertel 4094:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   4095: 					       1,0,1);
1.117     bowersj2 4096:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 4097: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 4098: 	    my $title = $minder.'.'.
                   4099: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   4100: 	    push(@titles, $title); # minder in case two titles are identical
                   4101: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 4102: 	    $minder++;
1.241     albertel 4103: 	}
1.68      ng       4104:     }
                   4105:     return \@titles,\%symbx;
                   4106: }
                   4107: 
1.72      ng       4108: #
                   4109: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       4110: sub displayPage {
                   4111:     my ($request) = shift;
                   4112: 
1.324     albertel 4113:     my ($symb) = &get_symb($request);
1.257     albertel 4114:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4115:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4116:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4117:     my $pageTitle = $env{'form.page'};
1.103     albertel 4118:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4119:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4120:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4121: 
                   4122:     #need to make sure we have the correct data for later EXT calls, 
                   4123:     #thus invalidate the cache
                   4124:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4125:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4126:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4127:     &Apache::lonnet::clear_EXT_cache_status();
                   4128: 
1.103     albertel 4129:     if (!&canview($usec)) {
1.398     albertel 4130: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4131: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4132: 	return;
                   4133:     }
1.398     albertel 4134:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4135:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4136: 	'</h3>'."\n";
1.382     albertel 4137:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4138: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4139:     } else {
                   4140: 	delete($env{'form.CODE'});
                   4141:     }
1.71      ng       4142:     &sub_page_js($request);
                   4143:     $request->print($result);
                   4144: 
1.132     bowersj2 4145:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4146:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4147:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4148:     if (!$map) {
1.398     albertel 4149: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4150: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4151: 	return; 
                   4152:     }
1.68      ng       4153:     my $iterator = $navmap->getIterator($map->map_start(),
                   4154: 					$map->map_finish());
                   4155: 
1.71      ng       4156:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4157: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4158: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4159: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4160: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4161: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4162: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4163: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4164: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4165: 
1.382     albertel 4166:     if (defined($env{'form.CODE'})) {
                   4167: 	$studentTable.=
                   4168: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4169:     }
1.381     albertel 4170:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4171: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4172: 	'/check.gif" height="16" border="0" />';
                   4173: 
1.118     ng       4174:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4175: 	' symbol.'."\n".
1.71      ng       4176: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4177: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4178: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4179: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4180: 
1.329     albertel 4181:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4182:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4183:     $iterator->next(); # skip the first BEGIN_MAP
                   4184:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4185:     while ($depth > 0) {
1.68      ng       4186:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4187:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4188: 
1.385     albertel 4189:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4190: 	    my $parts = $curRes->parts();
1.68      ng       4191:             my $title = $curRes->compTitle();
1.71      ng       4192: 	    my $symbx = $curRes->symb();
1.196     albertel 4193: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4194: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4195: 	    $studentTable.='<td valign="top">';
1.382     albertel 4196: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4197: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4198: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4199: 					     undef,'both',\%form);
1.71      ng       4200: 	    } else {
1.382     albertel 4201: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4202: 		$companswer =~ s|<form(.*?)>||g;
                   4203: 		$companswer =~ s|</form>||g;
1.71      ng       4204: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4205: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4206: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4207: #		}
1.116     ng       4208: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4209: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4210: 	    }
                   4211: 
1.257     albertel 4212: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4213: 
1.257     albertel 4214: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4215: 		if ($record{'version'} eq '') {
1.398     albertel 4216: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4217: 		} else {
1.116     ng       4218: 		    my %responseType = ();
                   4219: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4220: 			my @responseIds =$curRes->responseIds($partid);
                   4221: 			my @responseType =$curRes->responseType($partid);
                   4222: 			my %responseIds;
                   4223: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4224: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4225: 			}
                   4226: 			$responseType{$partid} = \%responseIds;
1.116     ng       4227: 		    }
1.148     albertel 4228: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4229: 
1.71      ng       4230: 		}
1.257     albertel 4231: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4232: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4233: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4234: 									$env{'request.course.id'},
1.71      ng       4235: 									'','.submission');
                   4236:  
                   4237: 	    }
1.103     albertel 4238: 	    if (&canmodify($usec)) {
                   4239: 		foreach my $partid (@{$parts}) {
                   4240: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4241: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4242: 		    $question++;
                   4243: 		}
1.196     albertel 4244: 		$prob++;
1.71      ng       4245: 	    }
                   4246: 	    $studentTable.='</td></tr>';
1.68      ng       4247: 
1.103     albertel 4248: 	}
1.68      ng       4249:         $curRes = $iterator->next();
                   4250:     }
                   4251: 
1.381     albertel 4252:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4253: 	'<input type="button" value="Save" '.
1.381     albertel 4254: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4255: 	'</form>'."\n";
1.324     albertel 4256:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4257:     $request->print($studentTable);
                   4258: 
                   4259:     return '';
1.119     ng       4260: }
                   4261: 
                   4262: sub displaySubByDates {
1.148     albertel 4263:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4264:     my $isCODE=0;
1.335     albertel 4265:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4266:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4267:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4268: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4269: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4270: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4271: 	'<td><b>Submission</b></td>'.
                   4272: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4273:     my ($version);
                   4274:     my %mark;
1.148     albertel 4275:     my %orders;
1.119     ng       4276:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4277:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4278: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4279:     }
1.335     albertel 4280: 
                   4281:     my $interaction;
1.119     ng       4282:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4283: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4284: 	if (exists($$record{$version.':resource.0.version'})) {
                   4285: 	    $interaction = $$record{$version.':resource.0.version'};
                   4286: 	}
                   4287: 
                   4288: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4289: 		             : "$version:resource");
1.119     ng       4290: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4291: 	if ($isCODE) {
                   4292: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4293: 	}
1.119     ng       4294: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4295: 	my @displaySub = ();
                   4296: 	foreach my $partid (@{$parts}) {
1.335     albertel 4297: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4298: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4299: 	    
                   4300: 
1.122     ng       4301: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4302: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4303: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4304: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4305: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4306: 
                   4307: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4308: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
1.207     albertel 4309: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4310: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4311: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4312: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4313: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4314: 		    } else {
                   4315: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4316: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4317: 		    }
1.335     albertel 4318: 		    my $responseType=($isTask ? 'Task'
                   4319:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4320: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4321: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4322: 			$orders{$partid}->{$responseId}=
                   4323: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4324: 		    }
1.147     albertel 4325: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4326: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4327: 		}
                   4328: 	    }
1.335     albertel 4329: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4330: 		$displaySub[1].='Checked in by '.
                   4331: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4332: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4333: 		    '<br />';
                   4334: 	    }
                   4335: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4336: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4337: 		    lc($$record{"$where.$partid.award"}).' '.
                   4338: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4339: 		    '<br />';
                   4340: 	    }
1.335     albertel 4341: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4342: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4343: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4344: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4345: 		$displaySub[2].=
                   4346: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4347: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4348: 	    }
                   4349: 	}
                   4350: 	# needed because old essay regrader has not parts info
                   4351: 	if (exists $$record{"$version:resource.regrader"}) {
                   4352: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4353: 	}
                   4354: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4355: 	if ($displaySub[2]) {
                   4356: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4357: 	}
1.382     albertel 4358: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4359:     
1.119     ng       4360:     }
                   4361:     $studentTable.='</table></td></tr></table>';
                   4362:     return $studentTable;
1.71      ng       4363: }
                   4364: 
                   4365: sub updateGradeByPage {
                   4366:     my ($request) = shift;
                   4367: 
1.257     albertel 4368:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4369:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4370:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4371:     my $pageTitle = $env{'form.page'};
1.103     albertel 4372:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4373:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4374:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4375:     if (!&canmodify($usec)) {
1.398     albertel 4376: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4377: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4378: 	return;
                   4379:     }
1.398     albertel 4380:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4381:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4382: 	'</h3>'."\n";
1.70      ng       4383: 
1.68      ng       4384:     $request->print($result);
                   4385: 
1.132     bowersj2 4386:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4387:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4388:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4389:     if (!$map) {
1.398     albertel 4390: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4391: 	my ($symb)=&get_symb($request);
                   4392: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4393: 	return; 
                   4394:     }
1.71      ng       4395:     my $iterator = $navmap->getIterator($map->map_start(),
                   4396: 					$map->map_finish());
1.70      ng       4397: 
1.71      ng       4398:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4399: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4400: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4401: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4402: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4403: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4404: 
                   4405:     $iterator->next(); # skip the first BEGIN_MAP
                   4406:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4407:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4408:     while ($depth > 0) {
1.71      ng       4409:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4410:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4411: 
1.385     albertel 4412:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4413: 	    my $parts = $curRes->parts();
1.71      ng       4414:             my $title = $curRes->compTitle();
                   4415: 	    my $symbx = $curRes->symb();
1.196     albertel 4416: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4417: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4418: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4419: 
                   4420: 	    my %newrecord=();
                   4421: 	    my @displayPts=();
1.269     raeburn  4422:             my %aggregate = ();
                   4423:             my $aggregateflag = 0;
1.71      ng       4424: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4425: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4426: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4427: 
1.257     albertel 4428: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4429: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4430: 		my $partial = $newpts/$wgt;
                   4431: 		my $score;
                   4432: 		if ($partial > 0) {
                   4433: 		    $score = 'correct_by_override';
1.125     ng       4434: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4435: 		    $score = 'incorrect_by_override';
                   4436: 		}
1.257     albertel 4437: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4438: 		if ($dropMenu eq 'excused') {
1.71      ng       4439: 		    $partial = '';
                   4440: 		    $score = 'excused';
1.125     ng       4441: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4442: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4443: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4444: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4445: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4446: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4447: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4448: 		    $changeflag++;
                   4449: 		    $newpts = '';
1.269     raeburn  4450:                     
                   4451:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4452:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4453:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4454:                     if ($aggtries > 0) {
                   4455:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4456:                         $aggregateflag = 1;
                   4457:                     }
1.71      ng       4458: 		}
1.324     albertel 4459: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4460: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4461: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4462: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4463: 		    '&nbsp;<br />';
1.207     albertel 4464: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4465: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4466: 		    '&nbsp;<br />';
1.71      ng       4467: 		$question++;
1.380     albertel 4468: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4469: 
1.71      ng       4470: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4471: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4472: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4473: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4474: 
                   4475: 		$changeflag++;
                   4476: 	    }
                   4477: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4478: 		my %record = 
                   4479: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4480: 					     $udom,$uname);
                   4481: 
                   4482: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4483: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4484: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4485: 		    $newrecord{'resource.CODE'} = '';
                   4486: 		}
1.257     albertel 4487: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4488: 					$udom,$uname);
1.382     albertel 4489: 		%record = &Apache::lonnet::restore($symbx,
                   4490: 						   $env{'request.course.id'},
                   4491: 						   $udom,$uname);
1.380     albertel 4492: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4493: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4494: 	    }
1.380     albertel 4495: 	    
1.269     raeburn  4496:             if ($aggregateflag) {
                   4497:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4498:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4499:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4500:             }
1.125     ng       4501: 
1.71      ng       4502: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4503: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4504: 		'</tr>';
1.68      ng       4505: 
1.196     albertel 4506: 	    $prob++;
1.68      ng       4507: 	}
1.71      ng       4508:         $curRes = $iterator->next();
1.68      ng       4509:     }
1.98      albertel 4510: 
1.71      ng       4511:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4512:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4513:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4514: 		  'The scores were changed for '.
                   4515: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4516:     $request->print($grademsg.$studentTable);
1.68      ng       4517: 
1.70      ng       4518:     return '';
                   4519: }
                   4520: 
1.72      ng       4521: #-------- end of section for handling grading by page/sequence ---------
                   4522: #
                   4523: #-------------------------------------------------------------------
                   4524: 
1.75      albertel 4525: #--------------------Scantron Grading-----------------------------------
                   4526: #
                   4527: #------ start of section for handling grading by page/sequence ---------
                   4528: 
1.423     albertel 4529: =pod
                   4530: 
                   4531: =head1 Bubble sheet grading routines
                   4532: 
1.424     albertel 4533:   For this documentation:
                   4534: 
                   4535:    'scanline' refers to the full line of characters
                   4536:    from the file that we are parsing that represents one entire sheet
                   4537: 
                   4538:    'bubble line' refers to the data
                   4539:    representing the line of bubbles that are on the physical bubble sheet
                   4540: 
                   4541: 
                   4542: The overall process is that a scanned in bubble sheet data is uploaded
                   4543: into a course. When a user wants to grade, they select a
                   4544: sequence/folder of resources, a file of bubble sheet info, and pick
                   4545: one of the predefined configurations for what each scanline looks
                   4546: like.
                   4547: 
                   4548: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4549: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4550: because too light bubbling), 'double bubble' (each bubble line should
                   4551: have no more that one letter picked), invalid or duplicated CODE,
                   4552: invalid student ID
                   4553: 
                   4554: If the CODE option is used that determines the randomization of the
                   4555: homework problems, either way the student ID is looked up into a
                   4556: username:domain.
                   4557: 
                   4558: During the validation phase the instructor can choose to skip scanlines. 
                   4559: 
1.435     foxr     4560: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4561: 
                   4562:   scantron_original_filename (unmodified original file)
                   4563:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4564:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4565: 
                   4566: Also there is a separate hash nohist_scantrondata that contains extra
                   4567: correction information that isn't representable in the bubble sheet
                   4568: file (see &scantron_getfile() for more information)
                   4569: 
                   4570: After all scanlines are either valid, marked as valid or skipped, then
                   4571: foreach line foreach problem in the picked sequence, an ssi request is
                   4572: made that simulates a user submitting their selected letter(s) against
                   4573: the homework problem.
1.423     albertel 4574: 
                   4575: =over 4
                   4576: 
                   4577: 
                   4578: 
                   4579: =item defaultFormData
                   4580: 
                   4581:   Returns html hidden inputs used to hold context/default values.
                   4582: 
                   4583:  Arguments:
                   4584:   $symb - $symb of the current resource 
                   4585: 
                   4586: =cut
1.422     foxr     4587: 
1.81      albertel 4588: sub defaultFormData {
1.324     albertel 4589:     my ($symb)=@_;
1.447     foxr     4590:     return '<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4591:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4592:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4593: }
                   4594: 
1.447     foxr     4595: 
1.423     albertel 4596: =pod 
                   4597: 
                   4598: =item getSequenceDropDown
                   4599: 
                   4600:    Return html dropdown of possible sequences to grade
                   4601:  
                   4602:  Arguments:
                   4603:    $symb - $symb of the current resource 
                   4604: 
                   4605: =cut
1.422     foxr     4606: 
1.75      albertel 4607: sub getSequenceDropDown {
1.423     albertel 4608:     my ($symb)=@_;
1.75      albertel 4609:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4610:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4611:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4612:     my $ctr=0;
                   4613:     foreach (@$titles) {
                   4614: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4615: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4616: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4617: 	    '>'.$showtitle.'</option>'."\n";
                   4618: 	$ctr++;
                   4619:     }
                   4620:     $result.= '</select>';
                   4621:     return $result;
                   4622: }
                   4623: 
1.423     albertel 4624: 
                   4625: =pod 
                   4626: 
                   4627: =item scantron_filenames
                   4628: 
                   4629:    Returns a list of the scantron files in the current course 
                   4630: 
                   4631: =cut
1.422     foxr     4632: 
1.202     albertel 4633: sub scantron_filenames {
1.257     albertel 4634:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4635:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4636:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4637: 				    &propath($cdom,$cname));
1.202     albertel 4638:     my @possiblenames;
1.201     albertel 4639:     foreach my $filename (sort(@files)) {
1.157     albertel 4640: 	($filename)=split(/&/,$filename);
                   4641: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4642: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4643: 	push(@possiblenames,$filename);
                   4644:     }
                   4645:     return @possiblenames;
                   4646: }
                   4647: 
1.423     albertel 4648: =pod 
                   4649: 
                   4650: =item scantron_uploads
                   4651: 
                   4652:    Returns  html drop-down list of scantron files in current course.
                   4653: 
                   4654:  Arguments:
                   4655:    $file2grade - filename to set as selected in the dropdown
                   4656: 
                   4657: =cut
1.422     foxr     4658: 
1.202     albertel 4659: sub scantron_uploads {
1.209     ng       4660:     my ($file2grade) = @_;
1.202     albertel 4661:     my $result=	'<select name="scantron_selectfile">';
                   4662:     $result.="<option></option>";
                   4663:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4664: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4665:     }
                   4666:     $result.="</select>";
                   4667:     return $result;
                   4668: }
                   4669: 
1.423     albertel 4670: =pod 
                   4671: 
                   4672: =item scantron_scantab
                   4673: 
                   4674:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4675:   file.
                   4676: 
                   4677: =cut
1.422     foxr     4678: 
1.82      albertel 4679: sub scantron_scantab {
                   4680:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4681:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4682:     $result.='<option></option>'."\n";
1.82      albertel 4683:     foreach my $line (<$fh>) {
                   4684: 	my ($name,$descrip)=split(/:/,$line);
                   4685: 	if ($name =~ /^\#/) { next; }
                   4686: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4687:     }
                   4688:     $result.='</select>'."\n";
                   4689: 
                   4690:     return $result;
                   4691: }
                   4692: 
1.423     albertel 4693: =pod 
                   4694: 
                   4695: =item scantron_CODElist
                   4696: 
                   4697:   Returns html drop down of the saved CODE lists from current course,
                   4698:   generated from earlier printings.
                   4699: 
                   4700: =cut
1.422     foxr     4701: 
1.186     albertel 4702: sub scantron_CODElist {
1.257     albertel 4703:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4704:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4705:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4706:     my $namechoice='<option></option>';
1.225     albertel 4707:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4708: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4709: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4710: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4711:     }
                   4712:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4713:     return $namechoice;
                   4714: }
                   4715: 
1.423     albertel 4716: =pod 
                   4717: 
                   4718: =item scantron_CODEunique
                   4719: 
                   4720:   Returns the html for "Each CODE to be used once" radio.
                   4721: 
                   4722: =cut
1.422     foxr     4723: 
1.186     albertel 4724: sub scantron_CODEunique {
1.381     albertel 4725:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4726:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4727:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4728:                 </span>
                   4729:                 <span style="white-space: nowrap;">
1.272     albertel 4730:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4731:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4732:                 </span>';
1.186     albertel 4733:     return $result;
                   4734: }
1.423     albertel 4735: 
                   4736: =pod 
                   4737: 
                   4738: =item scantron_selectphase
                   4739: 
                   4740:   Generates the initial screen to start the bubble sheet process.
                   4741:   Allows for - starting a grading run.
1.424     albertel 4742:              - downloading existing scan data (original, corrected
1.423     albertel 4743:                                                 or skipped info)
                   4744: 
                   4745:              - uploading new scan data
                   4746: 
                   4747:  Arguments:
                   4748:   $r          - The Apache request object
                   4749:   $file2grade - name of the file that contain the scanned data to score
                   4750: 
                   4751: =cut
1.186     albertel 4752: 
1.75      albertel 4753: sub scantron_selectphase {
1.209     ng       4754:     my ($r,$file2grade) = @_;
1.324     albertel 4755:     my ($symb)=&get_symb($r);
1.75      albertel 4756:     if (!$symb) {return '';}
1.423     albertel 4757:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4758:     my $default_form_data=&defaultFormData($symb);
                   4759:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4760:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4761:     my $format_selector=&scantron_scantab();
1.186     albertel 4762:     my $CODE_selector=&scantron_CODElist();
                   4763:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4764:     my $result;
1.422     foxr     4765: 
                   4766:     # Chunk of form to prompt for a file to grade and how:
                   4767: 
1.75      albertel 4768:     $result.= <<SCANTRONFORM;
1.162     albertel 4769:     <table width="100%" border="0">
1.75      albertel 4770:     <tr>
1.226     albertel 4771:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4772:       <td bgcolor="#777777">
1.203     albertel 4773:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4774:         $default_form_data
1.75      albertel 4775:         <table width="100%" border="0">
                   4776:           <tr bgcolor="#e6ffff">
1.174     albertel 4777:             <td colspan="2">
                   4778:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4779:             </td>
                   4780:           </tr>
                   4781:           <tr bgcolor="#ffffe6">
1.174     albertel 4782:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4783:           </tr>
                   4784:           <tr bgcolor="#ffffe6">
1.174     albertel 4785:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4786:           </tr>
1.82      albertel 4787:           <tr bgcolor="#ffffe6">
1.174     albertel 4788:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4789:           </tr>
1.157     albertel 4790:           <tr bgcolor="#ffffe6">
1.186     albertel 4791:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4792:           </tr>
                   4793:           <tr bgcolor="#ffffe6">
                   4794:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4795:           </tr>
                   4796:           <tr bgcolor="#ffffe6">
1.187     albertel 4797: 	    <td> Options: </td>
                   4798:             <td>
1.272     albertel 4799: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4800:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4801:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4802: 	    </td>
                   4803:           </tr>
                   4804:           <tr bgcolor="#ffffe6">
1.174     albertel 4805:             <td colspan="2">
1.265     www      4806:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4807:             </td>
                   4808:           </tr>
                   4809:         </table>
1.226     albertel 4810:        </td>
                   4811:      </form>
1.162     albertel 4812:     </tr>
                   4813: SCANTRONFORM
                   4814:    
                   4815:     $r->print($result);
                   4816: 
1.257     albertel 4817:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4818:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4819: 
1.422     foxr     4820: 	# Chunk of form to prompt for a scantron file upload.
                   4821: 
1.162     albertel 4822:         $r->print(<<SCANTRONFORM);
                   4823:     <tr>
                   4824:       <td bgcolor="#777777">
                   4825:         <table width="100%" border="0">
                   4826:           <tr bgcolor="#e6ffff">
                   4827:             <td>
1.174     albertel 4828:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4829:             </td>
                   4830:           </tr>
                   4831:           <tr bgcolor="#ffffe6">
                   4832:             <td>
                   4833: SCANTRONFORM
1.324     albertel 4834:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4835:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4836:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4837:     $r->print(<<UPLOAD);
                   4838:               <script type="text/javascript" language="javascript">
                   4839:     function checkUpload(formname) {
                   4840: 	if (formname.upfile.value == "") {
                   4841: 	    alert("Please use the browse button to select a file from your local directory.");
                   4842: 	    return false;
                   4843: 	}
                   4844: 	formname.submit();
                   4845:     }
                   4846:               </script>
                   4847: 
                   4848:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4849:                 $default_form_data
                   4850:                 <input name='courseid' type='hidden' value='$cnum' />
                   4851:                 <input name='domainid' type='hidden' value='$cdom' />
                   4852:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4853:                 File to upload:<input type="file" name="upfile" size="50" />
                   4854:                 <br />
                   4855:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4856:               </form>
                   4857: UPLOAD
1.162     albertel 4858: 
                   4859:         $r->print(<<SCANTRONFORM);
                   4860:             </td>
                   4861:           </tr>
1.75      albertel 4862:         </table>
                   4863:       </td>
                   4864:     </tr>
1.162     albertel 4865: SCANTRONFORM
                   4866:     }
1.422     foxr     4867: 
                   4868:     # Chunk of the form that prompts to view a scoring office file,
                   4869:     # corrected file, skipped records in a file.
                   4870: 
1.187     albertel 4871:     $r->print(<<SCANTRONFORM);
                   4872:     <tr>
1.226     albertel 4873:       <form action='/adm/grades' name='scantron_download'>
                   4874:         <td bgcolor="#777777">
1.379     albertel 4875: 	  $default_form_data
1.187     albertel 4876:           <input type="hidden" name="command" value="scantron_download" />
                   4877:           <table width="100%" border="0">
                   4878:             <tr bgcolor="#e6ffff">
                   4879:               <td colspan="2">
                   4880:                 &nbsp;<b>Download a scoring office file</b>
                   4881:               </td>
                   4882:             </tr>
                   4883:             <tr bgcolor="#ffffe6">
                   4884:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4885:             </tr>
                   4886:             <tr bgcolor="#ffffe6">
                   4887:               <td colspan="2">
1.293     www      4888:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4889:               </td>
                   4890:             </tr>
                   4891:           </table>
1.226     albertel 4892:         </td>
                   4893:       </form>
1.187     albertel 4894:     </tr>
                   4895: SCANTRONFORM
1.162     albertel 4896: 
                   4897:     $r->print(<<SCANTRONFORM);
1.75      albertel 4898:   </table>
1.81      albertel 4899: $grading_menu_button
1.75      albertel 4900: SCANTRONFORM
1.456   ! banghart 4901:     &Apache::lonpickcode::code_list($r,1);
1.162     albertel 4902:     return
1.75      albertel 4903: }
                   4904: 
1.423     albertel 4905: =pod
                   4906: 
                   4907: =item get_scantron_config
                   4908: 
                   4909:    Parse and return the scantron configuration line selected as a
                   4910:    hash of configuration file fields.
                   4911: 
                   4912:  Arguments:
                   4913:     which - the name of the configuration to parse from the file.
                   4914: 
                   4915: 
                   4916:  Returns:
                   4917:             If the named configuration is not in the file, an empty
                   4918:             hash is returned.
                   4919:     a hash with the fields
                   4920:       name         - internal name for the this configuration setup
                   4921:       description  - text to display to operator that describes this config
                   4922:       CODElocation - if 0 or the string 'none'
                   4923:                           - no CODE exists for this config
                   4924:                      if -1 || the string 'letter'
                   4925:                           - a CODE exists for this config and is
                   4926:                             a string of letters
                   4927:                      Unsupported value (but planned for future support)
                   4928:                           if a positive integer
                   4929:                                - The CODE exists as the first n items from
                   4930:                                  the question section of the form
                   4931:                           if the string 'number'
                   4932:                                - The CODE exists for this config and is
                   4933:                                  a string of numbers
                   4934:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4935:                      the CODE starts
                   4936:       CODElength  - length of the CODE
                   4937:       IDstart     - column where the student ID number starts
                   4938:       IDlength    - length of the student ID info
                   4939:       Qstart      - column where the information from the bubbled
                   4940:                     'questions' start
                   4941:       Qlength     - number of columns comprising a single bubble line from
                   4942:                     the sheet. (usually either 1 or 10)
1.424     albertel 4943:       Qon         - either a single character representing the character used
1.423     albertel 4944:                     to signal a bubble was chosen in the positional setup, or
                   4945:                     the string 'letter' if the letter of the chosen bubble is
                   4946:                     in the final, or 'number' if a number representing the
                   4947:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4948:       Qoff        - the character used to represent that a bubble was
                   4949:                     left blank
1.423     albertel 4950:       PaperID     - if the scanning process generates a unique number for each
                   4951:                     sheet scanned the column that this ID number starts in
                   4952:       PaperIDlength - number of columns that comprise the unique ID number
                   4953:                       for the sheet of paper
1.424     albertel 4954:       FirstName   - column that the first name starts in
1.423     albertel 4955:       FirstNameLength - number of columns that the first name spans
                   4956:  
                   4957:       LastName    - column that the last name starts in
                   4958:       LastNameLength - number of columns that the last name spans
                   4959: 
                   4960: =cut
1.422     foxr     4961: 
1.82      albertel 4962: sub get_scantron_config {
                   4963:     my ($which) = @_;
                   4964:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4965:     my %config;
1.157     albertel 4966:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4967:     foreach my $line (<$fh>) {
                   4968: 	my ($name,$descrip)=split(/:/,$line);
                   4969: 	if ($name ne $which ) { next; }
                   4970: 	chomp($line);
                   4971: 	my @config=split(/:/,$line);
                   4972: 	$config{'name'}=$config[0];
                   4973: 	$config{'description'}=$config[1];
                   4974: 	$config{'CODElocation'}=$config[2];
                   4975: 	$config{'CODEstart'}=$config[3];
                   4976: 	$config{'CODElength'}=$config[4];
                   4977: 	$config{'IDstart'}=$config[5];
                   4978: 	$config{'IDlength'}=$config[6];
                   4979: 	$config{'Qstart'}=$config[7];
                   4980: 	$config{'Qlength'}=$config[8];
                   4981: 	$config{'Qoff'}=$config[9];
                   4982: 	$config{'Qon'}=$config[10];
1.157     albertel 4983: 	$config{'PaperID'}=$config[11];
                   4984: 	$config{'PaperIDlength'}=$config[12];
                   4985: 	$config{'FirstName'}=$config[13];
                   4986: 	$config{'FirstNamelength'}=$config[14];
                   4987: 	$config{'LastName'}=$config[15];
                   4988: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4989: 	last;
                   4990:     }
                   4991:     return %config;
                   4992: }
                   4993: 
1.423     albertel 4994: =pod 
                   4995: 
                   4996: =item username_to_idmap
                   4997: 
                   4998:     creates a hash keyed by student id with values of the corresponding
                   4999:     student username:domain.
                   5000: 
                   5001:   Arguments:
                   5002: 
                   5003:     $classlist - reference to the class list hash. This is a hash
                   5004:                  keyed by student name:domain  whose elements are references
1.424     albertel 5005:                  to arrays containing various chunks of information
1.423     albertel 5006:                  about the student. (See loncoursedata for more info).
                   5007: 
                   5008:   Returns
                   5009:     %idmap - the constructed hash
                   5010: 
                   5011: =cut
                   5012: 
1.82      albertel 5013: sub username_to_idmap {
                   5014:     my ($classlist)= @_;
                   5015:     my %idmap;
                   5016:     foreach my $student (keys(%$classlist)) {
                   5017: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   5018: 	    $student;
                   5019:     }
                   5020:     return %idmap;
                   5021: }
1.423     albertel 5022: 
                   5023: =pod
                   5024: 
1.424     albertel 5025: =item scantron_fixup_scanline
1.423     albertel 5026: 
                   5027:    Process a requested correction to a scanline.
                   5028: 
                   5029:   Arguments:
                   5030:     $scantron_config   - hash from &get_scantron_config()
                   5031:     $scan_data         - hash of correction information 
                   5032:                           (see &scantron_getfile())
                   5033:     $line              - existing scanline
                   5034:     $whichline         - line number of the passed in scanline
                   5035:     $field             - type of change to process 
                   5036:                          (either 
                   5037:                           'ID'     -> correct the student ID number
                   5038:                           'CODE'   -> correct the CODE
                   5039:                           'answer' -> fixup the submitted answers)
                   5040:     
                   5041:    $args               - hash of additional info,
                   5042:                           - 'ID' 
                   5043:                                'newid' -> studentID to use in replacement
1.424     albertel 5044:                                           of existing one
1.423     albertel 5045:                           - 'CODE' 
                   5046:                                'CODE_ignore_dup' - set to true if duplicates
                   5047:                                                    should be ignored.
                   5048: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 5049:                                         if the existing unfound code should
1.423     albertel 5050:                                         be used as is
                   5051:                           - 'answer'
                   5052:                                'response' - new answer or 'none' if blank
                   5053:                                'question' - the bubble line to change
                   5054: 
                   5055:   Returns:
                   5056:     $line - the modified scanline
                   5057: 
                   5058:   Side effects: 
                   5059:     $scan_data - may be updated
                   5060: 
                   5061: =cut
                   5062: 
1.82      albertel 5063: 
1.157     albertel 5064: sub scantron_fixup_scanline {
                   5065:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 5066: 
1.157     albertel 5067:     if ($field eq 'ID') {
                   5068: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 5069: 	    return ($line,1,'New value too large');
1.157     albertel 5070: 	}
                   5071: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   5072: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   5073: 				     $args->{'newid'});
                   5074: 	}
                   5075: 	substr($line,$$scantron_config{'IDstart'}-1,
                   5076: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   5077: 	if ($args->{'newid'}=~/^\s*$/) {
                   5078: 	    &scan_data($scan_data,"$whichline.user",
                   5079: 		       $args->{'username'}.':'.$args->{'domain'});
                   5080: 	}
1.186     albertel 5081:     } elsif ($field eq 'CODE') {
1.192     albertel 5082: 	if ($args->{'CODE_ignore_dup'}) {
                   5083: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   5084: 	}
                   5085: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   5086: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 5087: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   5088: 		return ($line,1,'New CODE value too large');
                   5089: 	    }
                   5090: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   5091: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   5092: 	    }
                   5093: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   5094: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 5095: 	}
1.157     albertel 5096:     } elsif ($field eq 'answer') {
                   5097: 	my $length=$scantron_config->{'Qlength'};
                   5098: 	my $off=$scantron_config->{'Qoff'};
                   5099: 	my $on=$scantron_config->{'Qon'};
                   5100: 	my $answer=${off}x$length;
                   5101: 	if ($args->{'response'} eq 'none') {
                   5102: 	    &scan_data($scan_data,
                   5103: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   5104: 	} else {
1.274     albertel 5105: 	    if ($on eq 'letter') {
                   5106: 		my @alphabet=('A'..'Z');
                   5107: 		$answer=$alphabet[$args->{'response'}];
                   5108: 	    } elsif ($on eq 'number') {
                   5109: 		$answer=$args->{'response'}+1;
1.389     albertel 5110: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5111: 	    } else {
                   5112: 		substr($answer,$args->{'response'},1)=$on;
                   5113: 	    }
1.157     albertel 5114: 	    &scan_data($scan_data,
                   5115: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5116: 	}
                   5117: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5118: 	substr($line,$where-1,$length)=$answer;
                   5119:     }
                   5120:     return $line;
                   5121: }
1.423     albertel 5122: 
                   5123: =pod
                   5124: 
                   5125: =item scan_data
                   5126: 
                   5127:     Edit or look up  an item in the scan_data hash.
                   5128: 
                   5129:   Arguments:
                   5130:     $scan_data  - The hash (see scantron_getfile)
                   5131:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5132:                   scantronfilename_key).
1.423     albertel 5133:     $data        - New value of the hash entry.
                   5134:     $delete      - If true, the entry is removed from the hash.
                   5135: 
                   5136:   Returns:
                   5137:     The new value of the hash table field (undefined if deleted).
                   5138: 
                   5139: =cut
                   5140: 
                   5141: 
1.157     albertel 5142: sub scan_data {
                   5143:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5144:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5145:     if (defined($value)) {
                   5146: 	$scan_data->{$filename.'_'.$key} = $value;
                   5147:     }
                   5148:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5149:     return $scan_data->{$filename.'_'.$key};
                   5150: }
1.423     albertel 5151: 
                   5152: =pod 
                   5153: 
                   5154: =item scantron_parse_scanline
                   5155: 
                   5156:   Decodes a scanline from the selected scantron file
                   5157: 
                   5158:  Arguments:
                   5159:     line             - The text of the scantron file line to process
                   5160:     whichline        - Line number
                   5161:     scantron_config  - Hash describing the format of the scantron lines.
                   5162:     scan_data        - Hash of extra information about the scanline
                   5163:                        (see scantron_getfile for more information)
                   5164:     just_header      - True if should not process question answers but only
                   5165:                        the stuff to the left of the answers.
                   5166:  Returns:
                   5167:    Hash containing the result of parsing the scanline
                   5168: 
                   5169:    Keys are all proceeded by the string 'scantron.'
                   5170: 
                   5171:        CODE    - the CODE in use for this scanline
                   5172:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5173:                  by the operator
                   5174:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5175:                             CODEs were selected, but the usage has been
                   5176:                             forced by the operator
                   5177:        ID  - student ID
                   5178:        PaperID - if used, the ID number printed on the sheet when the 
                   5179:                  paper was scanned
                   5180:        FirstName - first name from the sheet
                   5181:        LastName  - last name from the sheet
                   5182: 
                   5183:      if just_header was not true these key may also exist
                   5184: 
1.447     foxr     5185:        missingerror - a list of bubble ranges that are considered to be answers
                   5186:                       to a single question that don't have any bubbles filled in.
                   5187:                       Of the form questionnumber:firstbubblenumber:count.
                   5188:        doubleerror  - a list of bubble ranges that are considered to be answers
                   5189:                       to a single question that have more than one bubble filled in.
                   5190:                       Of the form questionnumber::firstbubblenumber:count
                   5191:    
                   5192:                 In the above, count is the number of bubble responses in the
                   5193:                 input line needed to represent the possible answers to the question.
                   5194:                 e.g. a radioresponse with 15 choices in an answer sheet with 10 choices
                   5195:                 per line would have count = 2.
                   5196: 
1.423     albertel 5197:        maxquest     - the number of the last bubble line that was parsed
                   5198: 
                   5199:        (<number> starts at 1)
                   5200:        <number>.answer - zero or more letters representing the selected
                   5201:                          letters from the scanline for the bubble line 
                   5202:                          <number>.
                   5203:                          if blank there was either no bubble or there where
                   5204:                          multiple bubbles, (consult the keys missingerror and
                   5205:                          doubleerror if this is an error condition)
                   5206: 
                   5207: =cut
                   5208: 
1.82      albertel 5209: sub scantron_parse_scanline {
1.423     albertel 5210:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5211:     my %record;
1.422     foxr     5212:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5213:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5214:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5215: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5216: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5217: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5218: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5219: 	    $record{'scantron.CODE'}=substr($data,
                   5220: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5221: 					    $$scantron_config{'CODElength'});
1.191     albertel 5222: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5223: 		$record{'scantron.useCODE'}=1;
                   5224: 	    }
1.192     albertel 5225: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5226: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5227: 	    }
1.82      albertel 5228: 	} else {
                   5229: 	    #FIXME interpret first N questions
                   5230: 	}
                   5231:     }
1.83      albertel 5232:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5233: 				  $$scantron_config{'IDlength'});
1.157     albertel 5234:     $record{'scantron.PaperID'}=
                   5235: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5236: 	       $$scantron_config{'PaperIDlength'});
                   5237:     $record{'scantron.FirstName'}=
                   5238: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5239: 	       $$scantron_config{'FirstNamelength'});
                   5240:     $record{'scantron.LastName'}=
                   5241: 	substr($data,$$scantron_config{'LastName'}-1,
                   5242: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5243:     if ($just_header) { return \%record; }
1.194     albertel 5244: 
1.82      albertel 5245:     my @alphabet=('A'..'Z');
                   5246:     my $questnum=0;
1.447     foxr     5247:     my $ansnum  =1;		# Multiple 'answer lines'/question.
                   5248: 
1.82      albertel 5249:     while ($questions) {
1.447     foxr     5250: 	my $answers_needed = $bubble_lines_per_response{$questnum};
                   5251: 	my $answer_length  = $$scantron_config{'Qlength'} * $answers_needed;
                   5252: 
                   5253: 
                   5254: 
1.82      albertel 5255: 	$questnum++;
1.447     foxr     5256: 	my $currentquest = substr($questions,0,$answer_length);
                   5257: 	$questions       = substr($questions,0,$answer_length)='';
                   5258: 	if (length($currentquest) < $answer_length) { next; }
                   5259: 
                   5260: 	# Qon letter implies for each slot in currentquest we have:
                   5261: 	#    ? or * for doubles a letter in A-Z for a bubble and
                   5262:         #    about anything else (esp. a value of Qoff for missing
                   5263: 	#    bubbles.
                   5264: 
                   5265: 
1.239     albertel 5266: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.447     foxr     5267: 
                   5268: 	    if ($currentquest =~ /\?/
                   5269: 		|| $currentquest =~ /\*/
                   5270: 		|| (&occurence_count($currentquest, "[A-Z]") > 1)) {
1.274     albertel 5271: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5272: 		for (my $ans = 0; $ans < $answers_needed; $ans++) { 
                   5273: 		    $record{"scantron.$ansnum.answer"}='';
                   5274: 		    $ansnum++;
                   5275: 		}
                   5276: 
1.389     albertel 5277: 	    } elsif (!defined($currentquest)
1.447     foxr     5278: 		     || (&occurence_count($currentquest, $$scantron_config{'Qoff'}) == length($currentquest))
                   5279: 		     || (&occurence_count($currentquest, "[A-Z]") == 0)) {
                   5280: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5281: 		    $record{"scantron.$ansnum.answer"}='';
                   5282: 		    $ansnum++;
                   5283: 
                   5284: 		}
1.239     albertel 5285: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5286: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5287: 		    $ansnum += $answers_needed;
1.239     albertel 5288: 		}
1.447     foxr     5289: 
1.239     albertel 5290: 	    } else {
1.447     foxr     5291: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5292: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5293: 		    $ansnum++;
                   5294: 		}
1.239     albertel 5295: 	    }
1.447     foxr     5296: 
                   5297: 	# Qon 'number' implies each slot gives a digit that indexes the
                   5298: 	#    the bubbles filled or Qoff or a non number for unbubbled lines.
                   5299:         #    and *? for double bubbles on a line.
                   5300: 	#    these answers are also stored as letters.
                   5301: 
1.239     albertel 5302: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.447     foxr     5303: 	    if ($currentquest =~ /\?/
                   5304: 		|| $currentquest =~ /\*/
                   5305: 		|| (&occurence_count($currentquest, '\d') > 1)) {
1.274     albertel 5306: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5307: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5308: 		    $record{"scantron.$ansnum.answer"}='';
                   5309: 		    $ansnum++;
                   5310: 		}
                   5311: 
1.389     albertel 5312: 	    } elsif (!defined($currentquest)
1.447     foxr     5313: 		     || (&occurence_count($currentquest,$$scantron_config{'Qoff'}) == length($currentquest)) 
                   5314: 		     || (&occurence_count($currentquest, '\d') == 0)) {
                   5315: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5316: 		    $record{"scantron.$ansnum.answer"}='';
                   5317: 		    $ansnum++;
                   5318: 
                   5319: 		}
1.239     albertel 5320: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5321: 		    push(@{$record{"scantron.missingerror"}},$questnum);
1.447     foxr     5322: 		    $ansnum += $answers_needed;
1.239     albertel 5323: 		}
1.447     foxr     5324: 
1.239     albertel 5325: 	    } else {
1.447     foxr     5326: 		$currentquest = &digits_to_letters($currentquest);
                   5327: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5328: 		    $record{"scantron.$ansnum.answer"} = substr($currentquest, $ans, 1);
                   5329: 		    $ansnum++;
1.371     albertel 5330: 		}
1.239     albertel 5331: 	    }
1.82      albertel 5332: 	} else {
1.447     foxr     5333: 
                   5334: 	    # Otherwise there's a positional notation;
                   5335: 	    # each bubble line requires Qlength items, and there are filled in
                   5336: 	    # bubbles for each case where there 'Qon' characters.
                   5337: 	    #
                   5338: 
1.239     albertel 5339: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
1.447     foxr     5340: 
                   5341: 	    # If the split only  giveas us one element.. the full length of the
                   5342: 	    # answser string, no bubbles are filled in:
                   5343: 
                   5344: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}*$answers_needed) {
                   5345: 		for (my $ans = 0; $ans < $answers_needed; $ans++ ) {
                   5346: 		    $record{"scantron.$ansnum.answer"}='';
                   5347: 		    $ansnum++;
                   5348: 
                   5349: 		}
1.239     albertel 5350: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5351: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5352: 		}
1.447     foxr     5353: 	    } elsif (scalar(@array) lt 2) {
                   5354: 
                   5355: 		my $location      = [length($array[0])];
                   5356: 		my $line_num      = $location / $$scantron_config{'Qlength'};
                   5357: 		my $bubble        = $alphabet[$location % $$scantron_config{'Qlength'}];
                   5358: 
                   5359: 		for (my $ans = 0; $ans < $answers_needed; $ans++) {
                   5360: 		    if ($ans eq $line_num) {
                   5361: 			$record{"scantron.$ansnum.answer"} = $bubble;
                   5362: 		    } else {
                   5363: 			$record{"scantron.$ansnum.answer"} = ' ';
                   5364: 		    }
                   5365: 		    $ansnum++;
                   5366: 		}
1.239     albertel 5367: 	    }
1.447     foxr     5368: 	    #  If there's more than one instance of a bubble character
                   5369: 	    #  That's a double bubble; with positional notation we can
                   5370: 	    #  record all the bubbles filled in as well as the 
                   5371: 	    #  fact this response consists of multiple bubbles.
                   5372: 	    #
                   5373: 	    else {
1.239     albertel 5374: 		push(@{$record{'scantron.doubleerror'}},$questnum);
1.447     foxr     5375: 
                   5376: 		my $first_answer = $ansnum;
                   5377: 		for (my $ans =0; $ans < $answers_needed; $ans++) {
                   5378: 		    $record{"scantron.$ansnum.answer"} = '';
                   5379: 		    $ans++;
                   5380: 		}
                   5381: 
1.239     albertel 5382: 		my @ans=@array;
                   5383: 		my $i=length($ans[0]);shift(@ans);
                   5384: 		while ($#ans) {
                   5385: 		    $i+=length($ans[0])+1;
1.447     foxr     5386: 		    my $line   = $i/$$scantron_config{'Qlength'} + $first_answer;
                   5387: 		    my $bubble = $i%$$scantron_config{'Qlength'};
                   5388: 
                   5389: 		    $record{"scantron.$line.answer"}.=$alphabet[$bubble];
1.239     albertel 5390: 		    shift(@ans);
                   5391: 		}
                   5392: 	    }
1.82      albertel 5393: 	}
                   5394:     }
1.83      albertel 5395:     $record{'scantron.maxquest'}=$questnum;
                   5396:     return \%record;
1.82      albertel 5397: }
                   5398: 
1.423     albertel 5399: =pod
                   5400: 
                   5401: =item scantron_add_delay
                   5402: 
                   5403:    Adds an error message that occurred during the grading phase to a
                   5404:    queue of messages to be shown after grading pass is complete
                   5405: 
                   5406:  Arguments:
1.424     albertel 5407:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5408:    $scanline    - the scanline that caused the error
                   5409:    $errormesage - the error message
                   5410:    $errorcode   - a numeric code for the error
                   5411: 
                   5412:  Side Effects:
1.424     albertel 5413:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5414: 
                   5415: =cut
                   5416: 
1.82      albertel 5417: sub scantron_add_delay {
1.140     albertel 5418:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5419:     push(@$delayqueue,
                   5420: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5421: 	  'ecode' => $errorcode }
                   5422: 	 );
1.82      albertel 5423: }
                   5424: 
1.423     albertel 5425: =pod
                   5426: 
                   5427: =item scantron_find_student
                   5428: 
1.424     albertel 5429:    Finds the username for the current scanline
                   5430: 
                   5431:   Arguments:
                   5432:    $scantron_record - hash result from scantron_parse_scanline
                   5433:    $scan_data       - hash of correction information 
                   5434:                       (see &scantron_getfile() form more information)
                   5435:    $idmap           - hash from &username_to_idmap()
                   5436:    $line            - number of current scanline
                   5437:  
                   5438:   Returns:
                   5439:    Either 'username:domain' or undef if unknown
                   5440: 
1.423     albertel 5441: =cut
                   5442: 
1.82      albertel 5443: sub scantron_find_student {
1.157     albertel 5444:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5445:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5446:     if ($scanID =~ /^\s*$/) {
                   5447:  	return &scan_data($scan_data,"$line.user");
                   5448:     }
1.83      albertel 5449:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5450:  	if (lc($id) eq lc($scanID)) {
                   5451:  	    return $$idmap{$id};
                   5452:  	}
1.83      albertel 5453:     }
                   5454:     return undef;
                   5455: }
                   5456: 
1.423     albertel 5457: =pod
                   5458: 
                   5459: =item scantron_filter
                   5460: 
1.424     albertel 5461:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5462:    hidden resources was selected
                   5463: 
1.423     albertel 5464: =cut
                   5465: 
1.83      albertel 5466: sub scantron_filter {
                   5467:     my ($curres)=@_;
1.331     albertel 5468: 
                   5469:     if (ref($curres) && $curres->is_problem()) {
                   5470: 	# if the user has asked to not have either hidden
                   5471: 	# or 'randomout' controlled resources to be graded
                   5472: 	# don't include them
                   5473: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5474: 	    && $curres->randomout) {
                   5475: 	    return 0;
                   5476: 	}
1.83      albertel 5477: 	return 1;
                   5478:     }
                   5479:     return 0;
1.82      albertel 5480: }
                   5481: 
1.423     albertel 5482: =pod
                   5483: 
                   5484: =item scantron_process_corrections
                   5485: 
1.424     albertel 5486:    Gets correction information out of submitted form data and corrects
                   5487:    the scanline
                   5488: 
1.423     albertel 5489: =cut
                   5490: 
1.157     albertel 5491: sub scantron_process_corrections {
                   5492:     my ($r) = @_;
1.257     albertel 5493:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5494:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5495:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5496:     my $which=$env{'form.scantron_line'};
1.200     albertel 5497:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5498:     my ($skip,$err,$errmsg);
1.257     albertel 5499:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5500: 	$skip=1;
1.257     albertel 5501:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5502: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5503: 	    $env{'form.scantron_domain'};
1.157     albertel 5504: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5505: 	($line,$err,$errmsg)=
                   5506: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5507: 				     'ID',{'newid'=>$newid,
1.257     albertel 5508: 				    'username'=>$env{'form.scantron_username'},
                   5509: 				    'domain'=>$env{'form.scantron_domain'}});
                   5510:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5511: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5512: 	my $newCODE;
1.192     albertel 5513: 	my %args;
1.190     albertel 5514: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5515: 	    $newCODE='use_unfound';
1.190     albertel 5516: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5517: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5518: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5519: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5520: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5521: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5522: 	}
1.257     albertel 5523: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5524: 	    $args{'CODE_ignore_dup'}=1;
                   5525: 	}
                   5526: 	$args{'CODE'}=$newCODE;
1.186     albertel 5527: 	($line,$err,$errmsg)=
                   5528: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5529: 				     'CODE',\%args);
1.257     albertel 5530:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5531: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5532: 	    ($line,$err,$errmsg)=
                   5533: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5534: 					 $which,'answer',
                   5535: 					 { 'question'=>$question,
1.257     albertel 5536: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5537: 	    if ($err) { last; }
                   5538: 	}
                   5539:     }
                   5540:     if ($err) {
1.398     albertel 5541: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5542:     } else {
1.200     albertel 5543: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5544: 	&scantron_putfile($scanlines,$scan_data);
                   5545:     }
                   5546: }
                   5547: 
1.423     albertel 5548: =pod
                   5549: 
                   5550: =item reset_skipping_status
                   5551: 
1.424     albertel 5552:    Forgets the current set of remember skipped scanlines (and thus
                   5553:    reverts back to considering all lines in the
                   5554:    scantron_skipped_<filename> file)
                   5555: 
1.423     albertel 5556: =cut
                   5557: 
1.200     albertel 5558: sub reset_skipping_status {
                   5559:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5560:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5561:     &scantron_putfile(undef,$scan_data);
                   5562: }
                   5563: 
1.423     albertel 5564: =pod
                   5565: 
                   5566: =item start_skipping
                   5567: 
1.424     albertel 5568:    Marks a scanline to be skipped. 
                   5569: 
1.423     albertel 5570: =cut
                   5571: 
1.376     albertel 5572: sub start_skipping {
1.200     albertel 5573:     my ($scan_data,$i)=@_;
                   5574:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5575:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5576: 	$remembered{$i}=2;
                   5577:     } else {
                   5578: 	$remembered{$i}=1;
                   5579:     }
1.200     albertel 5580:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5581: }
                   5582: 
1.423     albertel 5583: =pod
                   5584: 
                   5585: =item should_be_skipped
                   5586: 
1.424     albertel 5587:    Checks whether a scanline should be skipped.
                   5588: 
1.423     albertel 5589: =cut
                   5590: 
1.200     albertel 5591: sub should_be_skipped {
1.376     albertel 5592:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5593:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5594: 	# not redoing old skips
1.376     albertel 5595: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5596: 	return 0;
                   5597:     }
                   5598:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5599: 
                   5600:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5601: 	return 0;
                   5602:     }
1.200     albertel 5603:     return 1;
                   5604: }
                   5605: 
1.423     albertel 5606: =pod
                   5607: 
                   5608: =item remember_current_skipped
                   5609: 
1.424     albertel 5610:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5611:    file and remembers them into scan_data for later use.
                   5612: 
1.423     albertel 5613: =cut
                   5614: 
1.200     albertel 5615: sub remember_current_skipped {
                   5616:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5617:     my %to_remember;
                   5618:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5619: 	if ($scanlines->{'skipped'}[$i]) {
                   5620: 	    $to_remember{$i}=1;
                   5621: 	}
                   5622:     }
1.376     albertel 5623: 
1.200     albertel 5624:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5625:     &scantron_putfile(undef,$scan_data);
                   5626: }
                   5627: 
1.423     albertel 5628: =pod
                   5629: 
                   5630: =item check_for_error
                   5631: 
1.424     albertel 5632:     Checks if there was an error when attempting to remove a specific
                   5633:     scantron_.. bubble sheet data file. Prints out an error if
                   5634:     something went wrong.
                   5635: 
1.423     albertel 5636: =cut
                   5637: 
1.200     albertel 5638: sub check_for_error {
                   5639:     my ($r,$result)=@_;
                   5640:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5641: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5642:     }
                   5643: }
1.157     albertel 5644: 
1.423     albertel 5645: =pod
                   5646: 
                   5647: =item scantron_warning_screen
                   5648: 
1.424     albertel 5649:    Interstitial screen to make sure the operator has selected the
                   5650:    correct options before we start the validation phase.
                   5651: 
1.423     albertel 5652: =cut
                   5653: 
1.203     albertel 5654: sub scantron_warning_screen {
                   5655:     my ($button_text)=@_;
1.257     albertel 5656:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5657:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5658:     my $CODElist;
1.284     albertel 5659:     if ($scantron_config{'CODElocation'} &&
                   5660: 	$scantron_config{'CODEstart'} &&
                   5661: 	$scantron_config{'CODElength'}) {
                   5662: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5663: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5664: 	$CODElist=
                   5665: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5666: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5667:     }
1.203     albertel 5668:     return (<<STUFF);
                   5669: <p>
1.398     albertel 5670: <span class="LC_warning">Please double check the information
                   5671:                  below before clicking on '$button_text'</span>
1.203     albertel 5672: </p>
                   5673: <table>
1.284     albertel 5674: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5675: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5676: $CODElist
1.203     albertel 5677: </table>
                   5678: <br />
                   5679: <p> If this information is correct, please click on '$button_text'.</p>
                   5680: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5681: 
                   5682: <br />
                   5683: STUFF
                   5684: }
                   5685: 
1.423     albertel 5686: =pod
                   5687: 
                   5688: =item scantron_do_warning
                   5689: 
1.424     albertel 5690:    Check if the operator has picked something for all required
                   5691:    fields. Error out if something is missing.
                   5692: 
1.423     albertel 5693: =cut
                   5694: 
1.203     albertel 5695: sub scantron_do_warning {
                   5696:     my ($r)=@_;
1.324     albertel 5697:     my ($symb)=&get_symb($r);
1.203     albertel 5698:     if (!$symb) {return '';}
1.324     albertel 5699:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5700:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5701:     if ( $env{'form.selectpage'} eq '' ||
                   5702: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5703: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5704: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5705: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5706: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5707: 	} 
1.257     albertel 5708: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5709: 	    $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 5710: 	} 
1.257     albertel 5711: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5712: 	    $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 5713: 	} 
                   5714:     } else {
1.265     www      5715: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5716: 	$r->print(<<STUFF);
1.203     albertel 5717: $warning
1.265     www      5718: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5719: <input type="hidden" name="command" value="scantron_validate" />
                   5720: STUFF
1.237     albertel 5721:     }
1.352     albertel 5722:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5723:     return '';
                   5724: }
                   5725: 
1.423     albertel 5726: =pod
                   5727: 
                   5728: =item scantron_form_start
                   5729: 
1.424     albertel 5730:     html hidden input for remembering all selected grading options
                   5731: 
1.423     albertel 5732: =cut
                   5733: 
1.203     albertel 5734: sub scantron_form_start {
                   5735:     my ($max_bubble)=@_;
                   5736:     my $result= <<SCANTRONFORM;
                   5737: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5738:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5739:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5740:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5741:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5742:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5743:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5744:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5745:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5746:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5747: SCANTRONFORM
1.447     foxr     5748: 
                   5749:   my $line = 0;
                   5750:     while (defined($env{"form.scantron.bubblelines.$line"})) {
1.448     foxr     5751: 	&Apache::lonnet::logthis("Saving chunk for $line");
1.447     foxr     5752:        my $chunk =
                   5753: 	   '<input type="hidden" name="scantron.bubblelines.'.$line.'" value="'.$env{"form.scantron.bubblelines.$line"}.'" />'."\n";
1.448     foxr     5754:        $chunk .=
                   5755: 	   '<input type="hidden" name="scantron.first_bubble_line.'.$line.'" value="'.$env{"form.scantron.first_bubble_line.$line"}.'" />'."\n";
1.447     foxr     5756:        $result .= $chunk;
                   5757:        $line++;
                   5758:    }
1.203     albertel 5759:     return $result;
                   5760: }
                   5761: 
1.423     albertel 5762: =pod
                   5763: 
                   5764: =item scantron_validate_file
                   5765: 
1.424     albertel 5766:     Dispatch routine for doing validation of a bubble sheet data file.
                   5767: 
                   5768:     Also processes any necessary information resets that need to
                   5769:     occur before validation begins (ignore previous corrections,
                   5770:     restarting the skipped records processing)
                   5771: 
1.423     albertel 5772: =cut
                   5773: 
1.157     albertel 5774: sub scantron_validate_file {
                   5775:     my ($r) = @_;
1.324     albertel 5776:     my ($symb)=&get_symb($r);
1.157     albertel 5777:     if (!$symb) {return '';}
1.324     albertel 5778:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5779:     
                   5780:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5781:     # them when doing the corrections reset
1.257     albertel 5782:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5783: 	&reset_skipping_status();
                   5784:     }
1.257     albertel 5785:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5786: 	&remember_current_skipped();
1.257     albertel 5787: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5788:     }
                   5789: 
1.257     albertel 5790:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5791: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5792: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5793: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5794: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5795:     }
1.200     albertel 5796: 
1.257     albertel 5797:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5798: 	&scantron_process_corrections($r);
                   5799:     }
1.424     albertel 5800:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5801:     #get the student pick code ready
                   5802:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5803:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5804:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5805:     $r->print($result);
                   5806:     
1.334     albertel 5807:     my @validate_phases=( 'sequence',
                   5808: 			  'ID',
1.157     albertel 5809: 			  'CODE',
                   5810: 			  'doublebubble',
                   5811: 			  'missingbubbles');
1.257     albertel 5812:     if (!$env{'form.validatepass'}) {
                   5813: 	$env{'form.validatepass'} = 0;
1.157     albertel 5814:     }
1.257     albertel 5815:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5816: 
1.448     foxr     5817:     &Apache::lonnet::logthis("Phase: $currentphase");
                   5818: 
1.157     albertel 5819:     my $stop=0;
                   5820:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5821: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5822: 	$r->rflush();
                   5823: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5824: 	{
                   5825: 	    no strict 'refs';
                   5826: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5827: 	}
                   5828:     }
                   5829:     if (!$stop) {
1.203     albertel 5830: 	my $warning=&scantron_warning_screen('Start Grading');
                   5831: 	$r->print(<<STUFF);
                   5832: Validation process complete.<br />
                   5833: $warning
                   5834: <input type="submit" name="submit" value="Start Grading" />
                   5835: <input type="hidden" name="command" value="scantron_process" />
                   5836: STUFF
                   5837: 
1.157     albertel 5838:     } else {
                   5839: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5840: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5841:     }
                   5842:     if ($stop) {
1.334     albertel 5843: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5844: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5845: 	    $r->print(' this error <br />');
                   5846: 
                   5847: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5848: 	} else {
                   5849: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5850: 	    $r->print(' using corrected info <br />');
                   5851: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5852: 	    $r->print(" this scanline saving it for later.");
                   5853: 	}
1.157     albertel 5854:     }
1.352     albertel 5855:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5856:     return '';
                   5857: }
                   5858: 
1.423     albertel 5859: 
                   5860: =pod
                   5861: 
                   5862: =item scantron_remove_file
                   5863: 
1.424     albertel 5864:    Removes the requested bubble sheet data file, makes sure that
                   5865:    scantron_original_<filename> is never removed
                   5866: 
                   5867: 
1.423     albertel 5868: =cut
                   5869: 
1.200     albertel 5870: sub scantron_remove_file {
1.192     albertel 5871:     my ($which)=@_;
1.257     albertel 5872:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5873:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5874:     my $file='scantron_';
1.200     albertel 5875:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5876: 	$file.=$which.'_';
1.192     albertel 5877:     } else {
                   5878: 	return 'refused';
                   5879:     }
1.257     albertel 5880:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5881:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5882: }
                   5883: 
1.423     albertel 5884: 
                   5885: =pod
                   5886: 
                   5887: =item scantron_remove_scan_data
                   5888: 
1.424     albertel 5889:    Removes all scan_data correction for the requested bubble sheet
                   5890:    data file.  (In the case that both the are doing skipped records we need
                   5891:    to remember the old skipped lines for the time being so that element
                   5892:    persists for a while.)
                   5893: 
1.423     albertel 5894: =cut
                   5895: 
1.200     albertel 5896: sub scantron_remove_scan_data {
1.257     albertel 5897:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5898:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5899:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5900:     my @todelete;
1.257     albertel 5901:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5902:     foreach my $key (@keys) {
                   5903: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5904: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5905: 		$key=~/remember_skipping/) {
                   5906: 		next;
                   5907: 	    }
1.192     albertel 5908: 	    push(@todelete,$key);
                   5909: 	}
                   5910:     }
1.200     albertel 5911:     my $result;
1.192     albertel 5912:     if (@todelete) {
1.200     albertel 5913: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5914:     }
                   5915:     return $result;
                   5916: }
                   5917: 
1.423     albertel 5918: 
                   5919: =pod
                   5920: 
                   5921: =item scantron_getfile
                   5922: 
1.424     albertel 5923:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5924:     the scan_data hash
                   5925:   
                   5926:   Arguments:
                   5927:     None
                   5928: 
                   5929:   Returns:
                   5930:     2 hash references
                   5931: 
                   5932:      - first one has 
                   5933:          orig      -
                   5934:          corrected -
                   5935:          skipped   -  each of which points to an array ref of the specified
                   5936:                       file broken up into individual lines
                   5937:          count     - number of scanlines
                   5938:  
                   5939:      - second is the scan_data hash possible keys are
1.425     albertel 5940:        ($number refers to scanline numbered $number and thus the key affects
                   5941:         only that scanline
                   5942:         $bubline refers to the specific bubble line element and the aspects
                   5943:         refers to that specific bubble line element)
                   5944: 
                   5945:        $number.user - username:domain to use
                   5946:        $number.CODE_ignore_dup 
                   5947:                     - ignore the duplicate CODE error 
                   5948:        $number.useCODE
                   5949:                     - use the CODE in the scanline as is
                   5950:        $number.no_bubble.$bubline
                   5951:                     - it is valid that there is no bubbled in bubble
                   5952:                       at $number $bubline
                   5953:        remember_skipping
                   5954:                     - a frozen hash containing keys of $number and values
                   5955:                       of either 
                   5956:                         1 - we are on a 'do skipped records pass' and plan
                   5957:                             on processing this line
                   5958:                         2 - we are on a 'do skipped records pass' and this
                   5959:                             scanline has been marked to skip yet again
1.424     albertel 5960: 
1.423     albertel 5961: =cut
                   5962: 
1.157     albertel 5963: sub scantron_getfile {
1.200     albertel 5964:     #FIXME really would prefer a scantron directory
1.257     albertel 5965:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5966:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5967:     my $lines;
                   5968:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5969: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5970:     my %scanlines;
                   5971:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5972:     my $temp=$scanlines{'orig'};
                   5973:     $scanlines{'count'}=$#$temp;
                   5974: 
                   5975:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5976: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5977:     if ($lines eq '-1') {
                   5978: 	$scanlines{'corrected'}=[];
                   5979:     } else {
                   5980: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5981:     }
                   5982:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5983: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5984:     if ($lines eq '-1') {
                   5985: 	$scanlines{'skipped'}=[];
                   5986:     } else {
                   5987: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5988:     }
1.175     albertel 5989:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5990:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5991:     my %scan_data = @tmp;
                   5992:     return (\%scanlines,\%scan_data);
                   5993: }
                   5994: 
1.423     albertel 5995: =pod
                   5996: 
                   5997: =item lonnet_putfile
                   5998: 
1.424     albertel 5999:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   6000: 
                   6001:  Arguments:
                   6002:    $contents - data to store
                   6003:    $filename - filename to store $contents into
                   6004: 
                   6005:  Returns:
                   6006:    result value from &Apache::lonnet::finishuserfileupload
                   6007: 
1.423     albertel 6008: =cut
                   6009: 
1.157     albertel 6010: sub lonnet_putfile {
                   6011:     my ($contents,$filename)=@_;
1.257     albertel 6012:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6013:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6014:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 6015:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 6016: 
                   6017: }
                   6018: 
1.423     albertel 6019: =pod
                   6020: 
                   6021: =item scantron_putfile
                   6022: 
1.424     albertel 6023:     Stores the current version of the bubble sheet data files, and the
                   6024:     scan_data hash. (Does not modify the original version only the
                   6025:     corrected and skipped versions.
                   6026: 
                   6027:  Arguments:
                   6028:     $scanlines - hash ref that looks like the first return value from
                   6029:                  &scantron_getfile()
                   6030:     $scan_data - hash ref that looks like the second return value from
                   6031:                  &scantron_getfile()
                   6032: 
1.423     albertel 6033: =cut
                   6034: 
1.157     albertel 6035: sub scantron_putfile {
                   6036:     my ($scanlines,$scan_data) = @_;
1.200     albertel 6037:     #FIXME really would prefer a scantron directory
1.257     albertel 6038:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6039:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 6040:     if ($scanlines) {
                   6041: 	my $prefix='scantron_';
1.157     albertel 6042: # no need to update orig, shouldn't change
                   6043: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 6044: #		    $env{'form.scantron_selectfile'});
1.200     albertel 6045: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   6046: 			$prefix.'corrected_'.
1.257     albertel 6047: 			$env{'form.scantron_selectfile'});
1.200     albertel 6048: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   6049: 			$prefix.'skipped_'.
1.257     albertel 6050: 			$env{'form.scantron_selectfile'});
1.200     albertel 6051:     }
1.175     albertel 6052:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 6053: }
                   6054: 
1.423     albertel 6055: =pod
                   6056: 
                   6057: =item scantron_get_line
                   6058: 
1.424     albertel 6059:    Returns the correct version of the scanline
                   6060: 
                   6061:  Arguments:
                   6062:     $scanlines - hash ref that looks like the first return value from
                   6063:                  &scantron_getfile()
                   6064:     $scan_data - hash ref that looks like the second return value from
                   6065:                  &scantron_getfile()
                   6066:     $i         - number of the requested line (starts at 0)
                   6067: 
                   6068:  Returns:
                   6069:    A scanline, (either the original or the corrected one if it
                   6070:    exists), or undef if the requested scanline should be
                   6071:    skipped. (Either because it's an skipped scanline, or it's an
                   6072:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   6073:    pass.
                   6074: 
1.423     albertel 6075: =cut
                   6076: 
1.157     albertel 6077: sub scantron_get_line {
1.200     albertel 6078:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 6079:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   6080:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 6081:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   6082:     return $scanlines->{'orig'}[$i]; 
                   6083: }
                   6084: 
1.423     albertel 6085: =pod
                   6086: 
                   6087: =item scantron_todo_count
                   6088: 
1.424     albertel 6089:     Counts the number of scanlines that need processing.
                   6090: 
                   6091:  Arguments:
                   6092:     $scanlines - hash ref that looks like the first return value from
                   6093:                  &scantron_getfile()
                   6094:     $scan_data - hash ref that looks like the second return value from
                   6095:                  &scantron_getfile()
                   6096: 
                   6097:  Returns:
                   6098:     $count - number of scanlines to process
                   6099: 
1.423     albertel 6100: =cut
                   6101: 
1.200     albertel 6102: sub get_todo_count {
                   6103:     my ($scanlines,$scan_data)=@_;
                   6104:     my $count=0;
                   6105:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   6106: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   6107: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6108: 	$count++;
                   6109:     }
                   6110:     return $count;
                   6111: }
                   6112: 
1.423     albertel 6113: =pod
                   6114: 
                   6115: =item scantron_put_line
                   6116: 
1.424     albertel 6117:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   6118:     data file.
                   6119: 
                   6120:  Arguments:
                   6121:     $scanlines - hash ref that looks like the first return value from
                   6122:                  &scantron_getfile()
                   6123:     $scan_data - hash ref that looks like the second return value from
                   6124:                  &scantron_getfile()
                   6125:     $i         - line number to update
                   6126:     $newline   - contents of the updated scanline
                   6127:     $skip      - if true make the line for skipping and update the
                   6128:                  'skipped' file
                   6129: 
1.423     albertel 6130: =cut
                   6131: 
1.157     albertel 6132: sub scantron_put_line {
1.200     albertel 6133:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 6134:     if ($skip) {
                   6135: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 6136: 	&start_skipping($scan_data,$i);
1.157     albertel 6137: 	return;
                   6138:     }
                   6139:     $scanlines->{'corrected'}[$i]=$newline;
                   6140: }
                   6141: 
1.423     albertel 6142: =pod
                   6143: 
                   6144: =item scantron_clear_skip
                   6145: 
1.424     albertel 6146:    Remove a line from the 'skipped' file
                   6147: 
                   6148:  Arguments:
                   6149:     $scanlines - hash ref that looks like the first return value from
                   6150:                  &scantron_getfile()
                   6151:     $scan_data - hash ref that looks like the second return value from
                   6152:                  &scantron_getfile()
                   6153:     $i         - line number to update
                   6154: 
1.423     albertel 6155: =cut
                   6156: 
1.376     albertel 6157: sub scantron_clear_skip {
                   6158:     my ($scanlines,$scan_data,$i)=@_;
                   6159:     if (exists($scanlines->{'skipped'}[$i])) {
                   6160: 	undef($scanlines->{'skipped'}[$i]);
                   6161: 	return 1;
                   6162:     }
                   6163:     return 0;
                   6164: }
                   6165: 
1.423     albertel 6166: =pod
                   6167: 
                   6168: =item scantron_filter_not_exam
                   6169: 
1.424     albertel 6170:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   6171:    filter out resources that are not marked as 'exam' mode
                   6172: 
1.423     albertel 6173: =cut
                   6174: 
1.334     albertel 6175: sub scantron_filter_not_exam {
                   6176:     my ($curres)=@_;
                   6177:     
                   6178:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   6179: 	# if the user has asked to not have either hidden
                   6180: 	# or 'randomout' controlled resources to be graded
                   6181: 	# don't include them
                   6182: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   6183: 	    && $curres->randomout) {
                   6184: 	    return 0;
                   6185: 	}
                   6186: 	return 1;
                   6187:     }
                   6188:     return 0;
                   6189: }
                   6190: 
1.423     albertel 6191: =pod
                   6192: 
                   6193: =item scantron_validate_sequence
                   6194: 
1.424     albertel 6195:     Validates the selected sequence, checking for resource that are
                   6196:     not set to exam mode.
                   6197: 
1.423     albertel 6198: =cut
                   6199: 
1.334     albertel 6200: sub scantron_validate_sequence {
                   6201:     my ($r,$currentphase) = @_;
                   6202: 
                   6203:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6204:     my (undef,undef,$sequence)=
                   6205: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   6206: 
                   6207:     my $map=$navmap->getResourceByUrl($sequence);
                   6208: 
                   6209:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6210:                                     value="ignore" />');
                   6211:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6212: 	my @resources=
                   6213: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6214: 	if (@resources) {
1.357     banghart 6215: 	    $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 6216: 	    return (1,$currentphase);
                   6217: 	}
                   6218:     }
                   6219: 
                   6220:     return (0,$currentphase+1);
                   6221: }
                   6222: 
1.423     albertel 6223: =pod
                   6224: 
                   6225: =item scantron_validate_ID
                   6226: 
1.424     albertel 6227:    Validates all scanlines in the selected file to not have any
                   6228:    invalid or underspecified student IDs
                   6229: 
1.423     albertel 6230: =cut
                   6231: 
1.157     albertel 6232: sub scantron_validate_ID {
                   6233:     my ($r,$currentphase) = @_;
                   6234:     
                   6235:     #get student info
                   6236:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6237:     my %idmap=&username_to_idmap($classlist);
                   6238: 
                   6239:     #get scantron line setup
1.257     albertel 6240:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6241:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6242:     
                   6243:     &scantron_get_maxbubble();	# parse needs the bubble_lines.. array.
1.157     albertel 6244: 
                   6245:     my %found=('ids'=>{},'usernames'=>{});
                   6246:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6247: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6248: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6249: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6250: 						 $scan_data);
                   6251: 	my $id=$$scan_record{'scantron.ID'};
                   6252: 	my $found;
                   6253: 	foreach my $checkid (keys(%idmap)) {
                   6254: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6255: 	}
                   6256: 	if ($found) {
                   6257: 	    my $username=$idmap{$found};
                   6258: 	    if ($found{'ids'}{$found}) {
                   6259: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6260: 					 $line,'duplicateID',$found);
1.194     albertel 6261: 		return(1,$currentphase);
1.157     albertel 6262: 	    } elsif ($found{'usernames'}{$username}) {
                   6263: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6264: 					 $line,'duplicateID',$username);
1.194     albertel 6265: 		return(1,$currentphase);
1.157     albertel 6266: 	    }
1.186     albertel 6267: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6268: 	    $found{'ids'}{$found}++;
                   6269: 	    $found{'usernames'}{$username}++;
                   6270: 	} else {
                   6271: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6272: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6273: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6274: 		    &scantron_get_correction($r,$i,$scan_record,
                   6275: 					     \%scantron_config,
                   6276: 					     $line,'duplicateID',$username);
1.194     albertel 6277: 		    return(1,$currentphase);
1.157     albertel 6278: 		} elsif (!defined($username)) {
                   6279: 		    &scantron_get_correction($r,$i,$scan_record,
                   6280: 					     \%scantron_config,
                   6281: 					     $line,'incorrectID');
1.194     albertel 6282: 		    return(1,$currentphase);
1.157     albertel 6283: 		}
                   6284: 		$found{'usernames'}{$username}++;
                   6285: 	    } else {
                   6286: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6287: 					 $line,'incorrectID');
1.194     albertel 6288: 		return(1,$currentphase);
1.157     albertel 6289: 	    }
                   6290: 	}
                   6291:     }
                   6292: 
                   6293:     return (0,$currentphase+1);
                   6294: }
                   6295: 
1.423     albertel 6296: =pod
                   6297: 
                   6298: =item scantron_get_correction
                   6299: 
1.424     albertel 6300:    Builds the interface screen to interact with the operator to fix a
                   6301:    specific error condition in a specific scanline
                   6302: 
                   6303:  Arguments:
                   6304:     $r           - Apache request object
                   6305:     $i           - number of the current scanline
                   6306:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6307:     $scan_config - hash ref as returned from &get_scantron_config()
                   6308:     $line        - full contents of the current scanline
                   6309:     $error       - error condition, valid values are
                   6310:                    'incorrectCODE', 'duplicateCODE',
                   6311:                    'doublebubble', 'missingbubble',
                   6312:                    'duplicateID', 'incorrectID'
                   6313:     $arg         - extra information needed
                   6314:        For errors:
                   6315:          - duplicateID   - paper number that this studentID was seen before on
                   6316:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6317:                            seen on before
                   6318:          - incorrectCODE - current incorrect CODE 
                   6319:          - doublebubble  - array ref of the bubble lines that have double
                   6320:                            bubble errors
                   6321:          - missingbubble - array ref of the bubble lines that have missing
                   6322:                            bubble errors
                   6323: 
1.423     albertel 6324: =cut
                   6325: 
1.157     albertel 6326: sub scantron_get_correction {
                   6327:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6328: 
1.454     banghart 6329: #FIXME in the case of a duplicated ID the previous line, probably need
1.157     albertel 6330: #to show both the current line and the previous one and allow skipping
                   6331: #the previous one or the current one
                   6332: 
1.161     albertel 6333:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6334:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6335: 	$r->print(" for PaperID <tt>".
                   6336: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6337:     } else {
                   6338: 	$r->print(" in scanline $i <pre>".
                   6339: 		  $line."</pre> \n");
                   6340:     }
1.242     albertel 6341:     my $message="<p>The ID on the form is  <tt>".
                   6342: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6343: 	"The name on the paper is ".
                   6344: 	$$scan_record{'scantron.LastName'}.",".
                   6345: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6346: 
1.157     albertel 6347:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6348:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6349:     if ($error =~ /ID$/) {
1.186     albertel 6350: 	if ($error eq 'incorrectID') {
1.157     albertel 6351: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6352: 	} elsif ($error eq 'duplicateID') {
                   6353: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6354: 	}
1.242     albertel 6355: 	$r->print($message);
1.157     albertel 6356: 	$r->print("<p>How should I handle this? <br /> \n");
                   6357: 	$r->print("\n<ul><li> ");
                   6358: 	#FIXME it would be nice if this sent back the user ID and
                   6359: 	#could do partial userID matches
                   6360: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6361: 				       'scantron_username','scantron_domain'));
                   6362: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6363: 	$r->print("\n@".
1.257     albertel 6364: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6365: 
                   6366: 	$r->print('</li>');
1.186     albertel 6367:     } elsif ($error =~ /CODE$/) {
                   6368: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6369: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6370: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6371: 	    $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 6372: 	}
1.224     albertel 6373: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6374: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6375: 	$r->print($message);
1.186     albertel 6376: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6377: 	$r->print("\n<br /> ");
1.194     albertel 6378: 	my $i=0;
1.273     albertel 6379: 	if ($error eq 'incorrectCODE' 
                   6380: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6381: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6382: 	    if ($closest > 0) {
                   6383: 		foreach my $testcode (@{$closest}) {
                   6384: 		    my $checked='';
1.401     albertel 6385: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6386: 		    $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' />");
                   6387: 		    $r->print("\n<br />");
                   6388: 		    $i++;
                   6389: 		}
1.194     albertel 6390: 	    }
                   6391: 	}
1.273     albertel 6392: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6393: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6394: 	    $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>");
                   6395: 	    $r->print("\n<br />");
                   6396: 	}
1.194     albertel 6397: 
1.188     albertel 6398: 	$r->print(<<ENDSCRIPT);
                   6399: <script type="text/javascript">
                   6400: function change_radio(field) {
1.190     albertel 6401:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6402:     var i;
                   6403:     for (i=0;i<slct.length;i++) {
                   6404:         if (slct[i].value==field) { slct[i].checked=true; }
                   6405:     }
                   6406: }
                   6407: </script>
                   6408: ENDSCRIPT
1.187     albertel 6409: 	my $href="/adm/pickcode?".
1.359     www      6410: 	   "form=".&escape("scantronupload").
                   6411: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6412: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6413: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6414: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6415: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6416: 	    $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')\" />");
                   6417: 	    $r->print("\n<br />");
                   6418: 	}
1.272     albertel 6419: 	$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 6420: 	$r->print("\n<br /><br />");
1.157     albertel 6421:     } elsif ($error eq 'doublebubble') {
                   6422: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6423: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6424: 		  join(',',@{$arg}).'" />');
1.242     albertel 6425: 	$r->print($message);
1.157     albertel 6426: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6427: 	foreach my $question (@{$arg}) {
1.447     foxr     6428: 
                   6429: 	    my $selected  = &get_response_bubbles($scan_record, $question);
1.422     foxr     6430: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6431: 				      split('',$selected));
1.157     albertel 6432: 	}
                   6433:     } elsif ($error eq 'missingbubble') {
                   6434: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6435: 	$r->print($message);
1.157     albertel 6436: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6437: 	$r->print("Some questions have no scanned bubbles\n");
                   6438: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6439: 		  join(',',@{$arg}).'" />');
                   6440: 	foreach my $question (@{$arg}) {
1.448     foxr     6441: 	    my $selected = &get_response_bubbles($scan_record, $question);
1.157     albertel 6442: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6443: 	}
                   6444:     } else {
                   6445: 	$r->print("\n<ul>");
                   6446:     }
                   6447:     $r->print("\n</li></ul>");
                   6448: 
                   6449: }
1.423     albertel 6450: 
                   6451: =pod
                   6452: 
                   6453: =item scantron_bubble_selector
                   6454:   
                   6455:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6456:    possibly showing the existing the selected bubbles if known
1.423     albertel 6457: 
                   6458:  Arguments:
                   6459:     $r           - Apache request object
                   6460:     $scan_config - hash from &get_scantron_config()
                   6461:     $quest       - number of the bubble line to make a corrector for
                   6462:     $selected    - array of letters of previously selected bubbles
                   6463: 
                   6464: =cut
                   6465: 
1.157     albertel 6466: sub scantron_bubble_selector {
1.447     foxr     6467:     my ($r,$scan_config,$quest,@selected)=@_;
1.157     albertel 6468:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6469: 
                   6470:     my $scmode=$$scan_config{'Qon'};
1.447     foxr     6471: 
                   6472: 
1.274     albertel 6473:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6474: 
1.448     foxr     6475:     my $response = $quest-1;
                   6476:     my $lines = $bubble_lines_per_response{$response};
                   6477:     &Apache::lonnet::logthis("Question $quest, lines: $lines");
1.447     foxr     6478: 
1.422     foxr     6479:     my $total_lines = $lines*2;
1.157     albertel 6480:     my @alphabet=('A'..'Z');
1.422     foxr     6481:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6482: 
                   6483:     for (my $l = 0; $l < $lines; $l++) {
                   6484: 	if ($l != 0) {
                   6485: 	    $r->print('<tr>');
                   6486: 	}
                   6487: 
                   6488: 	# FIXME:  This loop probably has to be considerably more clever for
                   6489: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6490: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6491: 
                   6492: 	for (my $i=0;$i<$max;$i++) {
                   6493: 	    $r->print("\n".'<td align="center">');
                   6494: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6495: 		$r->print('X'); 
                   6496: 		shift(@selected) ;
                   6497: 	    } else { 
                   6498: 		$r->print('&nbsp;'); 
                   6499: 	    }
                   6500: 	    $r->print('</td>');
                   6501: 	    
                   6502: 	}
                   6503: 
                   6504: 	if ($l == 0) {
                   6505: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6506: 
                   6507: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6508: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6509: 	
                   6510: 	}
                   6511: 
                   6512: 	$r->print('</tr><tr>');
                   6513: 
                   6514: 	# FIXME: This may have to be a bit more clever for
                   6515: 	#        multiline questions (different values e.g..).
                   6516: 
                   6517: 	for (my $i=0;$i<$max;$i++) {
                   6518: 	    $r->print("\n".
                   6519: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6520: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6521: 	}
                   6522: 	$r->print('</tr>');
                   6523: 
                   6524: 	    
1.157     albertel 6525:     }
1.422     foxr     6526:     $r->print('</table>');
1.157     albertel 6527: }
                   6528: 
1.423     albertel 6529: =pod
                   6530: 
                   6531: =item num_matches
                   6532: 
1.424     albertel 6533:    Counts the number of characters that are the same between the two arguments.
                   6534: 
                   6535:  Arguments:
                   6536:    $orig - CODE from the scanline
                   6537:    $code - CODE to match against
                   6538: 
                   6539:  Returns:
                   6540:    $count - integer count of the number of same characters between the
                   6541:             two arguments
                   6542: 
1.423     albertel 6543: =cut
                   6544: 
1.194     albertel 6545: sub num_matches {
                   6546:     my ($orig,$code) = @_;
                   6547:     my @code=split(//,$code);
                   6548:     my @orig=split(//,$orig);
                   6549:     my $same=0;
                   6550:     for (my $i=0;$i<scalar(@code);$i++) {
                   6551: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6552:     }
                   6553:     return $same;
                   6554: }
                   6555: 
1.423     albertel 6556: =pod
                   6557: 
                   6558: =item scantron_get_closely_matching_CODEs
                   6559: 
1.424     albertel 6560:    Cycles through all CODEs and finds the set that has the greatest
                   6561:    number of same characters as the provided CODE
                   6562: 
                   6563:  Arguments:
                   6564:    $allcodes - hash ref returned by &get_codes()
                   6565:    $CODE     - CODE from the current scanline
                   6566: 
                   6567:  Returns:
                   6568:    2 element list
                   6569:     - first elements is number of how closely matching the best fit is 
                   6570:       (5 means best set has 5 matching characters)
                   6571:     - second element is an arrary ref containing the set of valid CODEs
                   6572:       that best fit the passed in CODE
                   6573: 
1.423     albertel 6574: =cut
                   6575: 
1.194     albertel 6576: sub scantron_get_closely_matching_CODEs {
                   6577:     my ($allcodes,$CODE)=@_;
                   6578:     my @CODEs;
                   6579:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6580: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6581:     }
                   6582: 
                   6583:     return ($#CODEs,$CODEs[-1]);
                   6584: }
                   6585: 
1.423     albertel 6586: =pod
                   6587: 
                   6588: =item get_codes
                   6589: 
1.424     albertel 6590:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6591:    set of remembered CODEs.
                   6592: 
                   6593:  Arguments:
                   6594:   $old_name - name of the set of remembered CODEs
                   6595:   $cdom     - domain of the course
                   6596:   $cnum     - internal course name
                   6597: 
                   6598:  Returns:
                   6599:   %allcodes - keys are the valid CODEs, values are all 1
                   6600: 
1.423     albertel 6601: =cut
                   6602: 
1.194     albertel 6603: sub get_codes {
1.280     foxr     6604:     my ($old_name, $cdom, $cnum) = @_;
                   6605:     if (!$old_name) {
                   6606: 	$old_name=$env{'form.scantron_CODElist'};
                   6607:     }
                   6608:     if (!$cdom) {
                   6609: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6610:     }
                   6611:     if (!$cnum) {
                   6612: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6613:     }
1.278     albertel 6614:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6615: 				    $cdom,$cnum);
                   6616:     my %allcodes;
                   6617:     if ($result{"type\0$old_name"} eq 'number') {
                   6618: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6619:     } else {
                   6620: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6621:     }
1.194     albertel 6622:     return %allcodes;
                   6623: }
                   6624: 
1.423     albertel 6625: =pod
                   6626: 
                   6627: =item scantron_validate_CODE
                   6628: 
1.424     albertel 6629:    Validates all scanlines in the selected file to not have any
                   6630:    invalid or underspecified CODEs and that none of the codes are
                   6631:    duplicated if this was requested.
                   6632: 
1.423     albertel 6633: =cut
                   6634: 
1.157     albertel 6635: sub scantron_validate_CODE {
                   6636:     my ($r,$currentphase) = @_;
1.257     albertel 6637:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6638:     if ($scantron_config{'CODElocation'} &&
                   6639: 	$scantron_config{'CODEstart'} &&
                   6640: 	$scantron_config{'CODElength'}) {
1.257     albertel 6641: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6642: 	    &FIXME_blow_up()
                   6643: 	}
                   6644:     } else {
                   6645: 	return (0,$currentphase+1);
                   6646:     }
                   6647:     
                   6648:     my %usedCODEs;
                   6649: 
1.194     albertel 6650:     my %allcodes=&get_codes();
1.186     albertel 6651: 
1.447     foxr     6652:     &scantron_get_maxbubble();	# parse needs the lines per response array.
                   6653: 
1.186     albertel 6654:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6655:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6656: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6657: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6658: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6659: 						 $scan_data);
                   6660: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6661: 	my $error=0;
1.224     albertel 6662: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6663: 	    &scantron_get_correction($r,$i,$scan_record,
                   6664: 				     \%scantron_config,
                   6665: 				     $line,'incorrectCODE',\%allcodes);
                   6666: 	    return(1,$currentphase);
                   6667: 	}
1.221     albertel 6668: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6669: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6670: 	    &scantron_get_correction($r,$i,$scan_record,
                   6671: 				     \%scantron_config,
1.194     albertel 6672: 				     $line,'incorrectCODE',\%allcodes);
                   6673: 	    return(1,$currentphase);
1.186     albertel 6674: 	}
1.214     albertel 6675: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6676: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6677: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6678: 	    &scantron_get_correction($r,$i,$scan_record,
                   6679: 				     \%scantron_config,
1.194     albertel 6680: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6681: 	    return(1,$currentphase);
1.186     albertel 6682: 	}
1.194     albertel 6683: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6684:     }
1.157     albertel 6685:     return (0,$currentphase+1);
                   6686: }
                   6687: 
1.423     albertel 6688: =pod
                   6689: 
                   6690: =item scantron_validate_doublebubble
                   6691: 
1.424     albertel 6692:    Validates all scanlines in the selected file to not have any
                   6693:    bubble lines with multiple bubbles marked.
                   6694: 
1.423     albertel 6695: =cut
                   6696: 
1.157     albertel 6697: sub scantron_validate_doublebubble {
                   6698:     my ($r,$currentphase) = @_;
                   6699:     #get student info
                   6700:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6701:     my %idmap=&username_to_idmap($classlist);
                   6702: 
                   6703:     #get scantron line setup
1.257     albertel 6704:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6705:     my ($scanlines,$scan_data)=&scantron_getfile();
1.447     foxr     6706: 
                   6707:     &scantron_get_maxbubble();	# parse needs the bubble line array.
                   6708: 
1.157     albertel 6709:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6710: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6711: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6712: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6713: 						 $scan_data);
                   6714: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6715: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6716: 				 'doublebubble',
                   6717: 				 $$scan_record{'scantron.doubleerror'});
                   6718:     	return (1,$currentphase);
                   6719:     }
                   6720:     return (0,$currentphase+1);
                   6721: }
                   6722: 
1.423     albertel 6723: =pod
                   6724: 
                   6725: =item scantron_get_maxbubble
                   6726: 
1.424     albertel 6727:    Returns the maximum number of bubble lines that are expected to
                   6728:    occur. Does this by walking the selected sequence rendering the
                   6729:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6730:    for what the current value of the problem counter is.
                   6731: 
1.447     foxr     6732:    Caches the results to $env{'form.scantron_maxbubble'},
                   6733:    $env{'form.scantron.bubble_lines.n'} and 
                   6734:    $env{'form.scantron.first_bubble_line.n'}
                   6735:    which are the total number of bubble, lines, the number of bubble
                   6736:    lines for reponse n and number of the first bubble line for response n.
1.424     albertel 6737: 
1.423     albertel 6738: =cut
                   6739: 
1.330     albertel 6740: sub scantron_get_maxbubble {    
1.448     foxr     6741:     &Apache::lonnet::logthis("get_max_bubble");
1.257     albertel 6742:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6743: 	$env{'form.scantron_maxbubble'}) {
1.448     foxr     6744: 	&Apache::lonnet::logthis("cached");
1.447     foxr     6745: 	&restore_bubble_lines();
1.257     albertel 6746: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6747:     }
1.448     foxr     6748:     &Apache::lonnet::logthis("computing");
1.330     albertel 6749: 
1.447     foxr     6750:     my (undef, undef, $sequence) =
1.257     albertel 6751: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6752: 
1.447     foxr     6753:     my $navmap=Apache::lonnavmaps::navmap->new();
1.191     albertel 6754:     my $map=$navmap->getResourceByUrl($sequence);
                   6755:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6756: 
                   6757:     &Apache::lonxml::clear_problem_counter();
                   6758: 
1.435     foxr     6759:     my $uname       = $env{'form.student'};
                   6760:     my $udom        = $env{'form.userdom'};
                   6761:     my $cid         = $env{'request.course.id'};
                   6762:     my $total_lines = 0;
                   6763:     %bubble_lines_per_response = ();
1.447     foxr     6764:     %first_bubble_line         = ();
1.435     foxr     6765: 
1.447     foxr     6766:   
                   6767:     my $response_number = 0;
                   6768:     my $bubble_line     = 0;
1.191     albertel 6769:     foreach my $resource (@resources) {
1.435     foxr     6770: 	my $symb = $resource->symb();
1.447     foxr     6771: 	&Apache::lonxml::clear_bubble_lines_for_part();
1.330     albertel 6772: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6773: 					('symb' => $resource->symb()),
                   6774: 					('grade_target' => 'analyze'),
                   6775: 					('grade_courseid' => $cid),
                   6776: 					('grade_domain' => $udom),
                   6777: 					('grade_username' => $uname));
1.436     albertel 6778: 	my (undef, $an) =
1.435     foxr     6779: 	    split(/_HASH_REF__/,$result, 2);
                   6780: 
                   6781: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6782: 
                   6783: 
                   6784: 
                   6785: 	foreach my $part_id (@{$analysis{'parts'}}) {
1.447     foxr     6786: 	    my ($trash, $part) = split(/\./, $part_id);
                   6787: 
                   6788: 	    my $lines = $analysis{"$part_id.bubble_lines"}[0];
                   6789: 
                   6790: 	    # TODO - make this a persistent hash not an array.
                   6791: 
                   6792: 
                   6793: 	    $first_bubble_line{$response_number}           = $bubble_line;
                   6794: 	    $bubble_lines_per_response{$response_number}   = $lines;
                   6795: 	    $response_number++;
                   6796: 
                   6797: 	    $bubble_line +=  $lines;
                   6798: 	    $total_lines +=  $lines;
1.435     foxr     6799: 	}
                   6800: 
1.191     albertel 6801:     }
                   6802:     &Apache::lonnet::delenv('scantron\.');
1.447     foxr     6803: 
                   6804:     &save_bubble_lines();
1.330     albertel 6805:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6806: 	$total_lines;
1.257     albertel 6807:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6808: }
                   6809: 
1.423     albertel 6810: =pod
                   6811: 
                   6812: =item scantron_validate_missingbubbles
                   6813: 
1.424     albertel 6814:    Validates all scanlines in the selected file to not have any
1.447     foxr     6815:     answers that don't have bubbles that have not been verified
                   6816:     to be bubble free.
1.424     albertel 6817: 
1.423     albertel 6818: =cut
                   6819: 
1.157     albertel 6820: sub scantron_validate_missingbubbles {
                   6821:     my ($r,$currentphase) = @_;
                   6822:     #get student info
                   6823:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6824:     my %idmap=&username_to_idmap($classlist);
                   6825: 
                   6826:     #get scantron line setup
1.257     albertel 6827:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6828:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6829:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6830:     if (!$max_bubble) { $max_bubble=2**31; }
                   6831:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6832: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6833: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6834: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6835: 						 $scan_data);
                   6836: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6837: 	my @to_correct;
                   6838: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6839: 	    if ($missing > $max_bubble) { next; }
                   6840: 	    push(@to_correct,$missing);
                   6841: 	}
                   6842: 	if (@to_correct) {
                   6843: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6844: 				     $line,'missingbubble',\@to_correct);
                   6845: 	    return (1,$currentphase);
                   6846: 	}
                   6847: 
                   6848:     }
                   6849:     return (0,$currentphase+1);
                   6850: }
                   6851: 
1.423     albertel 6852: =pod
                   6853: 
                   6854: =item scantron_process_students
                   6855: 
                   6856:    Routine that does the actual grading of the bubble sheet information.
                   6857: 
                   6858:    The parsed scanline hash is added to %env 
                   6859: 
                   6860:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6861:    foreach resource , with the form data of
                   6862: 
                   6863: 	'submitted'     =>'scantron' 
                   6864: 	'grade_target'  =>'grade',
                   6865: 	'grade_username'=> username of student
                   6866: 	'grade_domain'  => domain of student
                   6867: 	'grade_courseid'=> of course
                   6868: 	'grade_symb'    => symb of resource to grade
                   6869: 
                   6870:     This triggers a grading pass. The problem grading code takes care
                   6871:     of converting the bubbled letter information (now in %env) into a
                   6872:     valid submission.
                   6873: 
                   6874: =cut
                   6875: 
1.82      albertel 6876: sub scantron_process_students {
1.75      albertel 6877:     my ($r) = @_;
1.257     albertel 6878:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6879:     my ($symb)=&get_symb($r);
1.81      albertel 6880:     if (!$symb) {return '';}
1.324     albertel 6881:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6882: 
1.257     albertel 6883:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6884:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6885:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6886:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6887:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6888:     my $map=$navmap->getResourceByUrl($sequence);
                   6889:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6890: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6891:     my $result= <<SCANTRONFORM;
1.81      albertel 6892: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6893:   <input type="hidden" name="command" value="scantron_configphase" />
                   6894:   $default_form_data
                   6895: SCANTRONFORM
1.82      albertel 6896:     $r->print($result);
                   6897: 
                   6898:     my @delayqueue;
1.140     albertel 6899:     my %completedstudents;
                   6900:     
1.200     albertel 6901:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6902:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6903:  				    'Scantron Progress',$count,
1.195     albertel 6904: 				    'inline',undef,'scantronupload');
1.140     albertel 6905:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6906: 					  'Processing first student');
                   6907:     my $start=&Time::HiRes::time();
1.158     albertel 6908:     my $i=-1;
1.200     albertel 6909:     my ($uname,$udom,$started);
1.447     foxr     6910: 
                   6911:     &scantron_get_maxbubble();	# Need the bubble lines array to parse.
                   6912: 
1.157     albertel 6913:     while ($i<$scanlines->{'count'}) {
                   6914:  	($uname,$udom)=('','');
                   6915:  	$i++;
1.200     albertel 6916:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6917:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6918: 	if ($started) {
                   6919: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6920: 						     'last student');
                   6921: 	}
                   6922: 	$started=1;
1.157     albertel 6923:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6924:  						 $scan_data);
                   6925:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6926:  					      \%idmap,$i)) {
                   6927:   	    &scantron_add_delay(\@delayqueue,$line,
                   6928:  				'Unable to find a student that matches',1);
                   6929:  	    next;
                   6930:   	}
                   6931:  	if (exists $completedstudents{$uname}) {
                   6932:  	    &scantron_add_delay(\@delayqueue,$line,
                   6933:  				'Student '.$uname.' has multiple sheets',2);
                   6934:  	    next;
                   6935:  	}
                   6936:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6937: 
                   6938: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6939:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6940: 
                   6941: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6942: 	    &scantron_putfile($scanlines,$scan_data);
                   6943: 	}
1.161     albertel 6944: 	
                   6945: 	my $i=0;
1.83      albertel 6946: 	foreach my $resource (@resources) {
1.85      albertel 6947: 	    $i++;
1.193     albertel 6948: 	    my %form=('submitted'     =>'scantron',
                   6949: 		      'grade_target'  =>'grade',
                   6950: 		      'grade_username'=>$uname,
                   6951: 		      'grade_domain'  =>$udom,
1.257     albertel 6952: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6953: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6954: 	    if (exists($scan_record->{'scantron.CODE'})
                   6955: 		&& 
                   6956: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6957: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6958: 	    } else {
                   6959: 		$form{'CODE'}='';
1.193     albertel 6960: 	    }
                   6961: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6962: 	    if ($result ne '') {
                   6963: 	    }
1.213     albertel 6964: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6965: 	}
1.140     albertel 6966: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6967: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6968:     } continue {
1.330     albertel 6969: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6970: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6971:     }
1.140     albertel 6972:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6973: #    my $lasttime = &Time::HiRes::time()-$start;
                   6974: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6975: 
1.200     albertel 6976:     $r->print("</form>");
1.324     albertel 6977:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6978:     return '';
1.75      albertel 6979: }
1.157     albertel 6980: 
1.423     albertel 6981: =pod
                   6982: 
                   6983: =item scantron_upload_scantron_data
                   6984: 
                   6985:     Creates the screen for adding a new bubble sheet data file to a course.
                   6986: 
                   6987: =cut
                   6988: 
1.157     albertel 6989: sub scantron_upload_scantron_data {
                   6990:     my ($r)=@_;
1.257     albertel 6991:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6992:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6993: 							  'domainid',
                   6994: 							  'coursename');
1.257     albertel 6995:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6996: 						   'domainid');
1.324     albertel 6997:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6998:     $r->print(<<UPLOAD);
                   6999: <script type="text/javascript" language="javascript">
                   7000:     function checkUpload(formname) {
                   7001: 	if (formname.upfile.value == "") {
                   7002: 	    alert("Please use the browse button to select a file from your local directory.");
                   7003: 	    return false;
                   7004: 	}
                   7005: 	formname.submit();
                   7006:     }
                   7007: </script>
                   7008: 
                   7009: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 7010: $default_form_data
1.181     albertel 7011: <table>
                   7012: <tr><td>$select_link </td></tr>
                   7013: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   7014: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   7015: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   7016: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   7017: </table>
1.157     albertel 7018: <input name='command' value='scantronupload_save' type='hidden' />
                   7019: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   7020: </form>
                   7021: UPLOAD
                   7022:     return '';
                   7023: }
                   7024: 
1.423     albertel 7025: =pod
                   7026: 
                   7027: =item scantron_upload_scantron_data_save
                   7028: 
                   7029:    Adds a provided bubble information data file to the course if user
                   7030:    has the correct privileges to do so.  
                   7031: 
                   7032: =cut
                   7033: 
1.157     albertel 7034: sub scantron_upload_scantron_data_save {
                   7035:     my($r)=@_;
1.324     albertel 7036:     my ($symb)=&get_symb($r,1);
1.182     albertel 7037:     my $doanotherupload=
                   7038: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   7039: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   7040: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   7041: 	'</form>'."\n";
1.257     albertel 7042:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 7043: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 7044: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 7045: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 7046: 	if ($symb) {
1.324     albertel 7047: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 7048: 	} else {
                   7049: 	    $r->print($doanotherupload);
                   7050: 	}
1.162     albertel 7051: 	return '';
                   7052:     }
1.257     albertel 7053:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       7054:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 7055:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 7056:     #FIXME
                   7057:     #copied from lonnet::userfileupload()
                   7058:     #make that function able to target a specified course
                   7059:     # Replace Windows backslashes by forward slashes
                   7060:     $fname=~s/\\/\//g;
                   7061:     # Get rid of everything but the actual filename
                   7062:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   7063:     # Replace spaces by underscores
                   7064:     $fname=~s/\s+/\_/g;
                   7065:     # Replace all other weird characters by nothing
                   7066:     $fname=~s/[^\w\.\-]//g;
                   7067:     # See if there is anything left
                   7068:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       7069:     my $uploadedfile=$fname;
1.157     albertel 7070:     $fname='scantron_orig_'.$fname;
1.257     albertel 7071:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 7072: 	$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 7073:     } else {
1.275     albertel 7074: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 7075: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 7076: 	    $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 7077: 	} else {
1.398     albertel 7078: 	    $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 7079: 	}
                   7080:     }
1.174     albertel 7081:     if ($symb) {
1.209     ng       7082: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 7083:     } else {
1.182     albertel 7084: 	$r->print($doanotherupload);
1.174     albertel 7085:     }
1.157     albertel 7086:     return '';
                   7087: }
                   7088: 
1.423     albertel 7089: =pod
                   7090: 
                   7091: =item valid_file
                   7092: 
1.424     albertel 7093:    Validates that the requested bubble data file exists in the course.
1.423     albertel 7094: 
                   7095: =cut
                   7096: 
1.202     albertel 7097: sub valid_file {
                   7098:     my ($requested_file)=@_;
                   7099:     foreach my $filename (sort(&scantron_filenames())) {
                   7100: 	if ($requested_file eq $filename) { return 1; }
                   7101:     }
                   7102:     return 0;
                   7103: }
                   7104: 
1.423     albertel 7105: =pod
                   7106: 
                   7107: =item scantron_download_scantron_data
                   7108: 
                   7109:    Shows a list of the three internal files (original, corrected,
                   7110:    skipped) for a specific bubble sheet data file that exists in the
                   7111:    course.
                   7112: 
                   7113: =cut
                   7114: 
1.202     albertel 7115: sub scantron_download_scantron_data {
                   7116:     my ($r)=@_;
1.324     albertel 7117:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 7118:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7119:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7120:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 7121:     if (! &valid_file($file)) {
                   7122: 	$r->print(<<ERROR);
                   7123: 	<p>
                   7124: 	    The requested file name was invalid.
                   7125:         </p>
                   7126: ERROR
1.324     albertel 7127: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7128: 	return;
                   7129:     }
                   7130:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   7131:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   7132:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   7133:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   7134:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   7135:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   7136:     $r->print(<<DOWNLOAD);
                   7137:     <p>
                   7138: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   7139:     </p>
                   7140:     <p>
                   7141: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   7142:     </p>
                   7143:     <p>
                   7144: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   7145:     </p>
                   7146: DOWNLOAD
1.324     albertel 7147:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 7148:     return '';
                   7149: }
1.157     albertel 7150: 
1.423     albertel 7151: =pod
                   7152: 
                   7153: =back
                   7154: 
                   7155: =cut
                   7156: 
1.75      albertel 7157: #-------- end of section for handling grading scantron forms -------
                   7158: #
                   7159: #-------------------------------------------------------------------
                   7160: 
1.72      ng       7161: #-------------------------- Menu interface -------------------------
                   7162: #
                   7163: #--- Show a Grading Menu button - Calls the next routine ---
                   7164: sub show_grading_menu_form {
1.324     albertel 7165:     my ($symb)=@_;
1.125     ng       7166:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 7167: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 7168: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       7169: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   7170: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   7171: 	'</form>'."\n";
                   7172:     return $result;
                   7173: }
                   7174: 
1.77      ng       7175: # -- Retrieve choices for grading form
                   7176: sub savedState {
                   7177:     my %savedState = ();
1.257     albertel 7178:     if ($env{'form.saveState'}) {
                   7179: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       7180: 	    my ($key,$value) = split(/=/,$_,2);
                   7181: 	    $savedState{$key} = $value;
                   7182: 	}
                   7183:     }
                   7184:     return \%savedState;
                   7185: }
1.76      ng       7186: 
1.443     banghart 7187: sub grading_menu {
                   7188:     my ($request) = @_;
                   7189:     my ($symb)=&get_symb($request);
                   7190:     if (!$symb) {return '';}
                   7191:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   7192:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   7193: 
                   7194:     #
                   7195:     # Define menu data
1.444     banghart 7196:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7197:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7198:     $request->print($table);
1.443     banghart 7199:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   7200:                   'handgrade'=>$hdgrade,
                   7201:                   'probTitle'=>$probTitle,
                   7202:                   'command'=>'submit_options',
                   7203:                   'saveState'=>"",
                   7204:                   'gradingMenu'=>1,
                   7205:                   'showgrading'=>"yes");
                   7206:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7207:     my @menu = ({ url => $url,
                   7208:                      name => &mt('Manual Grading/View Submissions'),
                   7209:                      short_description => 
                   7210:     &mt('Start the process of hand grading submissions.'),
                   7211:                  });
                   7212:     $fields{'command'} = 'csvform';
                   7213:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7214:     push (@menu, { url => $url,
                   7215:                    name => &mt('Upload Scores'),
                   7216:                    short_description => 
                   7217:             &mt('Specify a file containing the class scores for current resource.')});
                   7218:     $fields{'command'} = 'processclicker';
                   7219:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7220:     push (@menu, { url => $url,
                   7221:                    name => &mt('Process Clicker'),
                   7222:                    short_description => 
                   7223:             &mt('Specify a file containing the clicker information for this resource.')});
                   7224:     $fields{'command'} = 'scantron_selectphase';
                   7225:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   7226:     push (@menu, { url => $url,
1.454     banghart 7227:                    name => &mt('Grade/Manage Scantron Forms'),
                   7228:                    short_description => 
                   7229:             &mt('')});
1.443     banghart 7230:     $fields{'command'} = 'verify';
                   7231:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
1.445     banghart 7232:     push (@menu, { url => "",
                   7233:                    jscript => ' onClick="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" ',
1.443     banghart 7234:                    name => &mt('Verify Receipt'),
                   7235:                    short_description => 
                   7236:             &mt('')});
                   7237: 
                   7238:     #
                   7239:     # Create the menu
                   7240:     my $Str;
1.444     banghart 7241:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
1.445     banghart 7242:     $Str .= '<form method="post" action="" name="gradingMenu">';
                   7243:     $Str .= '<input type="hidden" name="command" value="" />'.
                   7244:     	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7245: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7246: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7247: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7248: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7249: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7250: 
1.443     banghart 7251:     foreach my $menudata (@menu) {
1.445     banghart 7252:         if ($menudata->{'name'} ne &mt('Verify Receipt')) {
                   7253:             $Str .='    <h3><a '.
                   7254:                 $menudata->{'jscript'}.
                   7255:                 ' href="'.
                   7256:                 $menudata->{'url'}.'" >'.
                   7257:                 $menudata->{'name'}."</a></h3>\n";
                   7258:         } else {
                   7259:             $Str .='    <h3><a '.
                   7260:                 $menudata->{'jscript'}.
1.446     banghart 7261:                 ' href="javascript:checkChoice2(document.forms.gradingMenu,\'5\',\'verify\')" >'.
1.445     banghart 7262:                 $menudata->{'name'}."</a></h3>\n";
1.446     banghart 7263:             $Str .= ('&nbsp;'x8).
                   7264:                     ' receipt: '.&Apache::lonnet::recprefix($env{'request.course.id'}).
1.445     banghart 7265:                     '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
1.444     banghart 7266:         }
1.443     banghart 7267:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7268:             "\n";
                   7269:     }
                   7270:     $Str .="</dl>\n";
1.444     banghart 7271:     $Str .="</form>\n";
1.443     banghart 7272:     $request->print(<<GRADINGMENUJS);
                   7273: <script type="text/javascript" language="javascript">
                   7274:     function checkChoice(formname,val,cmdx) {
                   7275: 	if (val <= 2) {
                   7276: 	    var cmd = radioSelection(formname.radioChoice);
                   7277: 	    var cmdsave = cmd;
                   7278: 	} else {
                   7279: 	    cmd = cmdx;
                   7280: 	    cmdsave = 'submission';
                   7281: 	}
                   7282: 	formname.command.value = cmd;
                   7283: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7284: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7285: 	if (val < 5) formname.submit();
                   7286: 	if (val == 5) {
                   7287: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7288: 	    formname.submit();
                   7289: 	}
                   7290: 	if (val < 7) formname.submit();
                   7291:     }
1.445     banghart 7292:     function checkChoice2(formname,val,cmdx) {
                   7293: 	if (val <= 2) {
                   7294: 	    var cmd = radioSelection(formname.radioChoice);
                   7295: 	    var cmdsave = cmd;
                   7296: 	} else {
                   7297: 	    cmd = cmdx;
                   7298: 	    cmdsave = 'submission';
                   7299: 	}
                   7300: 	formname.command.value = cmd;
                   7301: 	if (val < 5) formname.submit();
                   7302: 	if (val == 5) {
                   7303: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7304: 	    formname.submit();
                   7305: 	}
                   7306: 	if (val < 7) formname.submit();
                   7307:     }
1.443     banghart 7308: 
                   7309:     function checkReceiptNo(formname,nospace) {
                   7310: 	var receiptNo = formname.receipt.value;
                   7311: 	var checkOpt = false;
                   7312: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7313: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7314: 	if (checkOpt) {
                   7315: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7316: 	    formname.receipt.value = "";
                   7317: 	    formname.receipt.focus();
                   7318: 	    return false;
                   7319: 	}
                   7320: 	return true;
                   7321:     }
                   7322: </script>
                   7323: GRADINGMENUJS
                   7324:     &commonJSfunctions($request);
                   7325:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7326:     $result.=$table;
                   7327:     my (undef,$sections) = &getclasslist('all','0');
                   7328:     my $savedState = &savedState();
                   7329:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7330:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7331:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7332:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7333: 
                   7334:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7335: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7336: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7337: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7338: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7339: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7340: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7341: 
                   7342:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7343: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7344: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7345: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7346: 
                   7347:     $result.='<table width="100%" border="0">';
                   7348:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7349:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7350: #    $result.='<td>Groups</td>';
                   7351:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7352:     $result.='</tr>';
                   7353:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7354: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7355:     if (ref($sections)) {
                   7356: 	foreach (sort (@$sections)) {
                   7357: 	    $result.='<option value="'.$_.'" '.
                   7358: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7359: 	}
                   7360:     }
                   7361:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7362:     return $Str;    
                   7363: }
                   7364: 
                   7365: 
                   7366: #--- Displays the submissions first page -------
                   7367: sub submit_options {
1.72      ng       7368:     my ($request) = @_;
1.324     albertel 7369:     my ($symb)=&get_symb($request);
1.72      ng       7370:     if (!$symb) {return '';}
1.76      ng       7371:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7372: 
                   7373:     $request->print(<<GRADINGMENUJS);
                   7374: <script type="text/javascript" language="javascript">
1.116     ng       7375:     function checkChoice(formname,val,cmdx) {
                   7376: 	if (val <= 2) {
                   7377: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7378: 	    var cmdsave = cmd;
1.116     ng       7379: 	} else {
                   7380: 	    cmd = cmdx;
1.118     ng       7381: 	    cmdsave = 'submission';
1.116     ng       7382: 	}
                   7383: 	formname.command.value = cmd;
1.118     ng       7384: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7385: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7386: 	if (val < 5) formname.submit();
                   7387: 	if (val == 5) {
1.72      ng       7388: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7389: 	    formname.submit();
                   7390: 	}
1.238     albertel 7391: 	if (val < 7) formname.submit();
1.72      ng       7392:     }
                   7393: 
                   7394:     function checkReceiptNo(formname,nospace) {
                   7395: 	var receiptNo = formname.receipt.value;
                   7396: 	var checkOpt = false;
                   7397: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7398: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7399: 	if (checkOpt) {
                   7400: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7401: 	    formname.receipt.value = "";
                   7402: 	    formname.receipt.focus();
                   7403: 	    return false;
                   7404: 	}
                   7405: 	return true;
                   7406:     }
                   7407: </script>
                   7408: GRADINGMENUJS
1.118     ng       7409:     &commonJSfunctions($request);
1.398     albertel 7410:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7411:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7412:     $result.=$table;
1.76      ng       7413:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7414:     my $savedState = &savedState();
1.118     ng       7415:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7416:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7417:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7418:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7419: 
                   7420:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7421: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7422: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7423: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7424: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7425: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7426: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7427: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7428: 
1.446     banghart 7429:     $result.='<table border="0"><tr><td bgcolor=#777777>'."\n".
                   7430: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n".
1.72      ng       7431: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7432: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7433: 
1.326     albertel 7434:     $result.='<table width="100%" border="0">';
1.442     banghart 7435:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7436:     $result.='<td><b>'.&mt('Sections').'</b></td>';
1.446     banghart 7437:     $result.='<td><b>'.&mt('Groups').'</b></td>';
1.442     banghart 7438:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
1.455     banghart 7439:     $result.='<td><b>'.&mt('Submission Status').'</td>'."\n";
1.442     banghart 7440:     $result.='</tr>';
1.116     ng       7441:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7442: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7443:     if (ref($sections)) {
1.155     albertel 7444: 	foreach (sort (@$sections)) {
                   7445: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7446: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7447: 	}
1.116     ng       7448:     }
1.401     albertel 7449:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.446     banghart 7450:     $result.= '</td><td>'."\n";
                   7451:     $result.= &Apache::lonstatistics::GroupSelect('group','multiple',3);
1.442     banghart 7452:     $result.='</td><td>'."\n";
                   7453:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7454: 
1.455     banghart 7455:     $result.='</td>';
                   7456:     $result.='<td><select name="submitonly" size="3">'.
1.145     albertel 7457: 	'<option value="yes" '.
1.401     albertel 7458: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7459: 	'<option value="queued" '.
1.401     albertel 7460: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7461: 	'<option value="graded" '.
1.401     albertel 7462: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7463: 	'<option value="incorrect" '.
1.401     albertel 7464: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7465: 	'<option value="all" '.
1.455     banghart 7466: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>';
1.72      ng       7467: 
1.455     banghart 7468:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
                   7469: 	'<input type="radio" name="radioChoice" value="submission" '.
                   7470: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
                   7471: 	'</label> </td></tr>'."\n";
                   7472: 
                   7473:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3">'.
1.288     albertel 7474: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7475: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7476: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7477: 
1.455     banghart 7478:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
                   7479: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
                   7480: 	'</td></tr>'."\n";
                   7481: 
                   7482: 
                   7483:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="3">'.
                   7484: 	'<br /><label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7485: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.455     banghart 7486: 	'The <b>complete</b> set/page/sequence/folder: For one student</label></td></tr>'."\n";
1.46      ng       7487: 
1.455     banghart 7488:     $result.='<tr bgcolor="#ffffe6"><td colspan="3"><br />'.
1.126     ng       7489: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7490: 	'</td></tr></table>'."\n";
                   7491: 
1.446     banghart 7492:     $result.='</td>'; #<td valign="top">';
1.116     ng       7493: 
1.446     banghart 7494: #    $result.='<table width="100%" border="0">';
                   7495: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7496: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7497: #	' '.&mt('scores from file').' </td></tr>'."\n";
                   7498: #
                   7499: #    $result.='<tr bgcolor="#ffffe6"><td>'.
                   7500: #        '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7501: #        ' '.&mt('clicker file').' </td></tr>'."\n";
                   7502: #
                   7503: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7504: #	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
                   7505: #	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
                   7506: #
                   7507: #    if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
                   7508: #	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
                   7509: #	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7510: #	    ' '.&mt('receipt').': '.
                   7511: #	    &Apache::lonnet::recprefix($env{'request.course.id'}).
                   7512: #	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
                   7513: #	    '</td></tr>'."\n";
                   7514: #    } 
                   7515: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7516: #	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7517: #	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
                   7518: #    $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7519: #	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7520: #	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
                   7521: #
                   7522: #    $result.='</table>'."\n".'</td>';
                   7523:     $result.= '</tr></table>'."\n".
1.401     albertel 7524: 	'</td></tr></table></form>'."\n";
1.44      ng       7525:     return $result;
1.2       albertel 7526: }
                   7527: 
1.285     albertel 7528: sub reset_perm {
                   7529:     undef(%perm);
                   7530: }
                   7531: 
                   7532: sub init_perm {
                   7533:     &reset_perm();
1.300     albertel 7534:     foreach my $test_perm ('vgr','mgr','opa') {
                   7535: 
                   7536: 	my $scope = $env{'request.course.id'};
                   7537: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7538: 
                   7539: 	    $scope .= '/'.$env{'request.course.sec'};
                   7540: 	    if ( $perm{$test_perm}=
                   7541: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7542: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7543: 	    } else {
                   7544: 		delete($perm{$test_perm});
                   7545: 	    }
1.285     albertel 7546: 	}
                   7547:     }
                   7548: }
                   7549: 
1.400     www      7550: sub gather_clicker_ids {
1.408     albertel 7551:     my %clicker_ids;
1.400     www      7552: 
                   7553:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7554: 
                   7555:     # Set up a couple variables.
1.407     albertel 7556:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7557:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7558:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7559: 
1.407     albertel 7560:     foreach my $student (keys(%$classlist)) {
1.438     www      7561:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7562:         my $username = $classlist->{$student}->[$username_idx];
                   7563:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7564:         my $clickers =
1.408     albertel 7565: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7566:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7567:             $id=~s/^[\#0]+//;
1.421     www      7568:             $id=~s/[\-\:]//g;
1.407     albertel 7569:             if (exists($clicker_ids{$id})) {
1.408     albertel 7570: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7571:             } else {
1.408     albertel 7572: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7573:             }
                   7574:         }
                   7575:     }
1.407     albertel 7576:     return %clicker_ids;
1.400     www      7577: }
                   7578: 
1.402     www      7579: sub gather_adv_clicker_ids {
1.408     albertel 7580:     my %clicker_ids;
1.402     www      7581:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7582:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7583:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7584:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7585:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7586:             my ($puname,$pudom)=split(/\:/,$person);
                   7587:             my $clickers =
1.408     albertel 7588: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7589:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7590: 		$id=~s/^[\#0]+//;
1.421     www      7591:                 $id=~s/[\-\:]//g;
1.408     albertel 7592: 		if (exists($clicker_ids{$id})) {
                   7593: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7594: 		} else {
                   7595: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7596: 		}
1.405     www      7597:             }
1.402     www      7598:         }
                   7599:     }
1.407     albertel 7600:     return %clicker_ids;
1.402     www      7601: }
                   7602: 
1.413     www      7603: sub clicker_grading_parameters {
                   7604:     return ('gradingmechanism' => 'scalar',
                   7605:             'upfiletype' => 'scalar',
                   7606:             'specificid' => 'scalar',
                   7607:             'pcorrect' => 'scalar',
                   7608:             'pincorrect' => 'scalar');
                   7609: }
                   7610: 
1.400     www      7611: sub process_clicker {
                   7612:     my ($r)=@_;
                   7613:     my ($symb)=&get_symb($r);
                   7614:     if (!$symb) {return '';}
                   7615:     my $result=&checkforfile_js();
                   7616:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7617:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7618:     $result.=$table;
                   7619:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7620:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7621:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7622:         '.</b></td></tr>'."\n";
                   7623:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7624: # Attempt to restore parameters from last session, set defaults if not present
                   7625:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7626:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7627:                                                  \%Saveable_Parameters);
                   7628:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7629:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7630:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7631:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7632: 
                   7633:     my %checked;
                   7634:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7635:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7636:           $checked{$gradingmechanism}="checked='checked'";
                   7637:        }
                   7638:     }
                   7639: 
1.400     www      7640:     my $upload=&mt("Upload File");
                   7641:     my $type=&mt("Type");
1.402     www      7642:     my $attendance=&mt("Award points just for participation");
                   7643:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7644:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7645:     my $pcorrect=&mt("Percentage points for correct solution");
                   7646:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7647:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7648: 						   ('iclicker' => 'i>clicker',
                   7649:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7650:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7651:     $result.=<<ENDUPFORM;
1.402     www      7652: <script type="text/javascript">
                   7653: function sanitycheck() {
                   7654: // Accept only integer percentages
                   7655:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7656:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7657: // Find out grading choice
                   7658:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7659:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7660:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7661:       }
                   7662:    }
                   7663: // By default, new choice equals user selection
                   7664:    newgradingchoice=gradingchoice;
                   7665: // Not good to give more points for false answers than correct ones
                   7666:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7667:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7668:    }
                   7669: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7670:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7671:       document.forms.gradesupload.pcorrect.value=100;
                   7672:       document.forms.gradesupload.pincorrect.value=100;
                   7673:    }
                   7674: // If the values are different, cannot be attendance only
                   7675:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7676:        (gradingchoice=='attendance')) {
                   7677:        newgradingchoice='personnel';
                   7678:    }
                   7679: // Change grading choice to new one
                   7680:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7681:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7682:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7683:       } else {
                   7684:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7685:       }
                   7686:    }
                   7687: // Remember the old state
                   7688:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7689: }
                   7690: </script>
1.400     www      7691: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7692: <input type="hidden" name="symb" value="$symb" />
                   7693: <input type="hidden" name="command" value="processclickerfile" />
                   7694: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7695: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7696: <input type="file" name="upfile" size="50" />
                   7697: <br /><label>$type: $selectform</label>
1.451     albertel 7698: <br /><label><input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" />$attendance </label>
                   7699: <br /><label><input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" />$personnel</label>
                   7700: <br /><label><input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" />$specific </label>
1.414     www      7701: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7702: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7703: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7704: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7705: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7706: </form>
                   7707: ENDUPFORM
                   7708:     $result.='</td></tr></table>'."\n".
                   7709:              '</td></tr></table><br /><br />'."\n";
                   7710:     $result.=&show_grading_menu_form($symb);
                   7711:     return $result;
                   7712: }
                   7713: 
                   7714: sub process_clicker_file {
                   7715:     my ($r)=@_;
                   7716:     my ($symb)=&get_symb($r);
                   7717:     if (!$symb) {return '';}
1.413     www      7718: 
                   7719:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7720:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7721:                                               \%Saveable_Parameters);
                   7722: 
1.400     www      7723:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7724:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7725: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7726: 	return $result.&show_grading_menu_form($symb);
1.404     www      7727:     }
1.407     albertel 7728:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7729:     my %correct_ids;
1.404     www      7730:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7731: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7732:     }
                   7733:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7734: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7735: 	   $correct_id=~tr/a-z/A-Z/;
                   7736: 	   $correct_id=~s/\s//gs;
                   7737: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7738:            $correct_id=~s/[\-\:]//g;
1.414     www      7739:            if ($correct_id) {
                   7740: 	      $correct_ids{$correct_id}='specified';
                   7741:            }
                   7742:         }
1.400     www      7743:     }
1.404     www      7744:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7745: 	$result.=&mt('Score based on attendance only');
1.404     www      7746:     } else {
1.408     albertel 7747: 	my $number=0;
1.411     www      7748: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7749: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7750: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7751: 	    if ($correct_ids{$id} eq 'specified') {
                   7752: 		$result.=&mt('specified');
                   7753: 	    } else {
                   7754: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7755: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7756: 	    }
                   7757: 	    $number++;
                   7758: 	}
1.411     www      7759:         $result.="</p>\n";
1.408     albertel 7760: 	if ($number==0) {
                   7761: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7762: 	    return $result.&show_grading_menu_form($symb);
                   7763: 	}
1.404     www      7764:     }
1.405     www      7765:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7766:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7767: 		     '<span class="LC_error">',
                   7768: 		     '</span>',
                   7769: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7770:         return $result.&show_grading_menu_form($symb);
                   7771:     }
1.410     www      7772: 
                   7773: # Were able to get all the info needed, now analyze the file
                   7774: 
1.411     www      7775:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7776:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7777:     my $heading=&mt('Scanning clicker file');
                   7778:     $result.=(<<ENDHEADER);
                   7779: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7780: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7781: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7782: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7783: <input type="hidden" name="symb" value="$symb" />
                   7784: <input type="hidden" name="command" value="assignclickergrades" />
                   7785: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7786: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7787: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7788: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7789: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7790: ENDHEADER
1.408     albertel 7791:     my %responses;
                   7792:     my @questiontitles;
1.405     www      7793:     my $errormsg='';
                   7794:     my $number=0;
                   7795:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7796: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7797:     }
1.419     www      7798:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7799:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7800:     }
1.411     www      7801:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7802:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7803:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7804:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7805:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7806:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7807:              '<br />';
1.414     www      7808: # Remember Question Titles
                   7809: # FIXME: Possibly need delimiter other than ":"
                   7810:     for (my $i=0;$i<$number;$i++) {
                   7811:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7812:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7813:     }
1.411     www      7814:     my $correct_count=0;
                   7815:     my $student_count=0;
                   7816:     my $unknown_count=0;
1.414     www      7817: # Match answers with usernames
                   7818: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7819:     foreach my $id (keys(%responses)) {
1.410     www      7820:        if ($correct_ids{$id}) {
1.414     www      7821:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7822:           $correct_count++;
1.410     www      7823:        } elsif ($clicker_ids{$id}) {
1.437     www      7824:           if ($clicker_ids{$id}=~/\,/) {
                   7825: # More than one user with the same clicker!
                   7826:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7827:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7828:                            "<select name='multi".$id."'>";
                   7829:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7830:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7831:              }
                   7832:              $result.='</select>';
                   7833:              $unknown_count++;
                   7834:           } else {
                   7835: # Good: found one and only one user with the right clicker
                   7836:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7837:              $student_count++;
                   7838:           }
1.410     www      7839:        } else {
1.411     www      7840:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7841:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7842:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7843:                    "\n".&mt("Domain").": ".
                   7844:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7845:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7846:           $unknown_count++;
1.410     www      7847:        }
1.405     www      7848:     }
1.412     www      7849:     $result.='<hr />'.
                   7850:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7851:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7852:        if ($correct_count==0) {
                   7853:           $errormsg.="Found no correct answers answers for grading!";
                   7854:        } elsif ($correct_count>1) {
1.414     www      7855:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7856:        }
                   7857:     }
1.428     www      7858:     if ($number<1) {
                   7859:        $errormsg.="Found no questions.";
                   7860:     }
1.412     www      7861:     if ($errormsg) {
                   7862:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7863:     } else {
                   7864:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7865:     }
                   7866:     $result.='</form></td></tr></table>'."\n".
1.410     www      7867:              '</td></tr></table><br /><br />'."\n";
1.404     www      7868:     return $result.&show_grading_menu_form($symb);
1.400     www      7869: }
                   7870: 
1.405     www      7871: sub iclicker_eval {
1.406     www      7872:     my ($questiontitles,$responses)=@_;
1.405     www      7873:     my $number=0;
                   7874:     my $errormsg='';
                   7875:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7876:         my %components=&Apache::loncommon::record_sep($line);
                   7877:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7878: 	if ($entries[0] eq 'Question') {
                   7879: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7880: 		$$questiontitles[$number]=$entries[$i];
                   7881: 		$number++;
                   7882: 	    }
                   7883: 	}
                   7884: 	if ($entries[0]=~/^\#/) {
                   7885: 	    my $id=$entries[0];
                   7886: 	    my @idresponses;
                   7887: 	    $id=~s/^[\#0]+//;
                   7888: 	    for (my $i=0;$i<$number;$i++) {
                   7889: 		my $idx=3+$i*6;
                   7890: 		push(@idresponses,$entries[$idx]);
                   7891: 	    }
                   7892: 	    $$responses{$id}=join(',',@idresponses);
                   7893: 	}
1.405     www      7894:     }
                   7895:     return ($errormsg,$number);
                   7896: }
                   7897: 
1.419     www      7898: sub interwrite_eval {
                   7899:     my ($questiontitles,$responses)=@_;
                   7900:     my $number=0;
                   7901:     my $errormsg='';
1.420     www      7902:     my $skipline=1;
                   7903:     my $questionnumber=0;
                   7904:     my %idresponses=();
1.419     www      7905:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7906:         my %components=&Apache::loncommon::record_sep($line);
                   7907:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7908:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7909:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7910:         next if $skipline;
                   7911:         if ($entries[0]!=$questionnumber) {
                   7912:            $questionnumber=$entries[0];
                   7913:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7914:            $number++;
1.419     www      7915:         }
1.420     www      7916:         my $id=$entries[4];
                   7917:         $id=~s/^[\#0]+//;
1.421     www      7918:         $id=~s/^v\d*\://i;
                   7919:         $id=~s/[\-\:]//g;
1.420     www      7920:         $idresponses{$id}[$number]=$entries[6];
                   7921:     }
                   7922:     foreach my $id (keys %idresponses) {
                   7923:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7924:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7925:     }
                   7926:     return ($errormsg,$number);
                   7927: }
                   7928: 
1.414     www      7929: sub assign_clicker_grades {
                   7930:     my ($r)=@_;
                   7931:     my ($symb)=&get_symb($r);
                   7932:     if (!$symb) {return '';}
1.416     www      7933: # See which part we are saving to
                   7934:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7935: # FIXME: This should probably look for the first handgradeable part
                   7936:     my $part=$$partlist[0];
                   7937: # Start screen output
1.414     www      7938:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7939: 
1.414     www      7940:     my $heading=&mt('Assigning grades based on clicker file');
                   7941:     $result.=(<<ENDHEADER);
                   7942: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7943: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7944: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7945: ENDHEADER
                   7946: # Get correct result
                   7947: # FIXME: Possibly need delimiter other than ":"
                   7948:     my @correct=();
1.415     www      7949:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7950:     my $number=$env{'form.number'};
                   7951:     if ($gradingmechanism ne 'attendance') {
1.414     www      7952:        foreach my $key (keys(%env)) {
                   7953:           if ($key=~/^form\.correct\:/) {
                   7954:              my @input=split(/\,/,$env{$key});
                   7955:              for (my $i=0;$i<=$#input;$i++) {
                   7956:                  if (($correct[$i]) && ($input[$i]) &&
                   7957:                      ($correct[$i] ne $input[$i])) {
                   7958:                     $result.='<br /><span class="LC_warning">'.
                   7959:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7960:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7961:                  } elsif ($input[$i]) {
                   7962:                     $correct[$i]=$input[$i];
                   7963:                  }
                   7964:              }
                   7965:           }
                   7966:        }
1.415     www      7967:        for (my $i=0;$i<$number;$i++) {
1.414     www      7968:           if (!$correct[$i]) {
                   7969:              $result.='<br /><span class="LC_error">'.
                   7970:                       &mt('No correct result given for question "[_1]"!',
                   7971:                           $env{'form.question:'.$i}).'</span>';
                   7972:           }
                   7973:        }
                   7974:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7975:     }
                   7976: # Start grading
1.415     www      7977:     my $pcorrect=$env{'form.pcorrect'};
                   7978:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7979:     my $storecount=0;
1.415     www      7980:     foreach my $key (keys(%env)) {
1.420     www      7981:        my $user='';
1.415     www      7982:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7983:           $user=$1;
                   7984:        }
                   7985:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7986:           my $id=$1;
                   7987:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7988:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7989:           } elsif ($env{'form.multi'.$id}) {
                   7990:              $user=$env{'form.multi'.$id};
1.420     www      7991:           }
                   7992:        }
                   7993:        if ($user) { 
1.415     www      7994:           my @answer=split(/\,/,$env{$key});
                   7995:           my $sum=0;
                   7996:           for (my $i=0;$i<$number;$i++) {
                   7997:              if ($answer[$i]) {
                   7998:                 if ($gradingmechanism eq 'attendance') {
                   7999:                    $sum+=$pcorrect;
                   8000:                 } else {
                   8001:                    if ($answer[$i] eq $correct[$i]) {
                   8002:                       $sum+=$pcorrect;
                   8003:                    } else {
                   8004:                       $sum+=$pincorrect;
                   8005:                    }
                   8006:                 }
                   8007:              }
                   8008:           }
1.416     www      8009:           my $ave=$sum/(100*$number);
                   8010: # Store
                   8011:           my ($username,$domain)=split(/\:/,$user);
                   8012:           my %grades=();
                   8013:           $grades{"resource.$part.solved"}='correct_by_override';
                   8014:           $grades{"resource.$part.awarded"}=$ave;
                   8015:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   8016:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   8017:                                                  $env{'request.course.id'},
                   8018:                                                  $domain,$username);
                   8019:           if ($returncode ne 'ok') {
                   8020:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   8021:           } else {
                   8022:              $storecount++;
                   8023:           }
1.415     www      8024:        }
                   8025:     }
                   8026: # We are done
1.416     www      8027:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   8028:              '</td></tr></table>'."\n".
1.414     www      8029:              '</td></tr></table><br /><br />'."\n";
                   8030:     return $result.&show_grading_menu_form($symb);
                   8031: }
                   8032: 
1.1       albertel 8033: sub handler {
1.41      ng       8034:     my $request=$_[0];
1.434     albertel 8035:     &reset_caches();
1.257     albertel 8036:     if ($env{'browser.mathml'}) {
1.141     www      8037: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       8038:     } else {
1.141     www      8039: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       8040:     }
                   8041:     $request->send_http_header;
1.44      ng       8042:     return '' if $request->header_only;
1.41      ng       8043:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 8044:     my $symb=&get_symb($request,1);
1.160     albertel 8045:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   8046:     my $command=$commands[0];
1.447     foxr     8047: 
1.160     albertel 8048:     if ($#commands > 0) {
                   8049: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   8050:     }
1.447     foxr     8051: 
                   8052: 
1.353     albertel 8053:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 8054:     if ($symb eq '' && $command eq '') {
1.257     albertel 8055: 	if ($env{'user.adv'}) {
                   8056: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   8057: 		($env{'form.codethree'})) {
                   8058: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   8059: 		    $env{'form.codethree'};
1.41      ng       8060: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   8061: 		    &Apache::lonnet::checkin($token);
                   8062: 		if ($tsymb) {
1.137     albertel 8063: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       8064: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 8065: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   8066: 					  ('grade_username' => $tuname,
                   8067: 					   'grade_domain' => $tudom,
                   8068: 					   'grade_courseid' => $tcrsid,
                   8069: 					   'grade_symb' => $tsymb)));
1.41      ng       8070: 		    } else {
1.45      ng       8071: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 8072: 		    }
1.41      ng       8073: 		} else {
1.45      ng       8074: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       8075: 		}
1.14      www      8076: 	    } else {
1.41      ng       8077: 		$request->print(&Apache::lonxml::tokeninputfield());
                   8078: 	    }
                   8079: 	}
                   8080:     } else {
1.285     albertel 8081: 	&init_perm();
1.104     albertel 8082: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 8083: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 8084: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       8085: 	    &pickStudentPage($request);
1.103     albertel 8086: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       8087: 	    &displayPage($request);
1.104     albertel 8088: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       8089: 	    &updateGradeByPage($request);
1.104     albertel 8090: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       8091: 	    &processGroup($request);
1.104     albertel 8092: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 8093: 	    $request->print(&grading_menu($request));
                   8094: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   8095: 	    $request->print(&submit_options($request));
1.104     albertel 8096: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       8097: 	    $request->print(&viewgrades($request));
1.104     albertel 8098: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       8099: 	    $request->print(&processHandGrade($request));
1.106     albertel 8100: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       8101: 	    $request->print(&editgrades($request));
1.106     albertel 8102: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       8103: 	    $request->print(&verifyreceipt($request));
1.400     www      8104:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   8105:             $request->print(&process_clicker($request));
                   8106:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   8107:             $request->print(&process_clicker_file($request));
1.414     www      8108:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   8109:             $request->print(&assign_clicker_grades($request));
1.106     albertel 8110: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       8111: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 8112: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       8113: 	    $request->print(&csvupload($request));
1.106     albertel 8114: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       8115: 	    $request->print(&csvuploadmap($request));
1.246     albertel 8116: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 8117: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 8118: 		$request->print(&csvuploadoptions($request));
1.41      ng       8119: 	    } else {
1.257     albertel 8120: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   8121: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       8122: 		} else {
1.257     albertel 8123: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       8124: 		}
                   8125: 		$request->print(&csvuploadmap($request));
                   8126: 	    }
1.246     albertel 8127: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   8128: 	    $request->print(&csvuploadassign($request));
1.106     albertel 8129: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.447     foxr     8130: 	    &Apache::lonnet::logthis("Selecting pyhase");
1.75      albertel 8131: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 8132:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   8133:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 8134: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   8135: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 8136: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 8137: 	    $request->print(&scantron_process_students($request));
1.157     albertel 8138:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 8139:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8140: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 8141:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 8142:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 8143:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   8144: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 8145:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 8146:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 8147: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 8148:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 8149: 	} elsif ($command) {
1.157     albertel 8150: 	    $request->print("Access Denied ($command)");
1.26      albertel 8151: 	}
1.2       albertel 8152:     }
1.353     albertel 8153:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 8154:     &reset_caches();
1.44      ng       8155:     return '';
                   8156: }
                   8157: 
1.1       albertel 8158: 1;
                   8159: 
1.13      albertel 8160: __END__;

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