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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.444   ! banghart    4: # $Id: grades.pm,v 1.443 2007/10/04 02:00:29 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.55      matthew    38: use Apache::loncoursedata;
1.362     albertel   39: use Apache::lonmsg();
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.386     raeburn    42: use Apache::lonenc;
1.170     albertel   43: use String::Similarity;
1.359     www        44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
1.435     foxr       48: 
                     49: my %perm=();
                     50: my %bubble_lines_per_response;     # no. bubble lines for each response.
                     51:                                    # index is "symb.part_id"
                     52: 
1.1       albertel   53: 
1.68      ng         54: # ----- These first few routines are general use routines.----
1.44      ng         55: #
1.146     albertel   56: # --- Retrieve the parts from the metadata file.---
1.44      ng         57: sub getpartlist {
1.324     albertel   58:     my ($symb) = @_;
1.439     albertel   59: 
                     60:     my $navmap   = Apache::lonnavmaps::navmap->new();
                     61:     my $res      = $navmap->getBySymb($symb);
                     62:     my $partlist = $res->parts();
                     63:     my $url      = $res->src();
                     64:     my @metakeys = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     65: 
1.146     albertel   66:     my @stores;
1.439     albertel   67:     foreach my $part (@{ $partlist }) {
1.146     albertel   68: 	foreach my $key (@metakeys) {
                     69: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     70: 	}
                     71:     }
                     72:     return @stores;
1.2       albertel   73: }
                     74: 
1.44      ng         75: # --- Get the symbolic name of a problem and the url
1.324     albertel   76: sub get_symb {
1.173     albertel   77:     my ($request,$silent) = @_;
1.257     albertel   78:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     79:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   80:     if ($symb eq '') { 
                     81: 	if (!$silent) {
                     82: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     83: 	    return ();
                     84: 	}
                     85:     }
1.418     albertel   86:     &Apache::lonenc::check_decrypt(\$symb);
1.324     albertel   87:     return ($symb);
1.32      ng         88: }
                     89: 
1.129     ng         90: #--- Format fullname, username:domain if different for display
                     91: #--- Use anywhere where the student names are listed
                     92: sub nameUserString {
                     93:     my ($type,$fullname,$uname,$udom) = @_;
                     94:     if ($type eq 'header') {
1.398     albertel   95: 	return '<b>&nbsp;Fullname&nbsp;</b><span class="LC_internal_info">(Username)</span>';
1.129     ng         96:     } else {
1.398     albertel   97: 	return '&nbsp;'.$fullname.'<span class="LC_internal_info">&nbsp;('.$uname.
                     98: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</span>';
1.129     ng         99:     }
                    100: }
                    101: 
1.44      ng        102: #--- Get the partlist and the response type for a given problem. ---
                    103: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        104: sub response_type {
1.324     albertel  105:     my ($symb) = shift;
1.377     albertel  106: 
                    107:     my $navmap = Apache::lonnavmaps::navmap->new();
                    108:     my $res = $navmap->getBySymb($symb);
                    109:     my $partlist = $res->parts();
1.392     albertel  110:     my %vPart = 
                    111: 	map { $_ => 1 } (&Apache::loncommon::get_env_multiple('form.vPart'));
1.377     albertel  112:     my (%response_types,%handgrade);
                    113:     foreach my $part (@{ $partlist }) {
1.392     albertel  114: 	next if (%vPart && !exists($vPart{$part}));
                    115: 
1.377     albertel  116: 	my @types = $res->responseType($part);
                    117: 	my @ids = $res->responseIds($part);
                    118: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    119: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    120: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    121: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    122: 				     '.handgrade',$symb);
1.41      ng        123: 	}
                    124:     }
1.377     albertel  125:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        126: }
                    127: 
1.375     albertel  128: sub flatten_responseType {
                    129:     my ($responseType) = @_;
                    130:     my @part_response_id =
                    131: 	map { 
                    132: 	    my $part = $_;
                    133: 	    map {
                    134: 		[$part,$_]
                    135: 		} sort(keys(%{ $responseType->{$part} }));
                    136: 	} sort(keys(%$responseType));
                    137:     return @part_response_id;
                    138: }
                    139: 
1.207     albertel  140: sub get_display_part {
1.324     albertel  141:     my ($partID,$symb)=@_;
1.207     albertel  142:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    143:     if (defined($display) and $display ne '') {
1.398     albertel  144: 	$display.= " (<span class=\"LC_internal_info\">id $partID</span>)";
1.207     albertel  145:     } else {
                    146: 	$display=$partID;
                    147:     }
                    148:     return $display;
                    149: }
1.269     raeburn   150: 
1.118     ng        151: #--- Show resource title
                    152: #--- and parts and response type
                    153: sub showResourceInfo {
1.324     albertel  154:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  155:     my $col=3;
                    156:     if ($checkboxes) { $col=4; }
1.398     albertel  157:     my $result = '<h3>'.&mt('Current Resource').': '.$probTitle.'</h3>'."\n";
                    158:     $result .='<table border="0">';
1.324     albertel  159:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        160:     my %resptype = ();
1.122     ng        161:     my $hdgrade='no';
1.154     albertel  162:     my %partsseen;
1.375     albertel  163:     foreach my $partID (sort keys(%$responseType)) {
                    164: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    165: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    166: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    167: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    168: 	    $result.='<tr>';
                    169: 	    if ($checkboxes) {
                    170: 		if (exists($partsseen{$partID})) {
                    171: 		    $result.="<td>&nbsp;</td>";
                    172: 		} else {
1.401     albertel  173: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='checked' /></td>";
1.375     albertel  174: 		}
                    175: 		$partsseen{$partID}=1;
1.154     albertel  176: 	    }
1.375     albertel  177: 	    my $display_part=&get_display_part($partID,$symb);
1.398     albertel  178: 	    $result.='<td><b>Part: </b>'.$display_part.' <span class="LC_internal_info">'.
                    179: 		$resID.'</span></td>'.
1.375     albertel  180: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    181: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  182: 	}
1.118     ng        183:     }
                    184:     $result.='</table>'."\n";
1.147     albertel  185:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        186: }
                    187: 
1.434     albertel  188: sub reset_caches {
                    189:     &reset_analyze_cache();
                    190:     &reset_perm();
                    191: }
                    192: 
                    193: {
                    194:     my %analyze_cache;
1.148     albertel  195: 
1.434     albertel  196:     sub reset_analyze_cache {
                    197: 	undef(%analyze_cache);
                    198:     }
                    199: 
                    200:     sub get_analyze {
                    201: 	my ($symb,$uname,$udom)=@_;
                    202: 	my $key = "$symb\0$uname\0$udom";
                    203: 	return $analyze_cache{$key} if (exists($analyze_cache{$key}));
                    204: 
                    205: 	my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    206: 	$url=&Apache::lonnet::clutter($url);
                    207: 	my $subresult=&Apache::lonnet::ssi($url,
                    208: 					   ('grade_target' => 'analyze'),
                    209: 					   ('grade_domain' => $udom),
                    210: 					   ('grade_symb' => $symb),
                    211: 					   ('grade_courseid' => 
                    212: 					    $env{'request.course.id'}),
                    213: 					   ('grade_username' => $uname));
                    214: 	(undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
                    215: 	my %analyze=&Apache::lonnet::str2hash($subresult);
                    216: 	return $analyze_cache{$key} = \%analyze;
                    217:     }
                    218: 
                    219:     sub get_order {
                    220: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    221: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    222: 	return $analyze->{"$partid.$respid.shown"};
                    223:     }
                    224: 
                    225:     sub get_radiobutton_correct_foil {
                    226: 	my ($partid,$respid,$symb,$uname,$udom)=@_;
                    227: 	my $analyze = &get_analyze($symb,$uname,$udom);
                    228: 	foreach my $foil (@{&get_order($partid,$respid,$symb,$uname,$udom)}) {
                    229: 	    if ($analyze->{"$partid.$respid.foil.value.$foil"} eq 'true') {
                    230: 		return $foil;
                    231: 	    }
                    232: 	}
                    233:     }
1.148     albertel  234: }
1.434     albertel  235: 
1.118     ng        236: #--- Clean response type for display
1.335     albertel  237: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    238: #        response types only.
1.118     ng        239: sub cleanRecord {
1.336     albertel  240:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    241: 	$uname,$udom) = @_;
1.398     albertel  242:     my $grayFont = '<span class="LC_internal_info">';
1.148     albertel  243:     if ($response =~ /^(option|rank)$/) {
                    244: 	my %answer=&Apache::lonnet::str2hash($answer);
                    245: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    246: 	my ($toprow,$bottomrow);
                    247: 	foreach my $foil (@$order) {
                    248: 	    if ($grading{$foil} == 1) {
                    249: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    250: 	    } else {
                    251: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    252: 	    }
1.398     albertel  253: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  254: 	}
                    255: 	return '<blockquote><table border="1">'.
                    256: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  257: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  258: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    259:     } elsif ($response eq 'match') {
                    260: 	my %answer=&Apache::lonnet::str2hash($answer);
                    261: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    262: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    263: 	my ($toprow,$middlerow,$bottomrow);
                    264: 	foreach my $foil (@$order) {
                    265: 	    my $item=shift(@items);
                    266: 	    if ($grading{$foil} == 1) {
                    267: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
1.398     albertel  268: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</span></b></td>';
1.148     albertel  269: 	    } else {
                    270: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
1.398     albertel  271: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</span></i></td>';
1.148     albertel  272: 	    }
1.398     albertel  273: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.118     ng        274: 	}
1.126     ng        275: 	return '<blockquote><table border="1">'.
1.148     albertel  276: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  277: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</span></td>'.
1.148     albertel  278: 	    $middlerow.'</tr>'.
1.398     albertel  279: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  280: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    281:     } elsif ($response eq 'radiobutton') {
                    282: 	my %answer=&Apache::lonnet::str2hash($answer);
                    283: 	my ($toprow,$bottomrow);
1.434     albertel  284: 	my $correct = 
                    285: 	    &get_radiobutton_correct_foil($partid,$respid,$symb,$uname,$udom);
                    286: 	foreach my $foil (@$order) {
1.148     albertel  287: 	    if (exists($answer{$foil})) {
1.434     albertel  288: 		if ($foil eq $correct) {
1.148     albertel  289: 		    $toprow.='<td><b>true</b></td>';
                    290: 		} else {
                    291: 		    $toprow.='<td><i>true</i></td>';
                    292: 		}
                    293: 	    } else {
                    294: 		$toprow.='<td>false</td>';
                    295: 	    }
1.398     albertel  296: 	    $bottomrow.='<td>'.$grayFont.$foil.'</span>&nbsp;</td>';
1.148     albertel  297: 	}
                    298: 	return '<blockquote><table border="1">'.
                    299: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
1.398     albertel  300: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</span></td>'.
1.148     albertel  301: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    302:     } elsif ($response eq 'essay') {
1.257     albertel  303: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        304: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  305: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    306: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        307: 
1.257     albertel  308: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    309: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    310: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    311: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    312: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    313: 	    $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        314: 	}
1.166     albertel  315: 	$answer =~ s-\n-<br />-g;
                    316: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  317:     } elsif ( $response eq 'organic') {
                    318: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    319: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    320: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    321: 	return $result;
1.335     albertel  322:     } elsif ( $response eq 'Task') {
                    323: 	if ( $answer eq 'SUBMITTED') {
                    324: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  325: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  326: 	    return $result;
                    327: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    328: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    329: 			       keys(%{$record}));
                    330: 	    return join('<br />',($version,@matches));
                    331: 			       
                    332: 			       
                    333: 	} else {
                    334: 	    my $result =
                    335: 		'<p>'
                    336: 		.&mt('Overall result: [_1]',
                    337: 		     $record->{$version."resource.$respid.$partid.status"})
                    338: 		.'</p>';
                    339: 	    
                    340: 	    $result .= '<ul>';
                    341: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    342: 			     keys(%{$record}));
                    343: 	    foreach my $grade (sort(@grade)) {
                    344: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    345: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    346: 				     $dim, $record->{$grade}).
                    347: 			  '</li>';
                    348: 	    }
                    349: 	    $result.='</ul>';
                    350: 	    return $result;
                    351: 	}
1.440     albertel  352:     } elsif ( $response =~ m/(?:numerical|formula)/) {
                    353: 	$answer = 
                    354: 	    &Apache::loncommon::format_previous_attempt_value('submission',
                    355: 							      $answer);
1.122     ng        356:     }
1.118     ng        357:     return $answer;
                    358: }
                    359: 
                    360: #-- A couple of common js functions
                    361: sub commonJSfunctions {
                    362:     my $request = shift;
                    363:     $request->print(<<COMMONJSFUNCTIONS);
                    364: <script type="text/javascript" language="javascript">
                    365:     function radioSelection(radioButton) {
                    366: 	var selection=null;
                    367: 	if (radioButton.length > 1) {
                    368: 	    for (var i=0; i<radioButton.length; i++) {
                    369: 		if (radioButton[i].checked) {
                    370: 		    return radioButton[i].value;
                    371: 		}
                    372: 	    }
                    373: 	} else {
                    374: 	    if (radioButton.checked) return radioButton.value;
                    375: 	}
                    376: 	return selection;
                    377:     }
                    378: 
                    379:     function pullDownSelection(selectOne) {
                    380: 	var selection="";
                    381: 	if (selectOne.length > 1) {
                    382: 	    for (var i=0; i<selectOne.length; i++) {
                    383: 		if (selectOne[i].selected) {
                    384: 		    return selectOne[i].value;
                    385: 		}
                    386: 	    }
                    387: 	} else {
1.138     albertel  388:             // only one value it must be the selected one
                    389: 	    return selectOne.value;
1.118     ng        390: 	}
                    391:     }
                    392: </script>
                    393: COMMONJSFUNCTIONS
                    394: }
                    395: 
1.44      ng        396: #--- Dumps the class list with usernames,list of sections,
                    397: #--- section, ids and fullnames for each user.
                    398: sub getclasslist {
1.76      ng        399:     my ($getsec,$filterlist) = @_;
1.291     albertel  400:     my @getsec;
1.442     banghart  401:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.291     albertel  402:     if (!ref($getsec)) {
                    403: 	if ($getsec ne '' && $getsec ne 'all') {
                    404: 	    @getsec=($getsec);
                    405: 	}
                    406:     } else {
                    407: 	@getsec=@{$getsec};
                    408:     }
                    409:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    410: 
1.56      matthew   411:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  412:     # Bail out if we were unable to get the classlist
1.56      matthew   413:     return if (! defined($classlist));
                    414:     #
                    415:     my %sections;
                    416:     my %fullnames;
1.205     matthew   417:     foreach my $student (keys(%$classlist)) {
                    418:         my $end      = 
                    419:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    420:         my $start    = 
                    421:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    422:         my $id       = 
                    423:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    424:         my $section  = 
                    425:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    426:         my $fullname = 
                    427:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    428:         my $status   = 
                    429:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        430: 	# filter students according to status selected
1.442     banghart  431: 	if ($filterlist && (!($stu_status =~ /Any/))) {
                    432: 	    if (!($stu_status =~ $status)) {
1.205     matthew   433: 		delete ($classlist->{$student});
1.76      ng        434: 		next;
                    435: 	    }
                    436: 	}
1.205     matthew   437: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  438: 	if (&canview($section)) {
1.291     albertel  439: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  440: 		$sections{$section}++;
1.205     matthew   441: 		$fullnames{$student}=$fullname;
1.103     albertel  442: 	    } else {
1.205     matthew   443: 		delete($classlist->{$student});
1.103     albertel  444: 	    }
                    445: 	} else {
1.205     matthew   446: 	    delete($classlist->{$student});
1.103     albertel  447: 	}
1.44      ng        448:     }
                    449:     my %seen = ();
1.56      matthew   450:     my @sections = sort(keys(%sections));
                    451:     return ($classlist,\@sections,\%fullnames);
1.44      ng        452: }
                    453: 
1.103     albertel  454: sub canmodify {
                    455:     my ($sec)=@_;
                    456:     if ($perm{'mgr'}) {
                    457: 	if (!defined($perm{'mgr_section'})) {
                    458: 	    # can modify whole class
                    459: 	    return 1;
                    460: 	} else {
                    461: 	    if ($sec eq $perm{'mgr_section'}) {
                    462: 		#can modify the requested section
                    463: 		return 1;
                    464: 	    } else {
                    465: 		# can't modify the request section
                    466: 		return 0;
                    467: 	    }
                    468: 	}
                    469:     }
                    470:     #can't modify
                    471:     return 0;
                    472: }
                    473: 
                    474: sub canview {
                    475:     my ($sec)=@_;
                    476:     if ($perm{'vgr'}) {
                    477: 	if (!defined($perm{'vgr_section'})) {
                    478: 	    # can modify whole class
                    479: 	    return 1;
                    480: 	} else {
                    481: 	    if ($sec eq $perm{'vgr_section'}) {
                    482: 		#can modify the requested section
                    483: 		return 1;
                    484: 	    } else {
                    485: 		# can't modify the request section
                    486: 		return 0;
                    487: 	    }
                    488: 	}
                    489:     }
                    490:     #can't modify
                    491:     return 0;
                    492: }
                    493: 
1.44      ng        494: #--- Retrieve the grade status of a student for all the parts
                    495: sub student_gradeStatus {
1.324     albertel  496:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  497:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        498:     my %partstatus = ();
                    499:     foreach (@$partlist) {
1.128     ng        500: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        501: 	$status              = 'nothing' if ($status eq '');
                    502: 	$partstatus{$_}      = $status;
                    503: 	my $subkey           = "resource.$_.submitted_by";
                    504: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    505:     }
                    506:     return %partstatus;
                    507: }
                    508: 
1.45      ng        509: # hidden form and javascript that calls the form
                    510: # Use by verifyscript and viewgrades
                    511: # Shows a student's view of problem and submission
                    512: sub jscriptNform {
1.324     albertel  513:     my ($symb) = @_;
1.442     banghart  514:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.45      ng        515:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    516: 	'    function viewOneStudent(user,domain) {'."\n".
                    517: 	'	document.onestudent.student.value = user;'."\n".
                    518: 	'	document.onestudent.userdom.value = domain;'."\n".
                    519: 	'	document.onestudent.submit();'."\n".
                    520: 	'    }'."\n".
                    521: 	'</script>'."\n";
                    522:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  523: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  524: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    525: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
1.442     banghart  526: 	'<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.45      ng        527: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    528: 	'<input type="hidden" name="student" value="" />'."\n".
                    529: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    530: 	'</form>'."\n";
                    531:     return $jscript;
                    532: }
1.39      ng        533: 
1.315     bowersj2  534: # Given the score (as a number [0-1] and the weight) what is the final
                    535: # point value? This function will round to the nearest tenth, third,
                    536: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  537: sub compute_points {
1.315     bowersj2  538:     my ($score, $weight) = @_;
                    539:     
                    540:     my $tolerance = .00001;
                    541:     my $points = $score * $weight;
                    542: 
                    543:     # Check for nearness to 1/x.
                    544:     my $check_for_nearness = sub {
                    545:         my ($factor) = @_;
                    546:         my $num = ($points * $factor) + $tolerance;
                    547:         my $floored_num = floor($num);
1.316     albertel  548:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  549:             return $floored_num / $factor;
                    550:         }
                    551:         return $points;
                    552:     };
                    553: 
                    554:     $points = $check_for_nearness->(10);
                    555:     $points = $check_for_nearness->(3);
                    556:     $points = $check_for_nearness->(4);
                    557:     
                    558:     return $points;
                    559: }
                    560: 
1.44      ng        561: #------------------ End of general use routines --------------------
1.87      www       562: 
                    563: #
                    564: # Find most similar essay
                    565: #
                    566: 
                    567: sub most_similar {
1.426     albertel  568:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       569: 
                    570: # ignore spaces and punctuation
                    571: 
                    572:     $uessay=~s/\W+/ /gs;
                    573: 
1.282     www       574: # ignore empty submissions (occuring when only files are sent)
                    575: 
                    576:     unless ($uessay=~/\w+/) { return ''; }
                    577: 
1.87      www       578: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       579:     my $limit=0.6;
1.87      www       580:     my $sname='';
                    581:     my $sdom='';
                    582:     my $scrsid='';
                    583:     my $sessay='';
                    584: # go through all essays ...
1.426     albertel  585:     foreach my $tkey (keys(%$old_essays)) {
                    586: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       587: # ... except the same student
1.426     albertel  588:         next if (($tname eq $uname) && ($tdom eq $udom));
                    589: 	my $tessay=$old_essays->{$tkey};
                    590: 	$tessay=~s/\W+/ /gs;
1.87      www       591: # String similarity gives up if not even limit
1.426     albertel  592: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       593: # Found one
1.426     albertel  594: 	if ($tsimilar>$limit) {
                    595: 	    $limit=$tsimilar;
                    596: 	    $sname=$tname;
                    597: 	    $sdom=$tdom;
                    598: 	    $scrsid=$tcrsid;
                    599: 	    $sessay=$old_essays->{$tkey};
                    600: 	}
1.87      www       601:     }
1.88      www       602:     if ($limit>0.6) {
1.87      www       603:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    604:     } else {
                    605:        return ('','','','',0);
                    606:     }
                    607: }
                    608: 
1.44      ng        609: #-------------------------------------------------------------------
                    610: 
                    611: #------------------------------------ Receipt Verification Routines
1.45      ng        612: #
1.44      ng        613: #--- Check whether a receipt number is valid.---
                    614: sub verifyreceipt {
                    615:     my $request  = shift;
                    616: 
1.257     albertel  617:     my $courseid = $env{'request.course.id'};
1.184     www       618:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  619: 	$env{'form.receipt'};
1.44      ng        620:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  621:     my ($symb)   = &get_symb($request);
1.44      ng        622: 
1.398     albertel  623:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    624: 	$receipt.'</h3></span>'."\n".
                    625: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        626: 
                    627:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   628:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  629:     
                    630:     my $receiptparts=0;
1.390     albertel  631:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    632: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  633:     my $parts=['0'];
1.324     albertel  634:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  635:     foreach (sort 
                    636: 	     {
                    637: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    638: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    639: 		 }
                    640: 		 return $a cmp $b;
                    641: 	     } (keys(%$fullname))) {
1.44      ng        642: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  643: 	foreach my $part (@$parts) {
                    644: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    645: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    646: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  647: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  648: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    649: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    650: 		if ($receiptparts) {
                    651: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    652: 		}
                    653: 		$contents.='</tr>'."\n";
                    654: 		
                    655: 		$matches++;
                    656: 	    }
1.44      ng        657: 	}
                    658:     }
                    659:     if ($matches == 0) {
                    660: 	$string = $title.'No match found for the above receipt.';
                    661:     } else {
1.324     albertel  662: 	$string = &jscriptNform($symb).$title.
1.44      ng        663: 	    'The above receipt matches the following student'.
                    664: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    665: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    666: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    667: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    668: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  669: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    670: 	if ($receiptparts) {
                    671: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    672: 	}
                    673: 	$string.='</tr>'."\n".$contents.
1.44      ng        674: 	    '</table></td></tr></table>'."\n";
                    675:     }
1.324     albertel  676:     return $string.&show_grading_menu_form($symb);
1.44      ng        677: }
                    678: 
                    679: #--- This is called by a number of programs.
                    680: #--- Called from the Grading Menu - View/Grade an individual student
                    681: #--- Also called directly when one clicks on the subm button 
                    682: #    on the problem page.
1.30      ng        683: sub listStudents {
1.41      ng        684:     my ($request) = shift;
1.49      albertel  685: 
1.324     albertel  686:     my ($symb) = &get_symb($request);
1.257     albertel  687:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    688:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    689:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    690:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    691: 
                    692:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    693:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    694: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  695: 
1.398     albertel  696:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    697: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        698: 
1.324     albertel  699:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  700: 
1.45      ng        701:     $request->print(<<LISTJAVASCRIPT);
                    702: <script type="text/javascript" language="javascript">
1.110     ng        703:     function checkSelect(checkBox) {
                    704: 	var ctr=0;
                    705: 	var sense="";
                    706: 	if (checkBox.length > 1) {
                    707: 	    for (var i=0; i<checkBox.length; i++) {
                    708: 		if (checkBox[i].checked) {
                    709: 		    ctr++;
                    710: 		}
                    711: 	    }
                    712: 	    sense = "a student or group of students";
                    713: 	} else {
                    714: 	    if (checkBox.checked) {
                    715: 		ctr = 1;
                    716: 	    }
                    717: 	    sense = "the student";
                    718: 	}
                    719: 	if (ctr == 0) {
1.126     ng        720: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        721: 	    return false;
                    722: 	}
                    723: 	document.gradesub.submit();
                    724:     }
                    725: 
                    726:     function reLoadList(formname) {
1.112     ng        727: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        728: 	formname.command.value = 'submission';
                    729: 	formname.submit();
                    730:     }
1.45      ng        731: </script>
                    732: LISTJAVASCRIPT
                    733: 
1.118     ng        734:     &commonJSfunctions($request);
1.41      ng        735:     $request->print($result);
1.39      ng        736: 
1.401     albertel  737:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    738:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  739:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    740: 	"\n".$table.
1.401     albertel  741: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  742: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    743: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    744: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    745: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  746: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  747: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  748:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  749: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  750:     }
1.442     banghart  751:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                    752:     my $saveStatus = $stu_status eq '' ? 'Active' : $stu_status;
1.257     albertel  753:     $env{'form.Status'} = $saveStatus;
1.267     albertel  754:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    755: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    756: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  757: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    758:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    759:         '<option value="1">Whole Points</option>'.
                    760:         '<option value=".5">Half Points</option>'.
1.349     albertel  761:         '<option value=".25">Quarter Points</option>'.
                    762:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  763:         '</select>'.
1.432     banghart  764:         &build_section_inputs().
1.45      ng        765: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  766: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    767: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    768: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    769: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  770: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        771: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    772: 
1.257     albertel  773:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
1.442     banghart  774: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$stu_status.'" />'."\n";
1.124     ng        775:     } else {
                    776: 	$gradeTable.='<b>Student Status:</b> '.
                    777: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    778:     }
1.112     ng        779: 
1.126     ng        780:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    781: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        782: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  783: 
                    784: # checkall buttons
                    785:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        786:     $gradeTable.='<input type="button" '."\n".
1.45      ng        787: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  788: 	'value="Next->" /> <br />'."\n";
                    789:     $gradeTable.=&check_buttons();
1.401     albertel  790:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  791:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        792:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        793: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    794:     my $loop = 0;
                    795:     while ($loop < 2) {
1.126     ng        796: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  797: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  798: 	if ($env{'form.showgrading'} eq 'yes' 
                    799: 	    && $submitonly ne 'queued'
                    800: 	    && $submitonly ne 'all') {
1.110     ng        801: 	    foreach (sort(@$partlist)) {
1.324     albertel  802: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  803: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    804: 		    ' Status&nbsp;</b></td>';
1.110     ng        805: 	    }
1.301     albertel  806: 	} elsif ($submitonly eq 'queued') {
                    807: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        808: 	}
                    809: 	$loop++;
1.126     ng        810: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        811:     }
1.45      ng        812:     $gradeTable.='</tr>'."\n";
1.41      ng        813: 
1.45      ng        814:     my $ctr = 0;
1.294     albertel  815:     foreach my $student (sort 
                    816: 			 {
                    817: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    818: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    819: 			     }
                    820: 			     return $a cmp $b;
                    821: 			 }
                    822: 			 (keys(%$fullname))) {
1.41      ng        823: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  824: 
1.110     ng        825: 	my %status = ();
1.301     albertel  826: 
                    827: 	if ($submitonly eq 'queued') {
                    828: 	    my %queue_status = 
                    829: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    830: 							$udom,$uname);
                    831: 	    next if (!defined($queue_status{'gradingqueue'}));
                    832: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    833: 	}
                    834: 
                    835: 	if ($env{'form.showgrading'} eq 'yes' 
                    836: 	    && $submitonly ne 'queued'
                    837: 	    && $submitonly ne 'all') {
1.324     albertel  838: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  839: 	    my $submitted = 0;
1.164     albertel  840: 	    my $graded = 0;
1.248     albertel  841: 	    my $incorrect = 0;
1.110     ng        842: 	    foreach (keys(%status)) {
1.145     albertel  843: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  844: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    845: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    846: 		
1.110     ng        847: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    848: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  849: 		    $submitted = 0;
1.150     albertel  850: 		    my ($part)=split(/\./,$partid);
1.110     ng        851: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  852: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        853: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    854: 		}
1.41      ng        855: 	    }
1.248     albertel  856: 	    
1.156     albertel  857: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    858: 				     $submitonly eq 'incorrect' ||
                    859: 				     $submitonly eq 'graded'));
1.248     albertel  860: 	    next if (!$graded && ($submitonly eq 'graded'));
                    861: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        862: 	}
1.34      ng        863: 
1.45      ng        864: 	$ctr++;
1.249     albertel  865: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    866: 
1.104     albertel  867: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        868: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        869: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  870:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    871:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    872: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    873: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    874: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        875: 
1.257     albertel  876: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        877: 		foreach (sort keys(%status)) {
                    878: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  879: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        880: 		}
1.41      ng        881: 	    }
1.126     ng        882: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        883: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        884: 	}
                    885:     }
1.110     ng        886:     if ($ctr%2 ==1) {
1.126     ng        887: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  888: 	    if ($env{'form.showgrading'} eq 'yes' 
                    889: 		&& $submitonly ne 'queued'
                    890: 		&& $submitonly ne 'all') {
1.110     ng        891: 		foreach (@$partlist) {
                    892: 		    $gradeTable.='<td>&nbsp;</td>';
                    893: 		}
1.301     albertel  894: 	    } elsif ($submitonly eq 'queued') {
                    895: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        896: 	    }
                    897: 	$gradeTable.='</tr>';
                    898:     }
                    899: 
1.249     albertel  900:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        901: 	'<input type="button" '.
                    902: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        903: 	'value="Next->" /></form>'."\n";
1.45      ng        904:     if ($ctr == 0) {
1.96      albertel  905: 	my $num_students=(scalar(keys(%$fullname)));
                    906: 	if ($num_students eq 0) {
1.398     albertel  907: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  908: 	} else {
1.171     albertel  909: 	    my $submissions='submissions';
                    910: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    911: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  912: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  913: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  914: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  915: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  916: 	}
1.46      ng        917:     } elsif ($ctr == 1) {
                    918: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        919:     }
1.324     albertel  920:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        921:     $request->print($gradeTable);
1.44      ng        922:     return '';
1.10      ng        923: }
                    924: 
1.44      ng        925: #---- Called from the listStudents routine
1.249     albertel  926: 
                    927: sub check_script {
                    928:     my ($form, $type)=@_;
                    929:     my $chkallscript='<script type="text/javascript">
                    930:     function checkall() {
                    931:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    932:             ele = document.forms.'.$form.'.elements[i];
                    933:             if (ele.name == "'.$type.'") {
                    934:             document.forms.'.$form.'.elements[i].checked=true;
                    935:                                        }
                    936:         }
                    937:     }
                    938: 
                    939:     function checksec() {
                    940:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    941:             ele = document.forms.'.$form.'.elements[i];
                    942:            string = document.forms.'.$form.'.chksec.value;
                    943:            if
                    944:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    945:               document.forms.'.$form.'.elements[i].checked=true;
                    946:             }
                    947:         }
                    948:     }
                    949: 
                    950: 
                    951:     function uncheckall() {
                    952:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    953:             ele = document.forms.'.$form.'.elements[i];
                    954:             if (ele.name == "'.$type.'") {
                    955:             document.forms.'.$form.'.elements[i].checked=false;
                    956:                                        }
                    957:         }
                    958:     }
                    959: 
                    960: </script>'."\n";
                    961:     return $chkallscript;
                    962: }
                    963: 
                    964: sub check_buttons {
                    965:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    966:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    967:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    968:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    969:     return $buttons;
                    970: }
                    971: 
1.44      ng        972: #     Displays the submissions for one student or a group of students
1.34      ng        973: sub processGroup {
1.41      ng        974:     my ($request)  = shift;
                    975:     my $ctr        = 0;
1.155     albertel  976:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        977:     my $total      = scalar(@stuchecked)-1;
1.45      ng        978: 
1.396     banghart  979:     foreach my $student (@stuchecked) {
                    980: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  981: 	$env{'form.student'}        = $uname;
                    982: 	$env{'form.userdom'}        = $udom;
                    983: 	$env{'form.fullname'}       = $fullname;
1.41      ng        984: 	&submission($request,$ctr,$total);
                    985: 	$ctr++;
                    986:     }
                    987:     return '';
1.35      ng        988: }
1.34      ng        989: 
1.44      ng        990: #------------------------------------------------------------------------------------
                    991: #
                    992: #-------------------------- Next few routines handles grading by student, essentially
                    993: #                           handles essay response type problem/part
                    994: #
                    995: #--- Javascript to handle the submission page functionality ---
                    996: sub sub_page_js {
                    997:     my $request = shift;
                    998:     $request->print(<<SUBJAVASCRIPT);
                    999: <script type="text/javascript" language="javascript">
1.71      ng       1000:     function updateRadio(formname,id,weight) {
1.125     ng       1001: 	var gradeBox = formname["GD_BOX"+id];
                   1002: 	var radioButton = formname["RADVAL"+id];
                   1003: 	var oldpts = formname["oldpts"+id].value;
1.72      ng       1004: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1005: 	gradeBox.value = pts;
                   1006: 	var resetbox = false;
                   1007: 	if (isNaN(pts) || pts < 0) {
                   1008: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1009: 	    for (var i=0; i<radioButton.length; i++) {
                   1010: 		if (radioButton[i].checked) {
                   1011: 		    gradeBox.value = i;
                   1012: 		    resetbox = true;
                   1013: 		}
                   1014: 	    }
                   1015: 	    if (!resetbox) {
                   1016: 		formtextbox.value = "";
                   1017: 	    }
                   1018: 	    return;
1.44      ng       1019: 	}
1.71      ng       1020: 
                   1021: 	if (pts > weight) {
                   1022: 	    var resp = confirm("You entered a value ("+pts+
                   1023: 			       ") greater than the weight for the part. Accept?");
                   1024: 	    if (resp == false) {
1.125     ng       1025: 		gradeBox.value = oldpts;
1.71      ng       1026: 		return;
                   1027: 	    }
1.44      ng       1028: 	}
1.13      albertel 1029: 
1.71      ng       1030: 	for (var i=0; i<radioButton.length; i++) {
                   1031: 	    radioButton[i].checked=false;
                   1032: 	    if (pts == i && pts != "") {
                   1033: 		radioButton[i].checked=true;
                   1034: 	    }
                   1035: 	}
                   1036: 	updateSelect(formname,id);
1.125     ng       1037: 	formname["stores"+id].value = "0";
1.41      ng       1038:     }
1.5       albertel 1039: 
1.72      ng       1040:     function writeBox(formname,id,pts) {
1.125     ng       1041: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1042: 	if (checkSolved(formname,id) == 'update') {
                   1043: 	    gradeBox.value = pts;
                   1044: 	} else {
1.125     ng       1045: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1046: 	    gradeBox.value = oldpts;
1.125     ng       1047: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1048: 	    for (var i=0; i<radioButton.length; i++) {
                   1049: 		radioButton[i].checked=false;
1.72      ng       1050: 		if (i == oldpts) {
1.71      ng       1051: 		    radioButton[i].checked=true;
                   1052: 		}
                   1053: 	    }
1.41      ng       1054: 	}
1.125     ng       1055: 	formname["stores"+id].value = "0";
1.71      ng       1056: 	updateSelect(formname,id);
                   1057: 	return;
1.41      ng       1058:     }
1.44      ng       1059: 
1.71      ng       1060:     function clearRadBox(formname,id) {
                   1061: 	if (checkSolved(formname,id) == 'noupdate') {
                   1062: 	    updateSelect(formname,id);
                   1063: 	    return;
                   1064: 	}
1.125     ng       1065: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1066: 	for (var i=0; i<gradeSelect.length; i++) {
                   1067: 	    if (gradeSelect[i].selected) {
                   1068: 		var selectx=i;
                   1069: 	    }
                   1070: 	}
1.125     ng       1071: 	var stores = formname["stores"+id];
1.71      ng       1072: 	if (selectx == stores.value) { return };
1.125     ng       1073: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1074: 	gradeBox.value = "";
1.125     ng       1075: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1076: 	for (var i=0; i<radioButton.length; i++) {
                   1077: 	    radioButton[i].checked=false;
                   1078: 	}
                   1079: 	stores.value = selectx;
                   1080:     }
1.5       albertel 1081: 
1.71      ng       1082:     function checkSolved(formname,id) {
1.125     ng       1083: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1084: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1085: 	    if (!reply) {return "noupdate";}
1.120     ng       1086: 	    formname.overRideScore.value = 'yes';
1.41      ng       1087: 	}
1.71      ng       1088: 	return "update";
1.13      albertel 1089:     }
1.71      ng       1090: 
                   1091:     function updateSelect(formname,id) {
1.125     ng       1092: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1093: 	return;
1.41      ng       1094:     }
1.33      ng       1095: 
1.121     ng       1096: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1097:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1098: 	formname.gradeOpt.value = val;
1.71      ng       1099: 	if (val == "Save & Next") {
                   1100: 	    for (i=0;i<=total;i++) {
                   1101: 		for (j=0;j<parttot;j++) {
1.125     ng       1102: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1103: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1104: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1105: 			if (points == "") {
1.125     ng       1106: 			    var name = formname["name"+i].value;
1.129     ng       1107: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1108: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1109: 					       ", part "+partid+". Continue?");
1.71      ng       1110: 			    if (resp == false) {
1.125     ng       1111: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1112: 				return false;
                   1113: 			    }
                   1114: 			}
                   1115: 		    }
                   1116: 		    
                   1117: 		}
                   1118: 	    }
                   1119: 	    
                   1120: 	}
1.121     ng       1121: 	if (val == "Grade Student") {
                   1122: 	    formname.showgrading.value = "yes";
                   1123: 	    if (formname.Status.value == "") {
                   1124: 		formname.Status.value = "Active";
                   1125: 	    }
                   1126: 	    formname.studentNo.value = total;
                   1127: 	}
1.120     ng       1128: 	formname.submit();
                   1129:     }
                   1130: 
1.71      ng       1131: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1132:     function checkSubmitPage(formname,total) {
                   1133: 	noscore = new Array(100);
                   1134: 	var ptr = 0;
                   1135: 	for (i=1;i<total;i++) {
1.125     ng       1136: 	    var partid = formname["q_"+i].value;
1.127     ng       1137: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1138: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1139: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1140: 		if (points == "" && status != "correct_by_student") {
                   1141: 		    noscore[ptr] = i;
                   1142: 		    ptr++;
                   1143: 		}
                   1144: 	    }
                   1145: 	}
                   1146: 	if (ptr != 0) {
                   1147: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1148: 	    var prolist = "";
                   1149: 	    if (ptr == 1) {
                   1150: 		prolist = noscore[0];
                   1151: 	    } else {
                   1152: 		var i = 0;
                   1153: 		while (i < ptr-1) {
                   1154: 		    prolist += noscore[i]+", ";
                   1155: 		    i++;
                   1156: 		}
                   1157: 		prolist += "and "+noscore[i];
                   1158: 	    }
                   1159: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1160: 	    if (resp == false) {
                   1161: 		return false;
                   1162: 	    }
                   1163: 	}
1.45      ng       1164: 
1.71      ng       1165: 	formname.submit();
                   1166:     }
                   1167: </script>
                   1168: SUBJAVASCRIPT
                   1169: }
1.45      ng       1170: 
1.71      ng       1171: #--- javascript for essay type problem --
                   1172: sub sub_page_kw_js {
                   1173:     my $request = shift;
1.80      ng       1174:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1175:     &commonJSfunctions($request);
1.350     albertel 1176: 
1.351     albertel 1177:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1178:     <script text="text/javascript">
                   1179:     function checkInput() {
                   1180:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1181:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1182:       var usrctr = document.msgcenter.usrctr.value;
                   1183:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1184:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1185: 
                   1186:       var msgchk = "";
                   1187:       if (document.msgcenter.subchk.checked) {
                   1188:          msgchk = "msgsub,";
                   1189:       }
                   1190:       var includemsg = 0;
                   1191:       for (var i=1; i<=nmsg; i++) {
                   1192:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1193:           var frmmsg = document.msgcenter["msg"+i];
                   1194:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1195:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1196:           showflg.value = "1";
                   1197:           var chkbox = document.msgcenter["msgn"+i];
                   1198:           if (chkbox.checked) {
                   1199:              msgchk += "savemsg"+i+",";
                   1200:              includemsg = 1;
                   1201:           }
                   1202:       }
                   1203:       if (document.msgcenter.newmsgchk.checked) {
                   1204:          msgchk += "newmsg"+usrctr;
                   1205:          includemsg = 1;
                   1206:       }
                   1207:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1208:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1209:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1210:       includemsg.value = msgchk;
                   1211: 
                   1212:       self.close()
                   1213: 
                   1214:     }
                   1215:     </script>
                   1216: INNERJS
                   1217: 
1.351     albertel 1218:     my $inner_js_highlight_central=<<INNERJS;
                   1219:  <script type="text/javascript">
                   1220:     function updateChoice(flag) {
                   1221:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1222:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1223:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1224:       opener.document.SCORE.refresh.value = "on";
                   1225:       if (opener.document.SCORE.keywords.value!=""){
                   1226:          opener.document.SCORE.submit();
                   1227:       }
                   1228:       self.close()
                   1229:     }
                   1230: </script>
                   1231: INNERJS
                   1232: 
                   1233:     my $start_page_msg_central = 
                   1234:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1235: 				       {'js_ready'  => 1,
                   1236: 					'only_body' => 1,
                   1237: 					'bgcolor'   =>'#FFFFFF',});
                   1238:     my $end_page_msg_central = 
                   1239: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1240: 
                   1241: 
                   1242:     my $start_page_highlight_central = 
                   1243:         &Apache::loncommon::start_page('Highlight Central',
                   1244: 				       $inner_js_highlight_central,
1.350     albertel 1245: 				       {'js_ready'  => 1,
                   1246: 					'only_body' => 1,
                   1247: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1248:     my $end_page_highlight_central = 
1.350     albertel 1249: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1250: 
1.219     www      1251:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1252:     $docopen=~s/^document\.//;
1.71      ng       1253:     $request->print(<<SUBJAVASCRIPT);
                   1254: <script type="text/javascript" language="javascript">
1.45      ng       1255: 
1.44      ng       1256: //===================== Show list of keywords ====================
1.122     ng       1257:   function keywords(formname) {
                   1258:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1259:     if (nret==null) return;
1.122     ng       1260:     formname.keywords.value = nret;
1.44      ng       1261: 
1.122     ng       1262:     if (formname.keywords.value != "") {
1.128     ng       1263: 	formname.refresh.value = "on";
1.122     ng       1264: 	formname.submit();
1.44      ng       1265:     }
                   1266:     return;
                   1267:   }
                   1268: 
                   1269: //===================== Script to view submitted by ==================
                   1270:   function viewSubmitter(submitter) {
                   1271:     document.SCORE.refresh.value = "on";
                   1272:     document.SCORE.NCT.value = "1";
                   1273:     document.SCORE.unamedom0.value = submitter;
                   1274:     document.SCORE.submit();
                   1275:     return;
                   1276:   }
                   1277: 
                   1278: //===================== Script to add keyword(s) ==================
                   1279:   function getSel() {
                   1280:     if (document.getSelection) txt = document.getSelection();
                   1281:     else if (document.selection) txt = document.selection.createRange().text;
                   1282:     else return;
                   1283:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1284:     if (cleantxt=="") {
1.46      ng       1285: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1286: 	return;
                   1287:     }
                   1288:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1289:     if (nret==null) return;
1.127     ng       1290:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1291:     if (document.SCORE.keywords.value != "") {
1.127     ng       1292: 	document.SCORE.refresh.value = "on";
1.44      ng       1293: 	document.SCORE.submit();
                   1294:     }
                   1295:     return;
                   1296:   }
                   1297: 
                   1298: //====================== Script for composing message ==============
1.80      ng       1299:    // preload images
                   1300:    img1 = new Image();
                   1301:    img1.src = "$iconpath/mailbkgrd.gif";
                   1302:    img2 = new Image();
                   1303:    img2.src = "$iconpath/mailto.gif";
                   1304: 
1.44      ng       1305:   function msgCenter(msgform,usrctr,fullname) {
                   1306:     var Nmsg  = msgform.savemsgN.value;
                   1307:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1308:     var subject = msgform.msgsub.value;
1.127     ng       1309:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1310:     re = /msgsub/;
                   1311:     var shwsel = "";
                   1312:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1313:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1314:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1315:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1316: 	var testmsg = "savemsg"+i+",";
                   1317: 	re = new RegExp(testmsg,"g");
1.44      ng       1318: 	shwsel = "";
                   1319: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1320: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1321: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1322: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1323: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1324:     }
1.125     ng       1325:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1326:     shwsel = "";
                   1327:     re = /newmsg/;
                   1328:     if (re.test(msgchk)) { shwsel = "checked" }
                   1329:     newMsg(newmsg,shwsel);
                   1330:     msgTail(); 
                   1331:     return;
                   1332:   }
                   1333: 
1.123     ng       1334:   function checkEntities(strx) {
                   1335:     if (strx.length == 0) return strx;
                   1336:     var orgStr = ["&", "<", ">", '"']; 
                   1337:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1338:     var counter = 0;
                   1339:     while (counter < 4) {
                   1340: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1341: 	counter++;
                   1342:     }
                   1343:     return strx;
                   1344:   }
                   1345: 
                   1346:   function strReplace(strx, orgStr, newStr) {
                   1347:     return strx.split(orgStr).join(newStr);
                   1348:   }
                   1349: 
1.44      ng       1350:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1351:     var height = 70*Nmsg+250;
1.44      ng       1352:     var scrollbar = "no";
                   1353:     if (height > 600) {
                   1354: 	height = 600;
                   1355: 	scrollbar = "yes";
                   1356:     }
1.118     ng       1357:     var xpos = (screen.width-600)/2;
                   1358:     xpos = (xpos < 0) ? '0' : xpos;
                   1359:     var ypos = (screen.height-height)/2-30;
                   1360:     ypos = (ypos < 0) ? '0' : ypos;
                   1361: 
1.206     albertel 1362:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1363:     pWin.focus();
                   1364:     pDoc = pWin.document;
1.219     www      1365:     pDoc.$docopen;
1.351     albertel 1366:     pDoc.write('$start_page_msg_central');
1.76      ng       1367: 
                   1368:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1369:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1370:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1371: 
                   1372:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1373:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1374:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1375: }
                   1376:     function displaySubject(msg,shwsel) {
1.76      ng       1377:     pDoc = pWin.document;
                   1378:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1379:     pDoc.write("<td>Subject</td>");
                   1380:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1381:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1382: }
                   1383: 
1.72      ng       1384:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1385:     pDoc = pWin.document;
                   1386:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1387:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1388:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1389:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1390: }
                   1391: 
                   1392:   function newMsg(newmsg,shwsel) {
1.76      ng       1393:     pDoc = pWin.document;
                   1394:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1395:     pDoc.write("<td align=\\"center\\">New</td>");
                   1396:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1397:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1398: }
                   1399: 
                   1400:   function msgTail() {
1.76      ng       1401:     pDoc = pWin.document;
                   1402:     pDoc.write("</table>");
                   1403:     pDoc.write("</td></tr></table>&nbsp;");
                   1404:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1405:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1406:     pDoc.write("</form>");
1.351     albertel 1407:     pDoc.write('$end_page_msg_central');
1.128     ng       1408:     pDoc.close();
1.44      ng       1409: }
                   1410: 
                   1411: //====================== Script for keyword highlight options ==============
                   1412:   function kwhighlight() {
                   1413:     var kwclr    = document.SCORE.kwclr.value;
                   1414:     var kwsize   = document.SCORE.kwsize.value;
                   1415:     var kwstyle  = document.SCORE.kwstyle.value;
                   1416:     var redsel = "";
                   1417:     var grnsel = "";
                   1418:     var blusel = "";
                   1419:     if (kwclr=="red")   {var redsel="checked"};
                   1420:     if (kwclr=="green") {var grnsel="checked"};
                   1421:     if (kwclr=="blue")  {var blusel="checked"};
                   1422:     var sznsel = "";
                   1423:     var sz1sel = "";
                   1424:     var sz2sel = "";
                   1425:     if (kwsize=="0")  {var sznsel="checked"};
                   1426:     if (kwsize=="+1") {var sz1sel="checked"};
                   1427:     if (kwsize=="+2") {var sz2sel="checked"};
                   1428:     var synsel = "";
                   1429:     var syisel = "";
                   1430:     var sybsel = "";
                   1431:     if (kwstyle=="")    {var synsel="checked"};
                   1432:     if (kwstyle=="<i>") {var syisel="checked"};
                   1433:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1434:     highlightCentral();
                   1435:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1436:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1437:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1438:     highlightend();
                   1439:     return;
                   1440:   }
                   1441: 
                   1442:   function highlightCentral() {
1.76      ng       1443: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1444:     var xpos = (screen.width-400)/2;
                   1445:     xpos = (xpos < 0) ? '0' : xpos;
                   1446:     var ypos = (screen.height-330)/2-30;
                   1447:     ypos = (ypos < 0) ? '0' : ypos;
                   1448: 
1.206     albertel 1449:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1450:     hwdWin.focus();
                   1451:     var hDoc = hwdWin.document;
1.219     www      1452:     hDoc.$docopen;
1.351     albertel 1453:     hDoc.write('$start_page_highlight_central');
1.76      ng       1454:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1455:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1456: 
                   1457:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1458:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1459:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1460:   }
                   1461: 
                   1462:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1463:     var hDoc = hwdWin.document;
                   1464:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1465:     hDoc.write("<td align=\\"left\\">");
                   1466:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1467:     hDoc.write("<td align=\\"left\\">");
                   1468:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1469:     hDoc.write("<td align=\\"left\\">");
                   1470:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1471:     hDoc.write("</tr>");
1.44      ng       1472:   }
                   1473: 
                   1474:   function highlightend() { 
1.76      ng       1475:     var hDoc = hwdWin.document;
                   1476:     hDoc.write("</table>");
                   1477:     hDoc.write("</td></tr></table>&nbsp;");
                   1478:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1479:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1480:     hDoc.write("</form>");
1.351     albertel 1481:     hDoc.write('$end_page_highlight_central');
1.128     ng       1482:     hDoc.close();
1.44      ng       1483:   }
                   1484: 
                   1485: </script>
                   1486: SUBJAVASCRIPT
                   1487: }
                   1488: 
1.349     albertel 1489: sub get_increment {
1.348     bowersj2 1490:     my $increment = $env{'form.increment'};
                   1491:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1492:         $increment != .1) {
                   1493:         $increment = 1;
                   1494:     }
                   1495:     return $increment;
                   1496: }
                   1497: 
1.71      ng       1498: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1499: sub gradeBox {
1.322     albertel 1500:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1501:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1502: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1503: 	'/check.gif" height="16" border="0" />';
                   1504:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1505:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1506: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1507:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1508:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1509: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1510:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1511:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1512:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1513: 				       [$partid]);
                   1514:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1515:     if ($last_resets{$partid}) {
                   1516:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1517:     }
1.71      ng       1518:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1519: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1520:     my $ctr = 0;
1.348     bowersj2 1521:     my $thisweight = 0;
1.349     albertel 1522:     my $increment = &get_increment();
1.71      ng       1523:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1524:     while ($thisweight<=$wgt) {
1.381     albertel 1525: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1526: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1527: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1528: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1529: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1530:         $thisweight += $increment;
1.71      ng       1531: 	$ctr++;
                   1532:     }
                   1533:     $result.='</tr></table>';
                   1534:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1535:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1536: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1537: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1538: 	$wgt.')" /></td>'."\n";
                   1539:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1540: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1541: 	' </td><td>'."\n";
                   1542:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1543: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1544:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1545: 	$result.='<option></option>'.
1.401     albertel 1546: 	    '<option selected="selected">excused</option>';
1.71      ng       1547:     } else {
1.401     albertel 1548: 	$result.='<option selected="selected"></option>'.
1.125     ng       1549: 	    '<option>excused</option>';
1.71      ng       1550:     }
1.125     ng       1551:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1552:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1553:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1554: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1555: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1556: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1557:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1558:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1559:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1560:         $aggtries.'" />'."\n";
1.71      ng       1561:     $result.='</td></tr></table>'."\n";
1.323     banghart 1562:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1563:     return $result;
                   1564: }
1.322     albertel 1565: 
                   1566: sub handback_box {
1.323     banghart 1567:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1568:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1569:     my (@respids);
1.375     albertel 1570:      my @part_response_id = &flatten_responseType($responseType);
                   1571:     foreach my $part_response_id (@part_response_id) {
                   1572:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1573:         if ($part eq $partid) {
1.375     albertel 1574:             push(@respids,$resp);
1.323     banghart 1575:         }
                   1576:     }
1.318     banghart 1577:     my $result;
1.323     banghart 1578:     foreach my $respid (@respids) {
1.322     albertel 1579: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1580: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1581: 	next if (!@$files);
                   1582: 	my $file_counter = 1;
1.313     banghart 1583: 	foreach my $file (@$files) {
1.368     banghart 1584: 	    if ($file =~ /\/portfolio\//) {
                   1585:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1586:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1587:     	        $file_disp = "$name.$ext";
                   1588:     	        $file = $file_path.$file_disp;
                   1589:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1590:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1591:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1592:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1593:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1594:     	        $file_counter++;
                   1595: 	    }
1.322     albertel 1596: 	}
1.313     banghart 1597:     }
1.318     banghart 1598:     return $result;    
1.71      ng       1599: }
1.44      ng       1600: 
1.58      albertel 1601: sub show_problem {
1.382     albertel 1602:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1603:     my $rendered;
1.382     albertel 1604:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1605:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1606:     if ($mode eq 'both' or $mode eq 'text') {
                   1607: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1608: 						       $env{'request.course.id'},
                   1609: 						       undef,\%form);
1.144     albertel 1610:     }
1.58      albertel 1611:     if ($removeform) {
                   1612: 	$rendered=~s|<form(.*?)>||g;
                   1613: 	$rendered=~s|</form>||g;
1.374     albertel 1614: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1615:     }
1.144     albertel 1616:     my $companswer;
                   1617:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1618: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1619: 	$companswer=
                   1620: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1621: 						    $env{'request.course.id'},
                   1622: 						    %form);
1.144     albertel 1623:     }
1.58      albertel 1624:     if ($removeform) {
                   1625: 	$companswer=~s|<form(.*?)>||g;
                   1626: 	$companswer=~s|</form>||g;
1.144     albertel 1627: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1628:     }
                   1629:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1630:     $result.='<table border="0" width="100%">';
1.144     albertel 1631:     if ($viewon) {
                   1632: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1633: 	if ($mode eq 'both' or $mode eq 'text') {
                   1634: 	    $result.='View of the problem - ';
                   1635: 	} else {
                   1636: 	    $result.='Correct answer: ';
                   1637: 	}
1.257     albertel 1638: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1639:     }
                   1640:     if ($mode eq 'both') {
                   1641: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1642: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1643:     } elsif ($mode eq 'text') {
                   1644: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1645:     } elsif ($mode eq 'answer') {
                   1646: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1647:     }
1.58      albertel 1648:     $result.='</td></tr></table>';
                   1649:     $result.='</td></tr></table><br />';
1.71      ng       1650:     return $result;
1.58      albertel 1651: }
1.397     albertel 1652: 
1.396     banghart 1653: sub files_exist {
                   1654:     my ($r, $symb) = @_;
                   1655:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1656: 
1.396     banghart 1657:     foreach my $student (@students) {
                   1658:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1659:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1660: 					      $udom,$uname);
1.396     banghart 1661:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1662:         foreach my $submission (@$string) {
                   1663:             my ($partid,$respid) =
                   1664: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1665:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1666: 					   \%record);
                   1667:             return 1 if (@$files);
1.396     banghart 1668:         }
                   1669:     }
1.397     albertel 1670:     return 0;
1.396     banghart 1671: }
1.397     albertel 1672: 
1.394     banghart 1673: sub download_all_link {
                   1674:     my ($r,$symb) = @_;
1.395     albertel 1675:     my $all_students = 
                   1676: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1677: 
                   1678:     my $parts =
                   1679: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1680: 
1.394     banghart 1681:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1682:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1683:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1684:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1685:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1686: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1687:     return
                   1688: }
1.395     albertel 1689: 
1.432     banghart 1690: sub build_section_inputs {
                   1691:     my $section_inputs;
                   1692:     if ($env{'form.section'} eq '') {
                   1693:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1694:     } else {
                   1695:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1696:         foreach my $section (@sections) {
1.432     banghart 1697:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1698:         }
                   1699:     }
                   1700:     return $section_inputs;
                   1701: }
                   1702: 
1.44      ng       1703: # --------------------------- show submissions of a student, option to grade 
                   1704: sub submission {
                   1705:     my ($request,$counter,$total) = @_;
                   1706: 
1.257     albertel 1707:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1708:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1709:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1710:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.324     albertel 1711:     my $symb = &get_symb($request); 
                   1712:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1713: 
                   1714:     if (!&canview($usec)) {
1.398     albertel 1715: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1716: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1717: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1718: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1719: 	return;
                   1720:     }
                   1721: 
1.257     albertel 1722:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1723:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1724:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1725:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1726:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1727: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1728: 	'/check.gif" height="16" border="0" />';
1.41      ng       1729: 
1.426     albertel 1730:     my %old_essays;
1.41      ng       1731:     # header info
                   1732:     if ($counter == 0) {
                   1733: 	&sub_page_js($request);
1.257     albertel 1734: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1735: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1736: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1737: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1738: 	    &download_all_link($request, $symb);
                   1739: 	}
1.398     albertel 1740: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1741: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1742: 
1.257     albertel 1743: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1744: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1745: 		$checkIcon.' symbol.'."\n";
                   1746: 	    $request->print($checkMark);
                   1747: 	}
1.41      ng       1748: 
1.44      ng       1749: 	# option to display problem, only once else it cause problems 
                   1750:         # with the form later since the problem has a form.
1.257     albertel 1751: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1752: 	    my $mode;
1.257     albertel 1753: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1754: 		$mode='both';
1.257     albertel 1755: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1756: 		$mode='text';
1.257     albertel 1757: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1758: 		$mode='answer';
                   1759: 	    }
1.329     albertel 1760: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1761: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1762: 	}
1.441     www      1763: 
1.44      ng       1764: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1765:         # if this subroutine has been called once.
1.41      ng       1766: 	my %keyhash = ();
1.257     albertel 1767: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1768: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1769: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1770: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1771: 
1.257     albertel 1772: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1773: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1774: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1775: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1776: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1777: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1778: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1779: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1780: 	}
1.257     albertel 1781: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.442     banghart 1782: 	my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.303     banghart 1783: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1784: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1785: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 1786: 			'<input type="hidden" name="Status"     value="'.$stu_status.'" />'."\n".
1.120     ng       1787: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1788: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1789: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1790: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1791: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1792: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1793: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1794: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1795: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1796: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1797: 			&build_section_inputs().
1.326     albertel 1798: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1799: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1800: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1801: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1802: 	if ($env{'form.handgrade'} eq 'yes') {
                   1803: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1804: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1805: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1806: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1807: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1808: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1809: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1810: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1811: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1812: 	    }
1.123     ng       1813: 	}
1.41      ng       1814: 	
                   1815: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1816: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1817: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1818: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1819: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1820: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1821: 		'" />'."\n".
                   1822: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1823: 	    $cts++;
                   1824: 	}
                   1825: 	$request->print($prnmsg);
1.32      ng       1826: 
1.257     albertel 1827: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1828: #
                   1829: # Print out the keyword options line
                   1830: #
1.41      ng       1831: 	    $request->print(<<KEYWORDS);
1.38      ng       1832: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1833: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1834: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1835:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1836: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1837: KEYWORDS
1.88      www      1838: #
                   1839: # Load the other essays for similarity check
                   1840: #
1.324     albertel 1841:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1842: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1843: 	    $apath=&escape($apath);
1.88      www      1844: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1845: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1846:         }
                   1847:     }
1.44      ng       1848: 
1.441     www      1849: # This is where output for one specific student would start
                   1850:     my $bgcolor='#DDEEDD';
                   1851:     if (int($counter/2) eq $counter) { $bgcolor='#DDDDEE'; }
                   1852:     $request->print("\n\n".
                   1853:                     '<p><table border="2"><tr><th bgcolor="'.$bgcolor.'">'.$env{'form.fullname'}.'</th></tr><tr><td bgcolor="'.$bgcolor.'">');
                   1854: 
1.257     albertel 1855:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.144     albertel 1856: 	my $mode;
1.257     albertel 1857: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1858: 	    $mode='both';
1.257     albertel 1859: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1860: 	    $mode='text';
1.257     albertel 1861: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1862: 	    $mode='answer';
                   1863: 	}
1.329     albertel 1864: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1865: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1866:     }
1.144     albertel 1867: 
1.257     albertel 1868:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1869:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1870: 
1.44      ng       1871:     # Display student info
1.41      ng       1872:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1873:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1874: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1875: 
1.257     albertel 1876:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1877:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1878: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1879: 
1.118     ng       1880:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1881:     my @col_fullnames;
1.56      matthew  1882:     my ($classlist,$fullname);
1.257     albertel 1883:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1884: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1885: 	for (keys (%$handgrade)) {
1.44      ng       1886: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1887: 					    '.maxcollaborators',
                   1888:                                             $symb,$udom,$uname);
                   1889: 	    next if ($ncol <= 0);
                   1890:             s/\_/\./g;
                   1891:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1892:             my @goodcollaborators = ();
                   1893:             my @badcollaborators  = ();
                   1894: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1895: 		$_ =~ s/[\$\^\(\)]//g;
                   1896: 		next if ($_ eq '');
1.80      ng       1897: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1898: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1899: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1900: 		# Doing this grep allows 'fuzzy' specification
                   1901: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1902: 		if (! scalar(@Matches)) {
                   1903: 		    push @badcollaborators,$_;
                   1904: 		} else {
                   1905: 		    push @goodcollaborators, @Matches;
                   1906: 		}
1.80      ng       1907: 	    }
1.86      ng       1908:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1909:                 $result.='<b>Collaborators: </b>';
1.86      ng       1910:                 foreach (@goodcollaborators) {
                   1911: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1912: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1913: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1914: 		}
1.57      matthew  1915:                 $result.='<br />'."\n";
1.150     albertel 1916: 		my ($part)=split(/\./,$_);
1.86      ng       1917: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1918: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1919: 		    "\n";
1.86      ng       1920: 	    }
                   1921: 	    if (scalar(@badcollaborators) > 0) {
                   1922: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1923: 		$result.='This student has submitted ';
                   1924: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1925: 		$result .= ': '.join(', ',@badcollaborators);
                   1926: 		$result .= '</td></tr></table>';
                   1927: 	    }         
                   1928: 	    if (scalar(@badcollaborators > $ncol)) {
                   1929: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1930: 		$result .= 'This student has submitted too many '.
                   1931: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1932: 		$result .= '</td></tr></table>';
                   1933: 	    }
1.41      ng       1934: 	}
                   1935:     }
1.44      ng       1936:     $request->print($result."\n");
1.33      ng       1937: 
1.44      ng       1938:     # print student answer/submission
                   1939:     # Options are (1) Handgaded submission only
                   1940:     #             (2) Last submission, includes submission that is not handgraded 
                   1941:     #                  (for multi-response type part)
                   1942:     #             (3) Last submission plus the parts info
                   1943:     #             (4) The whole record for this student
1.257     albertel 1944:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1945: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1946: 	my $lastsubonly=''.
                   1947: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1948: 	     $$timestamp)."</td></tr>\n";
                   1949: 	if ($$timestamp eq '') {
                   1950: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1951: 	} else {
                   1952: 	    my %seenparts;
1.375     albertel 1953: 	    my @part_response_id = &flatten_responseType($responseType);
                   1954: 	    foreach my $part (@part_response_id) {
1.393     albertel 1955: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1956: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1957: 
1.375     albertel 1958: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1959: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1960: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1961: 		    if (exists($seenparts{$partid})) { next; }
                   1962: 		    $seenparts{$partid}=1;
1.207     albertel 1963: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1964: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1965: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1966: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1967: 			'\');" target="_self">'.
1.257     albertel 1968: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1969: 		    $request->print($submitby);
                   1970: 		    next;
                   1971: 		}
                   1972: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1973: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1974: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1975: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1976: 			' )</span>&nbsp; &nbsp;'.
                   1977: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1978: 		    next;
                   1979: 		}
                   1980: 		foreach (@$string) {
                   1981: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1982: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1983: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1984: 		    # Similarity check
                   1985: 		    my $similar='';
1.257     albertel 1986: 		    if($env{'form.checkPlag'}){
1.151     albertel 1987: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1988: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1989: 			if ($osim) {
                   1990: 			    $osim=int($osim*100.0);
1.426     albertel 1991: 			    my %old_course_desc = 
                   1992: 				&Apache::lonnet::coursedescription($ocrsid,
                   1993: 								   {'one_time' => 1});
                   1994: 
                   1995: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1996: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1997: 				    $osim,
                   1998: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1999: 				    $oname,$odom,
1.426     albertel 2000: 				    $old_course_desc{'description'},
1.427     albertel 2001: 				    $old_course_desc{'num'},
1.426     albertel 2002: 				    $old_course_desc{'domain'}).
1.398     albertel 2003: 				'</span></h3><blockquote><i>'.
1.151     albertel 2004: 				&keywords_highlight($oessay).
                   2005: 				'</i></blockquote><hr />';
                   2006: 			}
1.150     albertel 2007: 		    }
1.151     albertel 2008: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 2009: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2010: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2011: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2012: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2013: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2014: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2015: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2016: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2017: 			if (@$files) {
1.398     albertel 2018: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2019: 			    my $file_counter = 0;
1.313     banghart 2020: 			    foreach my $file (@$files) {
1.303     banghart 2021: 			        $file_counter ++;
1.232     albertel 2022: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2023: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2024: 			    }
1.236     albertel 2025: 			    $lastsubonly.='<br />';
1.41      ng       2026: 			}
1.151     albertel 2027: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2028: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2029: 					 $respid,\%record,$order);
                   2030: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2031: 		    }
                   2032: 		}
                   2033: 	    }
1.151     albertel 2034: 	}
                   2035: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2036: 	$request->print($lastsubonly);
1.257     albertel 2037:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2038: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2039: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2040:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2041: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2042: 								 $env{'request.course.id'},
1.44      ng       2043: 								 $last,'.submission',
                   2044: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2045:     }
1.120     ng       2046: 
1.121     ng       2047:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2048: 	.$udom.'" />'."\n");
1.41      ng       2049:     
1.44      ng       2050:     # return if view submission with no grading option
1.257     albertel 2051:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2052: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2053: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2054: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2055: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2056: 	if (($env{'form.command'} eq 'submission') || 
                   2057: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2058: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2059: 	}
1.180     albertel 2060: 	$request->print($toGrade);
1.41      ng       2061: 	return;
1.180     albertel 2062:     } else {
                   2063: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2064:     }
1.33      ng       2065: 
1.121     ng       2066:     # essay grading message center
1.257     albertel 2067:     if ($env{'form.handgrade'} eq 'yes') {
                   2068: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2069: 	my $msgfor = $givenn.' '.$lastname;
                   2070: 	if (scalar(@col_fullnames) > 0) {
                   2071: 	    my $lastone = pop @col_fullnames;
                   2072: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2073: 	}
                   2074: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2075: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2076: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2077: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2078: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2079: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2080: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2081: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2082: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2083: 	    '<br />&nbsp;('.
                   2084: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2085: 	$request->print($result);
1.118     ng       2086:     }
1.300     albertel 2087:     if ($perm{'vgr'}) {
1.297     www      2088: 	$request->print('<br />'.
1.300     albertel 2089: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2090: 						   $uname,$udom,'check'));
1.297     www      2091:     }
1.300     albertel 2092:     if ($perm{'opa'}) {
1.297     www      2093: 	$request->print('<br />'.
1.300     albertel 2094: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2095: 					 $uname,$udom,$symb,'check'));
1.297     www      2096:     }
1.41      ng       2097: 
                   2098:     my %seen = ();
                   2099:     my @partlist;
1.129     ng       2100:     my @gradePartRespid;
1.375     albertel 2101:     my @part_response_id = &flatten_responseType($responseType);
                   2102:     foreach my $part_response_id (@part_response_id) {
                   2103:     	my ($partid,$respid) = @{ $part_response_id };
                   2104: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2105: 	next if ($seen{$partid} > 0);
1.41      ng       2106: 	$seen{$partid}++;
1.393     albertel 2107: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2108: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2109: 	push @partlist,$partid;
1.129     ng       2110: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2111: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2112:     }
1.45      ng       2113:     $result='<input type="hidden" name="partlist'.$counter.
                   2114: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2115:     $result.='<input type="hidden" name="gradePartRespid'.
                   2116: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2117:     my $ctr = 0;
                   2118:     while ($ctr < scalar(@partlist)) {
                   2119: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2120: 	    $partlist[$ctr].'" />'."\n";
                   2121: 	$ctr++;
                   2122:     }
                   2123:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2124: 
1.441     www      2125: # Done with printing info for one student
                   2126: 
                   2127:     $request->print('</td></tr></table></p>');
                   2128: 
                   2129: 
1.41      ng       2130:     # print end of form
                   2131:     if ($counter == $total) {
1.297     www      2132: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2133: 	$endform.='<input type="button" value="Save & Next" '.
                   2134: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2135: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2136: 	my $ntstu ='<select name="NTSTU">'.
                   2137: 	    '<option>1</option><option>2</option>'.
                   2138: 	    '<option>3</option><option>5</option>'.
                   2139: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2140: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2141: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2142: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2143: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2144: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2145: 	    '<input type="button" value="Next" '.
1.417     albertel 2146: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2147: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2148:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2149:             "' name='increment' />";
1.45      ng       2150: 	$endform.='</td><tr></table></form>';
1.324     albertel 2151: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2152: 	$request->print($endform);
                   2153:     }
                   2154:     return '';
1.38      ng       2155: }
                   2156: 
1.44      ng       2157: #--- Retrieve the last submission for all the parts
1.38      ng       2158: sub get_last_submission {
1.119     ng       2159:     my ($returnhash)=@_;
1.46      ng       2160:     my (@string,$timestamp);
1.119     ng       2161:     if ($$returnhash{'version'}) {
1.46      ng       2162: 	my %lasthash=();
                   2163: 	my ($version);
1.119     ng       2164: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2165: 	    foreach my $key (sort(split(/\:/,
                   2166: 					$$returnhash{$version.':keys'}))) {
                   2167: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2168: 		$timestamp = 
                   2169: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2170: 	    }
                   2171: 	}
1.397     albertel 2172: 	foreach my $key (keys(%lasthash)) {
                   2173: 	    next if ($key !~ /\.submission$/);
                   2174: 
                   2175: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2176: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2177: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2178: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2179: 	}
                   2180:     }
1.397     albertel 2181:     if (!@string) {
                   2182: 	$string[0] =
1.398     albertel 2183: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2184:     }
                   2185:     return (\@string,\$timestamp);
1.38      ng       2186: }
1.35      ng       2187: 
1.44      ng       2188: #--- High light keywords, with style choosen by user.
1.38      ng       2189: sub keywords_highlight {
1.44      ng       2190:     my $string    = shift;
1.257     albertel 2191:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2192:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2193:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2194:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2195:     foreach my $keyword (@keylist) {
                   2196: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2197:     }
                   2198:     return $string;
1.38      ng       2199: }
1.36      ng       2200: 
1.44      ng       2201: #--- Called from submission routine
1.38      ng       2202: sub processHandGrade {
1.41      ng       2203:     my ($request) = shift;
1.324     albertel 2204:     my $symb   = &get_symb($request);
                   2205:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2206:     my $button = $env{'form.gradeOpt'};
                   2207:     my $ngrade = $env{'form.NCT'};
                   2208:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2209:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2210:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2211: 
1.44      ng       2212:     if ($button eq 'Save & Next') {
                   2213: 	my $ctr = 0;
                   2214: 	while ($ctr < $ngrade) {
1.257     albertel 2215: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2216: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2217: 	    if ($errorflag eq 'no_score') {
                   2218: 		$ctr++;
                   2219: 		next;
                   2220: 	    }
1.104     albertel 2221: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2222: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2223: 		$ctr++;
                   2224: 		next;
                   2225: 	    }
1.257     albertel 2226: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2227: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2228: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2229:             my ($feedurl,$showsymb) =
                   2230: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2231: 	    my $messagetail;
1.62      albertel 2232: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2233: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2234: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2235: 		$subject.=' ['.$restitle.']';
1.44      ng       2236: 		my (@msgnum) = split(/,/,$includemsg);
                   2237: 		foreach (@msgnum) {
1.257     albertel 2238: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2239: 		}
1.80      ng       2240: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2241: 		if ($env{'form.withgrades'.$ctr}) {
                   2242: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2243: 		    $messagetail = " for <a href=\"".
1.418     albertel 2244: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2245: 		}
                   2246: 		$msgstatus = 
                   2247:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2248: 						     $message.$messagetail,
1.418     albertel 2249:                                                      undef,$feedurl,undef,
1.386     raeburn  2250:                                                      undef,undef,$showsymb,
                   2251:                                                      $restitle);
                   2252: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2253: 				$msgstatus);
1.44      ng       2254: 	    }
1.257     albertel 2255: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2256: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2257: 		foreach my $collabstr (@collabstrs) {
                   2258: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2259: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2260: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2261: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2262: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2263: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2264: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2265: 			    next;
1.418     albertel 2266: 			} elsif ($message ne '') {
                   2267: 			    my ($baseurl,$showsymb) = 
                   2268: 				&get_feedurl_and_symb($symb,$collaborator,
                   2269: 						      $udom);
                   2270: 			    if ($env{'form.withgrades'.$ctr}) {
                   2271: 				$messagetail = " for <a href=\"".
1.386     raeburn  2272:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2273: 			    }
1.418     albertel 2274: 			    $msgstatus = 
                   2275: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2276: 			}
1.44      ng       2277: 		    }
                   2278: 		}
                   2279: 	    }
                   2280: 	    $ctr++;
                   2281: 	}
                   2282:     }
                   2283: 
1.257     albertel 2284:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2285: 	# Keywords sorted in alphabatical order
1.257     albertel 2286: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2287: 	my %keyhash = ();
1.257     albertel 2288: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2289: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2290: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2291: 	$env{'form.keywords'} = join(' ',@keywords);
                   2292: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2293: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2294: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2295: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2296: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2297: 
                   2298: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2299: 	# New messages are saved in env for the next student.
1.119     ng       2300: 	# All messages are saved in nohist_handgrade.db
                   2301: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2302: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2303: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2304: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2305: 		$idx++;
                   2306: 	    }
                   2307: 	    $ctr++;
1.41      ng       2308: 	}
1.119     ng       2309: 	$ctr = 0;
                   2310: 	while ($ctr < $ngrade) {
1.257     albertel 2311: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2312: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2313: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2314: 		$idx++;
                   2315: 	    }
                   2316: 	    $ctr++;
1.41      ng       2317: 	}
1.257     albertel 2318: 	$env{'form.savemsgN'} = --$idx;
                   2319: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2320: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2321: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2322:     }
1.44      ng       2323:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2324:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2325:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2326: 	my ($ctr,$total) = (0,0);
                   2327: 	while ($ctr < $ngrade) {
1.257     albertel 2328: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2329: 	    $ctr++;
                   2330: 	}
1.257     albertel 2331: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2332: 	$ctr = 0;
                   2333: 	while ($ctr < $total) {
1.257     albertel 2334: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2335: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2336: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2337: 	    &submission($request,$ctr,$total-1);
1.41      ng       2338: 	    $ctr++;
                   2339: 	}
                   2340: 	return '';
                   2341:     }
1.36      ng       2342: 
1.121     ng       2343: # Go directly to grade student - from submission or link from chart page
1.120     ng       2344:     if ($button eq 'Grade Student') {
1.324     albertel 2345: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2346: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2347: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2348: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2349: 	&submission($request,0,0);
                   2350: 	return '';
                   2351:     }
                   2352: 
1.44      ng       2353:     # Get the next/previous one or group of students
1.257     albertel 2354:     my $firststu = $env{'form.unamedom0'};
                   2355:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2356:     my $ctr = 2;
1.41      ng       2357:     while ($laststu eq '') {
1.257     albertel 2358: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2359: 	$ctr++;
                   2360: 	$laststu = $firststu if ($ctr > $ngrade);
                   2361:     }
1.44      ng       2362: 
1.41      ng       2363:     my (@parsedlist,@nextlist);
                   2364:     my ($nextflg) = 0;
1.294     albertel 2365:     foreach (sort 
                   2366: 	     {
                   2367: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2368: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2369: 		 }
                   2370: 		 return $a cmp $b;
                   2371: 	     } (keys(%$fullname))) {
1.41      ng       2372: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2373: 	    push @parsedlist,$_;
                   2374: 	}
                   2375: 	$nextflg = 1 if ($_ eq $laststu);
                   2376: 	if ($button eq 'Previous') {
                   2377: 	    last if ($_ eq $firststu);
                   2378: 	    push @parsedlist,$_;
                   2379: 	}
                   2380:     }
                   2381:     $ctr = 0;
                   2382:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2383:     my ($partlist) = &response_type($symb);
1.41      ng       2384:     foreach my $student (@parsedlist) {
1.257     albertel 2385: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2386: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2387: 	
                   2388: 	if ($submitonly eq 'queued') {
                   2389: 	    my %queue_status = 
                   2390: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2391: 							$udom,$uname);
                   2392: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2393: 	}
                   2394: 
1.156     albertel 2395: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2396: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2397: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2398: 	    my $submitted = 0;
1.248     albertel 2399: 	    my $ungraded = 0;
                   2400: 	    my $incorrect = 0;
1.145     albertel 2401: 	    foreach (keys(%status)) {
                   2402: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2403: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2404: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2405: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2406: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2407: 		    $submitted = 0;
                   2408: 		}
1.41      ng       2409: 	    }
1.156     albertel 2410: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2411: 				     $submitonly eq 'incorrect' ||
                   2412: 				     $submitonly eq 'graded'));
1.248     albertel 2413: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2414: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2415: 	}
                   2416: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2417: 	last if ($ctr == $ntstu);
1.41      ng       2418: 	$ctr++;
                   2419:     }
1.36      ng       2420: 
1.41      ng       2421:     $ctr = 0;
                   2422:     my $total = scalar(@nextlist)-1;
1.39      ng       2423: 
1.41      ng       2424:     foreach (sort @nextlist) {
                   2425: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2426: 	$env{'form.student'}  = $uname;
                   2427: 	$env{'form.userdom'}  = $udom;
                   2428: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2429: 	&submission($request,$ctr,$total);
                   2430: 	$ctr++;
                   2431:     }
                   2432:     if ($total < 0) {
1.398     albertel 2433: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2434: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2435: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2436: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2437: 	$request->print($the_end);
                   2438:     }
                   2439:     return '';
1.38      ng       2440: }
1.36      ng       2441: 
1.44      ng       2442: #---- Save the score and award for each student, if changed
1.38      ng       2443: sub saveHandGrade {
1.324     albertel 2444:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2445:     my @version_parts;
1.104     albertel 2446:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2447: 					   $env{'request.course.id'});
1.104     albertel 2448:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2449:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2450:     my @parts_graded;
1.77      ng       2451:     my %newrecord  = ();
                   2452:     my ($pts,$wgt) = ('','');
1.269     raeburn  2453:     my %aggregate = ();
                   2454:     my $aggregateflag = 0;
1.301     albertel 2455:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2456:     foreach my $new_part (@parts) {
1.337     banghart 2457: 	#collaborator ($submi may vary for different parts
1.259     banghart 2458: 	if ($submitter && $new_part ne $part) { next; }
                   2459: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2460: 	if ($dropMenu eq 'excused') {
1.259     banghart 2461: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2462: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2463: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2464: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2465: 		}
1.364     banghart 2466: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2467: 	    }
1.125     ng       2468: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2469: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2470: 	    foreach my $key (keys (%record)) {
1.259     banghart 2471: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2472: 	    }
1.259     banghart 2473: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2474: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2475:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2476: 
                   2477:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2478: 					       [$new_part]);
                   2479:             my $aggtries =$totaltries;
1.269     raeburn  2480:             if ($last_resets{$new_part}) {
1.270     albertel 2481:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2482: 					   $new_part);
1.269     raeburn  2483:             }
1.270     albertel 2484: 
                   2485:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2486:             if ($aggtries > 0) {
1.327     albertel 2487:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2488:                 $aggregateflag = 1;
                   2489:             }
1.125     ng       2490: 	} elsif ($dropMenu eq '') {
1.259     banghart 2491: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2492: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2493: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2494: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2495: 		next;
                   2496: 	    }
1.259     banghart 2497: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2498: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2499: 	    my $partial= $pts/$wgt;
1.259     banghart 2500: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2501: 		#do not update score for part if not changed.
1.346     banghart 2502:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2503: 		next;
1.251     banghart 2504: 	    } else {
1.259     banghart 2505: 	        push @parts_graded, $new_part;
1.153     albertel 2506: 	    }
1.259     banghart 2507: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2508: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2509: 	    }
1.259     banghart 2510: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2511: 	    if ($partial == 0) {
1.153     albertel 2512: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2513: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2514: 		}
1.41      ng       2515: 	    } else {
1.153     albertel 2516: 		if ($record{$reckey} ne 'correct_by_override') {
                   2517: 		    $newrecord{$reckey} = 'correct_by_override';
                   2518: 		}
                   2519: 	    }	    
                   2520: 	    if ($submitter && 
1.259     banghart 2521: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2522: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2523: 	    }
1.259     banghart 2524: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2525: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2526: 	}
1.259     banghart 2527: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2528: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2529: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2530: 	        $dropMenu eq 'reset status')
                   2531: 	   {
1.342     banghart 2532: 	    push (@version_parts,$new_part);
1.259     banghart 2533: 	}
1.41      ng       2534:     }
1.301     albertel 2535:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2536:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2537: 
1.344     albertel 2538:     if (%newrecord) {
                   2539:         if (@version_parts) {
1.364     banghart 2540:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2541:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2542: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2543: 	    foreach my $new_part (@version_parts) {
                   2544: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2545: 				$new_part,\%newrecord);
                   2546: 	    }
1.259     banghart 2547:         }
1.44      ng       2548: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2549: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2550: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2551: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2552:     }
1.269     raeburn  2553:     if ($aggregateflag) {
                   2554:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2555: 			      $cdom,$cnum);
1.269     raeburn  2556:     }
1.301     albertel 2557:     return ('',$pts,$wgt);
1.36      ng       2558: }
1.322     albertel 2559: 
1.380     albertel 2560: sub check_and_remove_from_queue {
                   2561:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2562:     my @ungraded_parts;
                   2563:     foreach my $part (@{$parts}) {
                   2564: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2565: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2566: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2567: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2568: 		) {
                   2569: 	    push(@ungraded_parts, $part);
                   2570: 	}
                   2571:     }
                   2572:     if ( !@ungraded_parts ) {
                   2573: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2574: 					       $cnum,$domain,$stuname);
                   2575:     }
                   2576: }
                   2577: 
1.337     banghart 2578: sub handback_files {
                   2579:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2580:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2581:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2582: 
                   2583:     my @part_response_id = &flatten_responseType($responseType);
                   2584:     foreach my $part_response_id (@part_response_id) {
                   2585:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2586: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2587:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2588:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2589:                 my $file_counter = 1;
1.367     albertel 2590: 		my $file_msg;
1.337     banghart 2591:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2592:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2593:                     my ($directory,$answer_file) = 
                   2594:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2595:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2596: 		        &file_name_version_ext($answer_file);
1.355     banghart 2597: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2598: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2599: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2600:                     # fix file name
                   2601:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2602:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2603:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2604:             	                                $save_file_name);
1.337     banghart 2605:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2606:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2607:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2608:                     } else {
1.360     banghart 2609:                         # mark the file as read only
                   2610:                         my @files = ($save_file_name);
1.372     albertel 2611:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2612:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2613: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2614: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2615: 			}
                   2616:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2617: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2618: 
1.337     banghart 2619:                     }
                   2620:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2621:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2622:                     $file_counter++;
                   2623:                 }
1.367     albertel 2624: 		my $subject = "File Handed Back by Instructor ";
                   2625: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2626: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2627: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2628: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2629: 		my ($feedurl,$showsymb) = 
                   2630: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2631:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2632: 		my $msgstatus = 
                   2633:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2634: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2635:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2636:             }
                   2637:         }
1.338     banghart 2638:     return;
1.337     banghart 2639: }
                   2640: 
1.418     albertel 2641: sub get_feedurl_and_symb {
                   2642:     my ($symb,$uname,$udom) = @_;
                   2643:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2644:     $url = &Apache::lonnet::clutter($url);
                   2645:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2646: 					$symb,$udom,$uname);
                   2647:     if ($encrypturl =~ /^yes$/i) {
                   2648: 	&Apache::lonenc::encrypted(\$url,1);
                   2649: 	&Apache::lonenc::encrypted(\$symb,1);
                   2650:     }
                   2651:     return ($url,$symb);
                   2652: }
                   2653: 
1.313     banghart 2654: sub get_submitted_files {
                   2655:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2656:     my @files;
                   2657:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2658:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2659:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2660:     	    push(@files,$file_url.$file);
                   2661:         }
                   2662:     }
                   2663:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2664:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2665:     }
                   2666:     return (\@files);
                   2667: }
1.322     albertel 2668: 
1.269     raeburn  2669: # ----------- Provides number of tries since last reset.
                   2670: sub get_num_tries {
                   2671:     my ($record,$last_reset,$part) = @_;
                   2672:     my $timestamp = '';
                   2673:     my $num_tries = 0;
                   2674:     if ($$record{'version'}) {
                   2675:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2676:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2677:                 $timestamp = $$record{$version.':timestamp'};
                   2678:                 if ($timestamp > $last_reset) {
                   2679:                     $num_tries ++;
                   2680:                 } else {
                   2681:                     last;
                   2682:                 }
                   2683:             }
                   2684:         }
                   2685:     }
                   2686:     return $num_tries;
                   2687: }
                   2688: 
                   2689: # ----------- Determine decrements required in aggregate totals 
                   2690: sub decrement_aggs {
                   2691:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2692:     my %decrement = (
                   2693:                         attempts => 0,
                   2694:                         users => 0,
                   2695:                         correct => 0
                   2696:                     );
                   2697:     $decrement{'attempts'} = $aggtries;
                   2698:     if ($solvedstatus =~ /^correct/) {
                   2699:         $decrement{'correct'} = 1;
                   2700:     }
                   2701:     if ($aggtries == $totaltries) {
                   2702:         $decrement{'users'} = 1;
                   2703:     }
                   2704:     foreach my $type (keys (%decrement)) {
                   2705:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2706:     }
                   2707:     return;
                   2708: }
                   2709: 
                   2710: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2711: sub get_last_resets {
1.270     albertel 2712:     my ($symb,$courseid,$partids) =@_;
                   2713:     my %last_resets;
1.269     raeburn  2714:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2715:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2716:     my @keys;
                   2717:     foreach my $part (@{$partids}) {
                   2718: 	push(@keys,"$symb\0$part\0resettime");
                   2719:     }
                   2720:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2721: 				     $cdom,$cname);
                   2722:     foreach my $part (@{$partids}) {
                   2723: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2724:     }
1.270     albertel 2725:     return %last_resets;
1.269     raeburn  2726: }
                   2727: 
1.251     banghart 2728: # ----------- Handles creating versions for portfolio files as answers
                   2729: sub version_portfiles {
1.343     banghart 2730:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2731:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2732:     my @returned_keys;
1.255     banghart 2733:     my $parts = join('|', @$parts_graded);
1.359     www      2734:     my $portfolio_root = &propath($domain,$stu_name).
                   2735: 	'/userfiles/portfolio';
1.277     albertel 2736:     foreach my $key (keys(%$record)) {
1.259     banghart 2737:         my $new_portfiles;
1.263     banghart 2738:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2739:             my @versioned_portfiles;
1.367     albertel 2740:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2741:             foreach my $file (@portfiles) {
1.306     banghart 2742:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2743:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2744: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2745: 		    &file_name_version_ext($answer_file);
1.306     banghart 2746:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2747:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2748:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2749:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2750:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2751:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2752:                         [$directory.$new_answer],
1.306     banghart 2753:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2754:                 }
1.252     banghart 2755:             }
1.343     banghart 2756:             $$record{$key} = join(',',@versioned_portfiles);
                   2757:             push(@returned_keys,$key);
1.251     banghart 2758:         }
                   2759:     } 
1.343     banghart 2760:     return (@returned_keys);   
1.305     banghart 2761: }
                   2762: 
1.307     banghart 2763: sub get_next_version {
1.341     banghart 2764:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2765:     my $version;
                   2766:     foreach my $row (@$dir_list) {
                   2767:         my ($file) = split(/\&/,$row,2);
                   2768:         my ($file_name,$file_version,$file_ext) =
                   2769: 	    &file_name_version_ext($file);
                   2770:         if (($file_name eq $answer_name) && 
                   2771: 	    ($file_ext eq $answer_ext)) {
                   2772:                 # gets here if filename and extension match, regardless of version
                   2773:                 if ($file_version ne '') {
                   2774:                 # a versioned file is found  so save it for later
                   2775:                 if ($file_version > $version) {
                   2776: 		    $version = $file_version;
                   2777: 	        }
                   2778:             }
                   2779:         }
                   2780:     } 
                   2781:     $version ++;
                   2782:     return($version);
                   2783: }
                   2784: 
1.305     banghart 2785: sub version_selected_portfile {
1.306     banghart 2786:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2787:     my ($answer_name,$answer_ver,$answer_ext) =
                   2788:         &file_name_version_ext($file_name);
                   2789:     my $new_answer;
                   2790:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2791:     if($env{'form.copy'} eq '-1') {
                   2792:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2793:         $new_answer = 'problem getting file';
                   2794:     } else {
                   2795:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2796:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2797:                             $stu_name,$domain,'copy',
                   2798: 		        '/portfolio'.$directory.$new_answer);
                   2799:     }    
                   2800:     return ($new_answer);
1.251     banghart 2801: }
                   2802: 
1.304     albertel 2803: sub file_name_version_ext {
                   2804:     my ($file)=@_;
                   2805:     my @file_parts = split(/\./, $file);
                   2806:     my ($name,$version,$ext);
                   2807:     if (@file_parts > 1) {
                   2808: 	$ext=pop(@file_parts);
                   2809: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2810: 	    $version=pop(@file_parts);
                   2811: 	}
                   2812: 	$name=join('.',@file_parts);
                   2813:     } else {
                   2814: 	$name=join('.',@file_parts);
                   2815:     }
                   2816:     return($name,$version,$ext);
                   2817: }
                   2818: 
1.44      ng       2819: #--------------------------------------------------------------------------------------
                   2820: #
                   2821: #-------------------------- Next few routines handles grading by section or whole class
                   2822: #
                   2823: #--- Javascript to handle grading by section or whole class
1.42      ng       2824: sub viewgrades_js {
                   2825:     my ($request) = shift;
                   2826: 
1.41      ng       2827:     $request->print(<<VIEWJAVASCRIPT);
                   2828: <script type="text/javascript" language="javascript">
1.45      ng       2829:    function writePoint(partid,weight,point) {
1.125     ng       2830: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2831: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2832: 	if (point == "textval") {
1.125     ng       2833: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2834: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2835: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2836: 		var resetbox = false;
                   2837: 		for (var i=0; i<radioButton.length; i++) {
                   2838: 		    if (radioButton[i].checked) {
                   2839: 			textbox.value = i;
                   2840: 			resetbox = true;
                   2841: 		    }
                   2842: 		}
                   2843: 		if (!resetbox) {
                   2844: 		    textbox.value = "";
                   2845: 		}
                   2846: 		return;
                   2847: 	    }
1.109     matthew  2848: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2849: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2850: 				   ") greater than the weight for the part. Accept?");
                   2851: 		if (resp == false) {
                   2852: 		    textbox.value = "";
                   2853: 		    return;
                   2854: 		}
                   2855: 	    }
1.42      ng       2856: 	    for (var i=0; i<radioButton.length; i++) {
                   2857: 		radioButton[i].checked=false;
1.109     matthew  2858: 		if (parseFloat(point) == i) {
1.42      ng       2859: 		    radioButton[i].checked=true;
                   2860: 		}
                   2861: 	    }
1.41      ng       2862: 
1.42      ng       2863: 	} else {
1.125     ng       2864: 	    textbox.value = parseFloat(point);
1.42      ng       2865: 	}
1.41      ng       2866: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2867: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2868: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2869: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2870: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2871: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2872: 	    if (saveval != "correct") {
                   2873: 		scorename.value = point;
1.43      ng       2874: 		if (selname[0].selected != true) {
                   2875: 		    selname[0].selected = true;
                   2876: 		}
1.42      ng       2877: 	    }
                   2878: 	}
1.125     ng       2879: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2880:     }
                   2881: 
                   2882:     function writeRadText(partid,weight) {
1.125     ng       2883: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2884: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2885:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2886: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2887: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2888: 	    for (var i=0; i<radioButton.length; i++) {
                   2889: 		radioButton[i].checked=false;
                   2890: 
                   2891: 	    }
                   2892: 	    textbox.value = "";
                   2893: 
                   2894: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2895: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2896: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2897: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2898: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2899: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2900: 		if ((saveval != "correct") || override) {
1.42      ng       2901: 		    scorename.value = "";
1.125     ng       2902: 		    if (selval[1].selected) {
                   2903: 			selname[1].selected = true;
                   2904: 		    } else {
                   2905: 			selname[2].selected = true;
                   2906: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2907: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2908: 		    }
1.42      ng       2909: 		}
                   2910: 	    }
1.43      ng       2911: 	} else {
                   2912: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2913: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2914: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2915: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2916: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2917: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2918: 		if ((saveval != "correct") || override) {
1.125     ng       2919: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2920: 		    selname[0].selected = true;
                   2921: 		}
                   2922: 	    }
                   2923: 	}	    
1.42      ng       2924:     }
                   2925: 
                   2926:     function changeSelect(partid,user) {
1.125     ng       2927: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2928: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2929: 	var point  = textbox.value;
1.125     ng       2930: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2931: 
1.109     matthew  2932: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2933: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2934: 	    textbox.value = "";
                   2935: 	    return;
                   2936: 	}
1.109     matthew  2937: 	if (parseFloat(point) > parseFloat(weight)) {
                   2938: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2939: 			       ") greater than the weight of the part. Accept?");
                   2940: 	    if (resp == false) {
                   2941: 		textbox.value = "";
                   2942: 		return;
                   2943: 	    }
                   2944: 	}
1.42      ng       2945: 	selval[0].selected = true;
                   2946:     }
                   2947: 
                   2948:     function changeOneScore(partid,user) {
1.125     ng       2949: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2950: 	if (selval[1].selected || selval[2].selected) {
                   2951: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2952: 	    if (selval[2].selected) {
                   2953: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2954: 	    }
1.269     raeburn  2955:         }
1.42      ng       2956:     }
                   2957: 
                   2958:     function resetEntry(numpart) {
                   2959: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2960: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2961: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2962: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2963: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2964: 	    for (var i=0; i<radioButton.length; i++) {
                   2965: 		radioButton[i].checked=false;
                   2966: 
                   2967: 	    }
                   2968: 	    textbox.value = "";
                   2969: 	    selval[0].selected = true;
                   2970: 
                   2971: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2972: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2973: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2974: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2975: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2976: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2977: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2978: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2979: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2980: 		if (saveselval == "excused") {
1.43      ng       2981: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2982: 		} else {
1.43      ng       2983: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2984: 		}
                   2985: 	    }
1.41      ng       2986: 	}
1.42      ng       2987:     }
                   2988: 
1.41      ng       2989: </script>
                   2990: VIEWJAVASCRIPT
1.42      ng       2991: }
                   2992: 
1.44      ng       2993: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2994: sub viewgrades {
                   2995:     my ($request) = shift;
                   2996:     &viewgrades_js($request);
1.41      ng       2997: 
1.324     albertel 2998:     my ($symb) = &get_symb($request);
1.168     albertel 2999:     #need to make sure we have the correct data for later EXT calls, 
                   3000:     #thus invalidate the cache
                   3001:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3002:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3003:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3004:     &Apache::lonnet::clear_EXT_cache_status();
                   3005: 
1.398     albertel 3006:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   3007:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       3008: 
                   3009:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 3010:     $result.=&jscriptNform($symb);
1.41      ng       3011: 
1.44      ng       3012:     #beginning of class grading form
1.442     banghart 3013:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
1.41      ng       3014:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 3015: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3016: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3017: 	&build_section_inputs().
1.257     albertel 3018: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
1.442     banghart 3019: 	'<input type="hidden" name="Status" value="'.$env{'stu_status'}.'" />'."\n".
1.257     albertel 3020: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3021: 
1.126     ng       3022:     my $sectionClass;
1.430     banghart 3023:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3024:     if ($env{'form.section'} eq 'all') {
1.126     ng       3025: 	$sectionClass='Class </h3>';
1.257     albertel 3026:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3027: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3028:     } else {
1.431     banghart 3029: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3030:     }
1.431     banghart 3031:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3032:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3033: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3034:     #radio buttons/text box for assigning points for a section or class.
                   3035:     #handles different parts of a problem
1.375     albertel 3036:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3037:     my %weight = ();
                   3038:     my $ctsparts = 0;
1.41      ng       3039:     $result.='<table border="0">';
1.45      ng       3040:     my %seen = ();
1.375     albertel 3041:     my @part_response_id = &flatten_responseType($responseType);
                   3042:     foreach my $part_response_id (@part_response_id) {
                   3043:     	my ($partid,$respid) = @{ $part_response_id };
                   3044: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3045: 	next if $seen{$partid};
                   3046: 	$seen{$partid}++;
1.375     albertel 3047: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3048: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3049: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3050: 
1.44      ng       3051: 	$result.='<input type="hidden" name="partid_'.
                   3052: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3053: 	$result.='<input type="hidden" name="weight_'.
                   3054: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3055: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3056: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3057: 	$result.='<table border="0"><tr>';  
1.41      ng       3058: 	my $ctr = 0;
1.42      ng       3059: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3060: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3061: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3062: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3063: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3064: 	    $ctr++;
                   3065: 	}
                   3066: 	$result.='</tr></table>';
1.44      ng       3067: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3068: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3069: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3070: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3071: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3072: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3073: 		$weight{$partid}.')"> '.
1.401     albertel 3074: 	    '<option selected="selected"> </option>'.
1.125     ng       3075: 	    '<option>excused</option>'.
1.265     www      3076: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3077:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3078: 	$ctsparts++;
1.41      ng       3079:     }
1.52      albertel 3080:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3081: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3082:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3083: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3084: 
1.44      ng       3085:     #table listing all the students in a section/class
                   3086:     #header of table
1.126     ng       3087:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3088:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3089: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3090: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3091:     my (@parts) = sort(&getpartlist($symb));
                   3092:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3093:     my @partids = ();
1.41      ng       3094:     foreach my $part (@parts) {
                   3095: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3096: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3097: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3098: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3099:         push(@partids, $partid);
1.324     albertel 3100: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3101: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3102: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3103: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3104: 	    next;
1.207     albertel 3105: 	} else {
                   3106: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3107: 	}
1.53      albertel 3108: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3109: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3110:     }
                   3111:     $result.='</tr>';
1.44      ng       3112: 
1.270     albertel 3113:     my %last_resets = 
                   3114: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3115: 
1.41      ng       3116:     #get info for each student
1.44      ng       3117:     #list all the students - with points and grade status
1.257     albertel 3118:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3119:     my $ctr = 0;
1.294     albertel 3120:     foreach (sort 
                   3121: 	     {
                   3122: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3123: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3124: 		 }
                   3125: 		 return $a cmp $b;
                   3126: 	     } (keys(%$fullname))) {
1.126     ng       3127: 	$ctr++;
1.324     albertel 3128: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3129: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3130:     }
                   3131:     $result.='</table></td></tr></table>';
                   3132:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3133:     $result.='<input type="button" value="Save" '.
1.417     albertel 3134: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3135:     if (scalar(%$fullname) eq 0) {
                   3136: 	my $colspan=3+scalar(@parts);
1.433     banghart 3137: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.442     banghart 3138:         my $stu_status = join(' or ',&Apache::loncommon::get_env_multiple('form.Status'));
1.433     banghart 3139: 	$result='<span class="LC_warning">'.
                   3140: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
1.442     banghart 3141: 	        $section_display, $stu_status).
1.433     banghart 3142: 	    '</span>';
1.96      albertel 3143:     }
1.324     albertel 3144:     $result.=&show_grading_menu_form($symb);
1.41      ng       3145:     return $result;
                   3146: }
                   3147: 
1.44      ng       3148: #--- call by previous routine to display each student
1.41      ng       3149: sub viewstudentgrade {
1.324     albertel 3150:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3151:     my ($uname,$udom) = split(/:/,$student);
                   3152:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3153:     my %aggregates = (); 
1.233     albertel 3154:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3155: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3156: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3157: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3158: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3159: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3160:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3161:     foreach my $apart (@$parts) {
                   3162: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3163: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3164:         $result.='<td align="center">';
1.269     raeburn  3165:         my ($aggtries,$totaltries);
                   3166:         unless (exists($aggregates{$part})) {
1.270     albertel 3167: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3168: 
                   3169: 	    $aggtries = $totaltries;
1.269     raeburn  3170:             if ($$last_resets{$part}) {  
1.270     albertel 3171:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3172: 					   $part);
                   3173:             }
1.269     raeburn  3174:             $result.='<input type="hidden" name="'.
                   3175:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3176:             $result.='<input type="hidden" name="'.
                   3177:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3178:             $aggregates{$part} = 1;
                   3179:         }
1.41      ng       3180: 	if ($type eq 'awarded') {
1.320     albertel 3181: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3182: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3183: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3184: 	    $result.='<input type="text" name="'.
1.89      albertel 3185: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3186: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3187: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3188: 	} elsif ($type eq 'solved') {
                   3189: 	    my ($status,$foo)=split(/_/,$score,2);
                   3190: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3191: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3192: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3193: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3194: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3195: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3196: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3197: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3198: 	    $result.='<option>reset status</option>';
1.126     ng       3199: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3200: 	} else {
                   3201: 	    $result.='<input type="hidden" name="'.
                   3202: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3203: 		    "\n";
1.233     albertel 3204: 	    $result.='<input type="text" name="'.
1.122     ng       3205: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3206: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3207: 	}
                   3208:     }
                   3209:     $result.='</tr>';
                   3210:     return $result;
1.38      ng       3211: }
                   3212: 
1.44      ng       3213: #--- change scores for all the students in a section/class
                   3214: #    record does not get update if unchanged
1.38      ng       3215: sub editgrades {
1.41      ng       3216:     my ($request) = @_;
                   3217: 
1.324     albertel 3218:     my $symb=&get_symb($request);
1.433     banghart 3219:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3220:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3221:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3222:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3223: 
1.44      ng       3224:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3225:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3226: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3227: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3228: 
                   3229:     my %scoreptr = (
                   3230: 		    'correct'  =>'correct_by_override',
                   3231: 		    'incorrect'=>'incorrect_by_override',
                   3232: 		    'excused'  =>'excused',
                   3233: 		    'ungraded' =>'ungraded_attempted',
                   3234: 		    'nothing'  => '',
                   3235: 		    );
1.257     albertel 3236:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3237: 
1.44      ng       3238:     my (@partid);
                   3239:     my %weight = ();
1.54      albertel 3240:     my %columns = ();
1.44      ng       3241:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3242: 
1.324     albertel 3243:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3244:     my $header;
1.257     albertel 3245:     while ($ctr < $env{'form.totalparts'}) {
                   3246: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3247: 	push @partid,$partid;
1.257     albertel 3248: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3249: 	$ctr++;
1.54      albertel 3250:     }
1.324     albertel 3251:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3252:     foreach my $partid (@partid) {
                   3253: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3254: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3255: 	$columns{$partid}=2;
                   3256: 	foreach my $stores (@parts) {
                   3257: 	    my ($part,$type) = &split_part_type($stores);
                   3258: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3259: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3260: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3261: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3262: 	    $display =~ s/Number of Attempts/Tries/;
                   3263: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3264: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3265: 	    $columns{$partid}+=2;
                   3266: 	}
                   3267:     }
                   3268:     foreach my $partid (@partid) {
1.324     albertel 3269: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3270: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3271: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3272: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3273: 
1.44      ng       3274:     }
                   3275:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3276:     $result .= $header;
1.44      ng       3277:     $result .= '</tr>'."\n";
1.93      albertel 3278:     my $noupdate;
1.126     ng       3279:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3280:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3281: 	my $line;
1.257     albertel 3282: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3283: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3284: 	my %newrecord;
                   3285: 	my $updateflag = 0;
1.281     albertel 3286: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3287: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3288: 	if (!&canmodify($usec)) {
1.126     ng       3289: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3290: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3291: 	    next;
                   3292: 	}
1.269     raeburn  3293:         my %aggregate = ();
                   3294:         my $aggregateflag = 0;
1.281     albertel 3295: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3296: 	foreach (@partid) {
1.257     albertel 3297: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3298: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3299: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3300: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3301: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3302: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3303: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3304: 	    my $score;
                   3305: 	    if ($partial eq '') {
1.257     albertel 3306: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3307: 	    } elsif ($partial > 0) {
                   3308: 		$score = 'correct_by_override';
                   3309: 	    } elsif ($partial == 0) {
                   3310: 		$score = 'incorrect_by_override';
                   3311: 	    }
1.257     albertel 3312: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3313: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3314: 
1.292     albertel 3315: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3316: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3317: 	    if ($dropMenu eq 'reset status' &&
                   3318: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3319: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3320: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3321: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3322: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3323: 		$updateflag = 1;
1.269     raeburn  3324:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3325:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3326:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3327:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3328:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3329:                     $aggregateflag = 1;
                   3330:                 }
1.139     albertel 3331: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3332: 		$updateflag = 1;
                   3333: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3334: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3335: 		$rec_update++;
1.125     ng       3336: 	    }
                   3337: 
1.93      albertel 3338: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3339: 		'<td align="center">'.$awarded.
                   3340: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3341: 
1.54      albertel 3342: 
                   3343: 	    my $partid=$_;
                   3344: 	    foreach my $stores (@parts) {
                   3345: 		my ($part,$type) = &split_part_type($stores);
                   3346: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3347: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3348: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3349: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3350: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3351: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3352: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3353: 		    $updateflag=1;
                   3354: 		}
1.93      albertel 3355: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3356: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3357: 	    }
1.44      ng       3358: 	}
1.93      albertel 3359: 	$line.='</tr>'."\n";
1.301     albertel 3360: 
                   3361: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3362: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3363: 
1.44      ng       3364: 	if ($updateflag) {
                   3365: 	    $count++;
1.257     albertel 3366: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3367: 				    $udom,$uname);
1.301     albertel 3368: 
                   3369: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3370: 					      $cnum,$udom,$uname)) {
                   3371: 		# need to figure out if should be in queue.
                   3372: 		my %record =  
                   3373: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3374: 					     $udom,$uname);
                   3375: 		my $all_graded = 1;
                   3376: 		my $none_graded = 1;
                   3377: 		foreach my $part (@parts) {
                   3378: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3379: 			$all_graded = 0;
                   3380: 		    } else {
                   3381: 			$none_graded = 0;
                   3382: 		    }
                   3383: 		}
                   3384: 
                   3385: 		if ($all_graded || $none_graded) {
                   3386: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3387: 							   $symb,$cdom,$cnum,
                   3388: 							   $udom,$uname);
                   3389: 		}
                   3390: 	    }
                   3391: 
1.126     ng       3392: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3393: 	    $updateCtr++;
1.93      albertel 3394: 	} else {
1.126     ng       3395: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3396: 	    $noupdateCtr++;
1.44      ng       3397: 	}
1.269     raeburn  3398:         if ($aggregateflag) {
                   3399:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3400: 				  $cdom,$cnum);
1.269     raeburn  3401:         }
1.93      albertel 3402:     }
                   3403:     if ($noupdate) {
1.126     ng       3404: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3405: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3406: 	$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       3407:     }
1.72      ng       3408:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3409: 	&show_grading_menu_form ($symb);
1.125     ng       3410:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3411: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3412: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3413:     return $title.$msg.$result;
1.5       albertel 3414: }
1.54      albertel 3415: 
                   3416: sub split_part_type {
                   3417:     my ($partstr) = @_;
                   3418:     my ($temp,@allparts)=split(/_/,$partstr);
                   3419:     my $type=pop(@allparts);
1.439     albertel 3420:     my $part=join('_',@allparts);
1.54      albertel 3421:     return ($part,$type);
                   3422: }
                   3423: 
1.44      ng       3424: #------------- end of section for handling grading by section/class ---------
                   3425: #
                   3426: #----------------------------------------------------------------------------
                   3427: 
1.5       albertel 3428: 
1.44      ng       3429: #----------------------------------------------------------------------------
                   3430: #
                   3431: #-------------------------- Next few routines handles grading by csv upload
                   3432: #
                   3433: #--- Javascript to handle csv upload
1.27      albertel 3434: sub csvupload_javascript_reverse_associate {
1.246     albertel 3435:     my $error1=&mt('You need to specify the username or ID');
                   3436:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3437:   return(<<ENDPICK);
                   3438:   function verify(vf) {
                   3439:     var foundsomething=0;
                   3440:     var founduname=0;
1.243     albertel 3441:     var foundID=0;
1.27      albertel 3442:     for (i=0;i<=vf.nfields.value;i++) {
                   3443:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3444:       if (i==0 && tw!=0) { foundID=1; }
                   3445:       if (i==1 && tw!=0) { founduname=1; }
                   3446:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3447:     }
1.246     albertel 3448:     if (founduname==0 && foundID==0) {
                   3449: 	alert('$error1');
                   3450: 	return;
1.27      albertel 3451:     }
                   3452:     if (foundsomething==0) {
1.246     albertel 3453: 	alert('$error2');
                   3454: 	return;
1.27      albertel 3455:     }
                   3456:     vf.submit();
                   3457:   }
                   3458:   function flip(vf,tf) {
                   3459:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3460:     var i;
                   3461:     for (i=0;i<=vf.nfields.value;i++) {
                   3462:       //can not pick the same destination field for both name and domain
                   3463:       if (((i ==0)||(i ==1)) && 
                   3464:           ((tf==0)||(tf==1)) && 
                   3465:           (i!=tf) &&
                   3466:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3467:         eval('vf.f'+i+'.selectedIndex=0;')
                   3468:       }
                   3469:     }
                   3470:   }
                   3471: ENDPICK
                   3472: }
                   3473: 
                   3474: sub csvupload_javascript_forward_associate {
1.246     albertel 3475:     my $error1=&mt('You need to specify the username or ID');
                   3476:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3477:   return(<<ENDPICK);
                   3478:   function verify(vf) {
                   3479:     var foundsomething=0;
                   3480:     var founduname=0;
1.243     albertel 3481:     var foundID=0;
1.27      albertel 3482:     for (i=0;i<=vf.nfields.value;i++) {
                   3483:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3484:       if (tw==1) { foundID=1; }
                   3485:       if (tw==2) { founduname=1; }
                   3486:       if (tw>3) { foundsomething=1; }
1.27      albertel 3487:     }
1.246     albertel 3488:     if (founduname==0 && foundID==0) {
                   3489: 	alert('$error1');
                   3490: 	return;
1.27      albertel 3491:     }
                   3492:     if (foundsomething==0) {
1.246     albertel 3493: 	alert('$error2');
                   3494: 	return;
1.27      albertel 3495:     }
                   3496:     vf.submit();
                   3497:   }
                   3498:   function flip(vf,tf) {
                   3499:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3500:     var i;
                   3501:     //can not pick the same destination field twice
                   3502:     for (i=0;i<=vf.nfields.value;i++) {
                   3503:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3504:         eval('vf.f'+i+'.selectedIndex=0;')
                   3505:       }
                   3506:     }
                   3507:   }
                   3508: ENDPICK
                   3509: }
                   3510: 
1.26      albertel 3511: sub csvuploadmap_header {
1.324     albertel 3512:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3513:     my $javascript;
1.257     albertel 3514:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3515: 	$javascript=&csvupload_javascript_reverse_associate();
                   3516:     } else {
                   3517: 	$javascript=&csvupload_javascript_forward_associate();
                   3518:     }
1.45      ng       3519: 
1.324     albertel 3520:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3521:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3522:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3523:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3524:     $request->print(<<ENDPICK);
1.26      albertel 3525: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3526: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3527: $result
1.326     albertel 3528: <hr />
1.26      albertel 3529: <h3>Identify fields</h3>
                   3530: Total number of records found in file: $distotal <hr />
                   3531: Enter as many fields as you can. The system will inform you and bring you back
                   3532: to this page if the data selected is insufficient to run your class.<hr />
                   3533: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3534: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3535: <input type="hidden" name="associate"  value="" />
                   3536: <input type="hidden" name="phase"      value="three" />
                   3537: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3538: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3539: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3540: <input type="hidden" name="upfile_associate" 
1.257     albertel 3541:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3542: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3543: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3544: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3545: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3546: <hr />
                   3547: <script type="text/javascript" language="Javascript">
                   3548: $javascript
                   3549: </script>
                   3550: ENDPICK
1.118     ng       3551:     return '';
1.26      albertel 3552: 
                   3553: }
                   3554: 
                   3555: sub csvupload_fields {
1.324     albertel 3556:     my ($symb) = @_;
                   3557:     my (@parts) = &getpartlist($symb);
1.243     albertel 3558:     my @fields=(['ID','Student ID'],
                   3559: 		['username','Student Username'],
                   3560: 		['domain','Student Domain']);
1.324     albertel 3561:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3562:     foreach my $part (sort(@parts)) {
                   3563: 	my @datum;
                   3564: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3565: 	my $name=$part;
                   3566: 	if  (!$display) { $display = $name; }
                   3567: 	@datum=($name,$display);
1.244     albertel 3568: 	if ($name=~/^stores_(.*)_awarded/) {
                   3569: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3570: 	}
1.41      ng       3571: 	push(@fields,\@datum);
                   3572:     }
                   3573:     return (@fields);
1.26      albertel 3574: }
                   3575: 
                   3576: sub csvuploadmap_footer {
1.41      ng       3577:     my ($request,$i,$keyfields) =@_;
                   3578:     $request->print(<<ENDPICK);
1.26      albertel 3579: </table>
                   3580: <input type="hidden" name="nfields" value="$i" />
                   3581: <input type="hidden" name="keyfields" value="$keyfields" />
                   3582: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3583: </form>
                   3584: ENDPICK
                   3585: }
                   3586: 
1.283     albertel 3587: sub checkforfile_js {
1.86      ng       3588:     my $result =<<CSVFORMJS;
                   3589: <script type="text/javascript" language="javascript">
                   3590:     function checkUpload(formname) {
                   3591: 	if (formname.upfile.value == "") {
                   3592: 	    alert("Please use the browse button to select a file from your local directory.");
                   3593: 	    return false;
                   3594: 	}
                   3595: 	formname.submit();
                   3596:     }
                   3597:     </script>
                   3598: CSVFORMJS
1.283     albertel 3599:     return $result;
                   3600: }
                   3601: 
                   3602: sub upcsvScores_form {
                   3603:     my ($request) = shift;
1.324     albertel 3604:     my ($symb)=&get_symb($request);
1.283     albertel 3605:     if (!$symb) {return '';}
                   3606:     my $result=&checkforfile_js();
1.257     albertel 3607:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3608:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3609:     $result.=$table;
1.326     albertel 3610:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3611:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3612:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3613: 	'.</b></td></tr>'."\n";
                   3614:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3615:     my $upload=&mt("Upload Scores");
1.86      ng       3616:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3617:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3618:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3619:     $result.=<<ENDUPFORM;
1.106     albertel 3620: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3621: <input type="hidden" name="symb" value="$symb" />
                   3622: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3623: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3624: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3625: $upfile_select
1.370     www      3626: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3627: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3628: </form>
                   3629: ENDUPFORM
1.370     www      3630:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3631:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3632:     .'</td></tr></table>'."\n";
1.86      ng       3633:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3634:     $result.=&show_grading_menu_form($symb);
1.86      ng       3635:     return $result;
                   3636: }
                   3637: 
                   3638: 
1.26      albertel 3639: sub csvuploadmap {
1.41      ng       3640:     my ($request)= @_;
1.324     albertel 3641:     my ($symb)=&get_symb($request);
1.41      ng       3642:     if (!$symb) {return '';}
1.72      ng       3643: 
1.41      ng       3644:     my $datatoken;
1.257     albertel 3645:     if (!$env{'form.datatoken'}) {
1.41      ng       3646: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3647:     } else {
1.257     albertel 3648: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3649: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3650:     }
1.41      ng       3651:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3652:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3653:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3654:     my ($i,$keyfields);
                   3655:     if (@records) {
1.324     albertel 3656: 	my @fields=&csvupload_fields($symb);
1.45      ng       3657: 
1.257     albertel 3658: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3659: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3660: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3661: 							  \@fields);
                   3662: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3663: 	    chop($keyfields);
                   3664: 	} else {
                   3665: 	    unshift(@fields,['none','']);
                   3666: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3667: 							    \@fields);
1.311     banghart 3668:             foreach my $rec (@records) {
                   3669:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3670:                 if (%temp) {
                   3671:                     $keyfields=join(',',sort(keys(%temp)));
                   3672:                     last;
                   3673:                 }
                   3674:             }
1.41      ng       3675: 	}
                   3676:     }
                   3677:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3678:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3679: 
1.41      ng       3680:     return '';
1.27      albertel 3681: }
                   3682: 
1.246     albertel 3683: sub csvuploadoptions {
1.41      ng       3684:     my ($request)= @_;
1.324     albertel 3685:     my ($symb)=&get_symb($request);
1.257     albertel 3686:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3687:     my $ignore=&mt('Ignore First Line');
                   3688:     $request->print(<<ENDPICK);
                   3689: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3690: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3691: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3692: <!--
1.246     albertel 3693: <p>
                   3694: <label>
                   3695:    <input type="checkbox" name="show_full_results" />
                   3696:    Show a table of all changes
                   3697: </label>
                   3698: </p>
1.302     albertel 3699: -->
1.246     albertel 3700: <p>
                   3701: <label>
                   3702:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3703:    Overwrite any existing score
                   3704: </label>
                   3705: </p>
                   3706: ENDPICK
                   3707:     my %fields=&get_fields();
                   3708:     if (!defined($fields{'domain'})) {
1.257     albertel 3709: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3710: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3711:     }
1.257     albertel 3712:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3713: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3714: 	my $cleankey=$1;
                   3715: 	if ($cleankey eq 'command') { next; }
                   3716: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3717: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3718:     }
                   3719:     # FIXME do a check for any duplicated user ids...
                   3720:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3721:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3722: <hr /></form>'."\n");
1.324     albertel 3723:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3724:     return '';
                   3725: }
                   3726: 
                   3727: sub get_fields {
                   3728:     my %fields;
1.257     albertel 3729:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3730:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3731: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3732: 	    if ($env{'form.f'.$i} ne 'none') {
                   3733: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3734: 	    }
                   3735: 	} else {
1.257     albertel 3736: 	    if ($env{'form.f'.$i} ne 'none') {
                   3737: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3738: 	    }
                   3739: 	}
1.27      albertel 3740:     }
1.246     albertel 3741:     return %fields;
                   3742: }
                   3743: 
                   3744: sub csvuploadassign {
                   3745:     my ($request)= @_;
1.324     albertel 3746:     my ($symb)=&get_symb($request);
1.246     albertel 3747:     if (!$symb) {return '';}
1.345     bowersj2 3748:     my $error_msg = '';
1.246     albertel 3749:     &Apache::loncommon::load_tmp_file($request);
                   3750:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3751:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3752:     my %fields=&get_fields();
1.41      ng       3753:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3754:     my $courseid=$env{'request.course.id'};
1.97      albertel 3755:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3756:     my @notallowed;
1.41      ng       3757:     my @skipped;
                   3758:     my $countdone=0;
                   3759:     foreach my $grade (@gradedata) {
                   3760: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3761: 	my $domain;
                   3762: 	if ($entries{$fields{'domain'}}) {
                   3763: 	    $domain=$entries{$fields{'domain'}};
                   3764: 	} else {
1.257     albertel 3765: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3766: 	}
1.243     albertel 3767: 	$domain=~s/\s//g;
1.41      ng       3768: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3769: 	$username=~s/\s//g;
1.243     albertel 3770: 	if (!$username) {
                   3771: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3772: 	    $id=~s/\s//g;
1.243     albertel 3773: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3774: 	    $username=$ids{$id};
                   3775: 	}
1.41      ng       3776: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3777: 	    my $id=$entries{$fields{'ID'}};
                   3778: 	    $id=~s/\s//g;
                   3779: 	    if ($id) {
                   3780: 		push(@skipped,"$id:$domain");
                   3781: 	    } else {
                   3782: 		push(@skipped,"$username:$domain");
                   3783: 	    }
1.41      ng       3784: 	    next;
                   3785: 	}
1.108     albertel 3786: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3787: 	if (!&canmodify($usec)) {
                   3788: 	    push(@notallowed,"$username:$domain");
                   3789: 	    next;
                   3790: 	}
1.244     albertel 3791: 	my %points;
1.41      ng       3792: 	my %grades;
                   3793: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3794: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3795: 		$dest eq 'domain') { next; }
                   3796: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3797: 	    if ($dest=~/stores_(.*)_points/) {
                   3798: 		my $part=$1;
                   3799: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3800: 					      $symb,$domain,$username);
1.345     bowersj2 3801:                 if ($wgt) {
                   3802:                     $entries{$fields{$dest}}=~s/\s//g;
                   3803:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3804:                     my $award='correct_by_override';
                   3805:                     $grades{"resource.$part.awarded"}=$pcr;
                   3806:                     $grades{"resource.$part.solved"}=$award;
                   3807:                     $points{$part}=1;
                   3808:                 } else {
                   3809:                     $error_msg = "<br />" .
                   3810:                         &mt("Some point values were assigned"
                   3811:                             ." for problems with a weight "
                   3812:                             ."of zero. These values were "
                   3813:                             ."ignored.");
                   3814:                 }
1.244     albertel 3815: 	    } else {
                   3816: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3817: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3818: 		my $store_key=$dest;
                   3819: 		$store_key=~s/^stores/resource/;
                   3820: 		$store_key=~s/_/\./g;
                   3821: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3822: 	    }
1.41      ng       3823: 	}
1.398     albertel 3824: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3825: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3826: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3827: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3828: 					   $env{'request.course.id'},
                   3829: 					   $domain,$username);
                   3830: 	if ($result eq 'ok') {
                   3831: 	    $request->print('.');
                   3832: 	} else {
                   3833: 	    $request->print("<p>
1.398     albertel 3834:                               <span class=\"LC_error\">
                   3835:                                  Failed to save student $username:$domain.
                   3836:                                  Message when trying to save was ($result)
                   3837:                               </span>
1.302     albertel 3838:                              </p>" );
                   3839: 	}
1.41      ng       3840: 	$request->rflush();
                   3841: 	$countdone++;
                   3842:     }
1.398     albertel 3843:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3844:     if (@skipped) {
1.398     albertel 3845: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3846: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3847:     }
                   3848:     if (@notallowed) {
1.398     albertel 3849: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3850: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3851:     }
1.106     albertel 3852:     $request->print("<br />\n");
1.324     albertel 3853:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3854:     return $error_msg;
1.26      albertel 3855: }
1.44      ng       3856: #------------- end of section for handling csv file upload ---------
                   3857: #
                   3858: #-------------------------------------------------------------------
                   3859: #
1.122     ng       3860: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3861: #
                   3862: #--- Select a page/sequence and a student to grade
1.68      ng       3863: sub pickStudentPage {
                   3864:     my ($request) = shift;
                   3865: 
                   3866:     $request->print(<<LISTJAVASCRIPT);
                   3867: <script type="text/javascript" language="javascript">
                   3868: 
                   3869: function checkPickOne(formname) {
1.76      ng       3870:     if (radioSelection(formname.student) == null) {
1.68      ng       3871: 	alert("Please select the student you wish to grade.");
                   3872: 	return;
                   3873:     }
1.125     ng       3874:     ptr = pullDownSelection(formname.selectpage);
                   3875:     formname.page.value = formname["page"+ptr].value;
                   3876:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3877:     formname.submit();
                   3878: }
                   3879: 
                   3880: </script>
                   3881: LISTJAVASCRIPT
1.118     ng       3882:     &commonJSfunctions($request);
1.324     albertel 3883:     my ($symb) = &get_symb($request);
1.257     albertel 3884:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3885:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3886:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3887: 
1.398     albertel 3888:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3889: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3890: 
1.80      ng       3891:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3892:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3893:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3894:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3895: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3896: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3897:     my $ctr=0;
1.68      ng       3898:     foreach (@$titles) {
                   3899: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3900: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3901: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3902: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3903: 	$ctr++;
1.68      ng       3904:     }
1.326     albertel 3905:     $result.= '</select>'."<br />\n";
1.70      ng       3906:     $ctr=0;
                   3907:     foreach (@$titles) {
                   3908: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3909: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3910: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3911: 	$ctr++;
                   3912:     }
1.72      ng       3913:     $result.='<input type="hidden" name="page" />'."\n".
                   3914: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3915: 
1.401     albertel 3916:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3917: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3918: 
1.71      ng       3919:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3920: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3921: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3922: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 3923:     
                   3924:     $result.=&build_section_inputs();
1.442     banghart 3925:     my $stu_status = join(':',&Apache::loncommon::get_env_multiple('form.Status'));
                   3926:     $result.='<input type="hidden" name="Status"  value="'.$stu_status.'" />'."\n".
1.72      ng       3927: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3928: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3929: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3930: 
1.382     albertel 3931:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3932: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3933: 
1.80      ng       3934:     $result.='&nbsp;<input type="button" '.
1.126     ng       3935: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3936: 
1.68      ng       3937:     $request->print($result);
                   3938: 
1.326     albertel 3939:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3940: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3941: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3942: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3943: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3944: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3945: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3946:  
1.76      ng       3947:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3948:     my $ptr = 1;
1.294     albertel 3949:     foreach my $student (sort 
                   3950: 			 {
                   3951: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3952: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3953: 			     }
                   3954: 			     return $a cmp $b;
                   3955: 			 } (keys(%$fullname))) {
1.68      ng       3956: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3957: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3958: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3959: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3960: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3961: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3962: 	$ptr++;
                   3963:     }
1.381     albertel 3964:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3965:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3966:     $studentTable.='<input type="button" '.
                   3967: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3968: 
1.324     albertel 3969:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3970:     $request->print($studentTable);
                   3971: 
                   3972:     return '';
                   3973: }
                   3974: 
                   3975: sub getSymbMap {
1.132     bowersj2 3976:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3977: 
                   3978:     my %symbx = ();
                   3979:     my @titles = ();
1.117     bowersj2 3980:     my $minder = 0;
                   3981: 
                   3982:     # Gather every sequence that has problems.
1.240     albertel 3983:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3984: 					       1,0,1);
1.117     bowersj2 3985:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3986: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3987: 	    my $title = $minder.'.'.
                   3988: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3989: 	    push(@titles, $title); # minder in case two titles are identical
                   3990: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3991: 	    $minder++;
1.241     albertel 3992: 	}
1.68      ng       3993:     }
                   3994:     return \@titles,\%symbx;
                   3995: }
                   3996: 
1.72      ng       3997: #
                   3998: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3999: sub displayPage {
                   4000:     my ($request) = shift;
                   4001: 
1.324     albertel 4002:     my ($symb) = &get_symb($request);
1.257     albertel 4003:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4004:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4005:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4006:     my $pageTitle = $env{'form.page'};
1.103     albertel 4007:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4008:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4009:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 4010: 
                   4011:     #need to make sure we have the correct data for later EXT calls, 
                   4012:     #thus invalidate the cache
                   4013:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 4014:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   4015:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 4016:     &Apache::lonnet::clear_EXT_cache_status();
                   4017: 
1.103     albertel 4018:     if (!&canview($usec)) {
1.398     albertel 4019: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4020: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4021: 	return;
                   4022:     }
1.398     albertel 4023:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4024:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4025: 	'</h3>'."\n";
1.382     albertel 4026:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4027: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4028:     } else {
                   4029: 	delete($env{'form.CODE'});
                   4030:     }
1.71      ng       4031:     &sub_page_js($request);
                   4032:     $request->print($result);
                   4033: 
1.132     bowersj2 4034:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4035:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4036:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4037:     if (!$map) {
1.398     albertel 4038: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4039: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4040: 	return; 
                   4041:     }
1.68      ng       4042:     my $iterator = $navmap->getIterator($map->map_start(),
                   4043: 					$map->map_finish());
                   4044: 
1.71      ng       4045:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4046: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4047: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4048: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4049: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4050: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4051: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4052: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4053: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4054: 
1.382     albertel 4055:     if (defined($env{'form.CODE'})) {
                   4056: 	$studentTable.=
                   4057: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4058:     }
1.381     albertel 4059:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4060: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4061: 	'/check.gif" height="16" border="0" />';
                   4062: 
1.118     ng       4063:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4064: 	' symbol.'."\n".
1.71      ng       4065: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4066: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4067: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4068: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4069: 
1.329     albertel 4070:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4071:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4072:     $iterator->next(); # skip the first BEGIN_MAP
                   4073:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4074:     while ($depth > 0) {
1.68      ng       4075:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4076:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4077: 
1.385     albertel 4078:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4079: 	    my $parts = $curRes->parts();
1.68      ng       4080:             my $title = $curRes->compTitle();
1.71      ng       4081: 	    my $symbx = $curRes->symb();
1.196     albertel 4082: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4083: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4084: 	    $studentTable.='<td valign="top">';
1.382     albertel 4085: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4086: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4087: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4088: 					     undef,'both',\%form);
1.71      ng       4089: 	    } else {
1.382     albertel 4090: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4091: 		$companswer =~ s|<form(.*?)>||g;
                   4092: 		$companswer =~ s|</form>||g;
1.71      ng       4093: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4094: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4095: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4096: #		}
1.116     ng       4097: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4098: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4099: 	    }
                   4100: 
1.257     albertel 4101: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4102: 
1.257     albertel 4103: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4104: 		if ($record{'version'} eq '') {
1.398     albertel 4105: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4106: 		} else {
1.116     ng       4107: 		    my %responseType = ();
                   4108: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4109: 			my @responseIds =$curRes->responseIds($partid);
                   4110: 			my @responseType =$curRes->responseType($partid);
                   4111: 			my %responseIds;
                   4112: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4113: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4114: 			}
                   4115: 			$responseType{$partid} = \%responseIds;
1.116     ng       4116: 		    }
1.148     albertel 4117: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4118: 
1.71      ng       4119: 		}
1.257     albertel 4120: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4121: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4122: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4123: 									$env{'request.course.id'},
1.71      ng       4124: 									'','.submission');
                   4125:  
                   4126: 	    }
1.103     albertel 4127: 	    if (&canmodify($usec)) {
                   4128: 		foreach my $partid (@{$parts}) {
                   4129: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4130: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4131: 		    $question++;
                   4132: 		}
1.196     albertel 4133: 		$prob++;
1.71      ng       4134: 	    }
                   4135: 	    $studentTable.='</td></tr>';
1.68      ng       4136: 
1.103     albertel 4137: 	}
1.68      ng       4138:         $curRes = $iterator->next();
                   4139:     }
                   4140: 
1.381     albertel 4141:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4142: 	'<input type="button" value="Save" '.
1.381     albertel 4143: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4144: 	'</form>'."\n";
1.324     albertel 4145:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4146:     $request->print($studentTable);
                   4147: 
                   4148:     return '';
1.119     ng       4149: }
                   4150: 
                   4151: sub displaySubByDates {
1.148     albertel 4152:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4153:     my $isCODE=0;
1.335     albertel 4154:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4155:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4156:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4157: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4158: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4159: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4160: 	'<td><b>Submission</b></td>'.
                   4161: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4162:     my ($version);
                   4163:     my %mark;
1.148     albertel 4164:     my %orders;
1.119     ng       4165:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4166:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4167: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4168:     }
1.335     albertel 4169: 
                   4170:     my $interaction;
1.119     ng       4171:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4172: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4173: 	if (exists($$record{$version.':resource.0.version'})) {
                   4174: 	    $interaction = $$record{$version.':resource.0.version'};
                   4175: 	}
                   4176: 
                   4177: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4178: 		             : "$version:resource");
                   4179: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4180: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4181: 	if ($isCODE) {
                   4182: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4183: 	}
1.119     ng       4184: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4185: 	my @displaySub = ();
                   4186: 	foreach my $partid (@{$parts}) {
1.335     albertel 4187: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4188: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4189: 	    
                   4190: 
1.122     ng       4191: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4192: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4193: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4194: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4195: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4196: 
                   4197: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4198: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4199: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4200: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4201: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4202: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4203: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4204: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4205: 		    } else {
                   4206: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4207: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4208: 		    }
1.335     albertel 4209: 		    my $responseType=($isTask ? 'Task'
                   4210:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4211: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4212: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4213: 			$orders{$partid}->{$responseId}=
                   4214: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4215: 		    }
1.147     albertel 4216: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4217: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4218: 		}
                   4219: 	    }
1.335     albertel 4220: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4221: 		$displaySub[1].='Checked in by '.
                   4222: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4223: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4224: 		    '<br />';
                   4225: 	    }
                   4226: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4227: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4228: 		    lc($$record{"$where.$partid.award"}).' '.
                   4229: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4230: 		    '<br />';
                   4231: 	    }
1.335     albertel 4232: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4233: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4234: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4235: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4236: 		$displaySub[2].=
                   4237: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4238: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4239: 	    }
                   4240: 	}
                   4241: 	# needed because old essay regrader has not parts info
                   4242: 	if (exists $$record{"$version:resource.regrader"}) {
                   4243: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4244: 	}
                   4245: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4246: 	if ($displaySub[2]) {
                   4247: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4248: 	}
1.382     albertel 4249: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4250:     
1.119     ng       4251:     }
                   4252:     $studentTable.='</table></td></tr></table>';
                   4253:     return $studentTable;
1.71      ng       4254: }
                   4255: 
                   4256: sub updateGradeByPage {
                   4257:     my ($request) = shift;
                   4258: 
1.257     albertel 4259:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4260:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4261:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4262:     my $pageTitle = $env{'form.page'};
1.103     albertel 4263:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4264:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4265:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4266:     if (!&canmodify($usec)) {
1.398     albertel 4267: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4268: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4269: 	return;
                   4270:     }
1.398     albertel 4271:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4272:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4273: 	'</h3>'."\n";
1.70      ng       4274: 
1.68      ng       4275:     $request->print($result);
                   4276: 
1.132     bowersj2 4277:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4278:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4279:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4280:     if (!$map) {
1.398     albertel 4281: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4282: 	my ($symb)=&get_symb($request);
                   4283: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4284: 	return; 
                   4285:     }
1.71      ng       4286:     my $iterator = $navmap->getIterator($map->map_start(),
                   4287: 					$map->map_finish());
1.70      ng       4288: 
1.71      ng       4289:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4290: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4291: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4292: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4293: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4294: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4295: 
                   4296:     $iterator->next(); # skip the first BEGIN_MAP
                   4297:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4298:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4299:     while ($depth > 0) {
1.71      ng       4300:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4301:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4302: 
1.385     albertel 4303:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4304: 	    my $parts = $curRes->parts();
1.71      ng       4305:             my $title = $curRes->compTitle();
                   4306: 	    my $symbx = $curRes->symb();
1.196     albertel 4307: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4308: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4309: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4310: 
                   4311: 	    my %newrecord=();
                   4312: 	    my @displayPts=();
1.269     raeburn  4313:             my %aggregate = ();
                   4314:             my $aggregateflag = 0;
1.71      ng       4315: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4316: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4317: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4318: 
1.257     albertel 4319: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4320: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4321: 		my $partial = $newpts/$wgt;
                   4322: 		my $score;
                   4323: 		if ($partial > 0) {
                   4324: 		    $score = 'correct_by_override';
1.125     ng       4325: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4326: 		    $score = 'incorrect_by_override';
                   4327: 		}
1.257     albertel 4328: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4329: 		if ($dropMenu eq 'excused') {
1.71      ng       4330: 		    $partial = '';
                   4331: 		    $score = 'excused';
1.125     ng       4332: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4333: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4334: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4335: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4336: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4337: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4338: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4339: 		    $changeflag++;
                   4340: 		    $newpts = '';
1.269     raeburn  4341:                     
                   4342:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4343:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4344:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4345:                     if ($aggtries > 0) {
                   4346:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4347:                         $aggregateflag = 1;
                   4348:                     }
1.71      ng       4349: 		}
1.324     albertel 4350: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4351: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4352: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4353: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4354: 		    '&nbsp;<br />';
1.207     albertel 4355: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4356: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4357: 		    '&nbsp;<br />';
1.71      ng       4358: 		$question++;
1.380     albertel 4359: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4360: 
1.71      ng       4361: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4362: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4363: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4364: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4365: 
                   4366: 		$changeflag++;
                   4367: 	    }
                   4368: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4369: 		my %record = 
                   4370: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4371: 					     $udom,$uname);
                   4372: 
                   4373: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4374: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4375: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4376: 		    $newrecord{'resource.CODE'} = '';
                   4377: 		}
1.257     albertel 4378: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4379: 					$udom,$uname);
1.382     albertel 4380: 		%record = &Apache::lonnet::restore($symbx,
                   4381: 						   $env{'request.course.id'},
                   4382: 						   $udom,$uname);
1.380     albertel 4383: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4384: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4385: 	    }
1.380     albertel 4386: 	    
1.269     raeburn  4387:             if ($aggregateflag) {
                   4388:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4389:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4390:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4391:             }
1.125     ng       4392: 
1.71      ng       4393: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4394: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4395: 		'</tr>';
1.68      ng       4396: 
1.196     albertel 4397: 	    $prob++;
1.68      ng       4398: 	}
1.71      ng       4399:         $curRes = $iterator->next();
1.68      ng       4400:     }
1.98      albertel 4401: 
1.71      ng       4402:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4403:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4404:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4405: 		  'The scores were changed for '.
                   4406: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4407:     $request->print($grademsg.$studentTable);
1.68      ng       4408: 
1.70      ng       4409:     return '';
                   4410: }
                   4411: 
1.72      ng       4412: #-------- end of section for handling grading by page/sequence ---------
                   4413: #
                   4414: #-------------------------------------------------------------------
                   4415: 
1.75      albertel 4416: #--------------------Scantron Grading-----------------------------------
                   4417: #
                   4418: #------ start of section for handling grading by page/sequence ---------
                   4419: 
1.423     albertel 4420: =pod
                   4421: 
                   4422: =head1 Bubble sheet grading routines
                   4423: 
1.424     albertel 4424:   For this documentation:
                   4425: 
                   4426:    'scanline' refers to the full line of characters
                   4427:    from the file that we are parsing that represents one entire sheet
                   4428: 
                   4429:    'bubble line' refers to the data
                   4430:    representing the line of bubbles that are on the physical bubble sheet
                   4431: 
                   4432: 
                   4433: The overall process is that a scanned in bubble sheet data is uploaded
                   4434: into a course. When a user wants to grade, they select a
                   4435: sequence/folder of resources, a file of bubble sheet info, and pick
                   4436: one of the predefined configurations for what each scanline looks
                   4437: like.
                   4438: 
                   4439: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4440: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4441: because too light bubbling), 'double bubble' (each bubble line should
                   4442: have no more that one letter picked), invalid or duplicated CODE,
                   4443: invalid student ID
                   4444: 
                   4445: If the CODE option is used that determines the randomization of the
                   4446: homework problems, either way the student ID is looked up into a
                   4447: username:domain.
                   4448: 
                   4449: During the validation phase the instructor can choose to skip scanlines. 
                   4450: 
1.435     foxr     4451: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4452: 
                   4453:   scantron_original_filename (unmodified original file)
                   4454:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4455:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4456: 
                   4457: Also there is a separate hash nohist_scantrondata that contains extra
                   4458: correction information that isn't representable in the bubble sheet
                   4459: file (see &scantron_getfile() for more information)
                   4460: 
                   4461: After all scanlines are either valid, marked as valid or skipped, then
                   4462: foreach line foreach problem in the picked sequence, an ssi request is
                   4463: made that simulates a user submitting their selected letter(s) against
                   4464: the homework problem.
1.423     albertel 4465: 
                   4466: =over 4
                   4467: 
                   4468: =cut
                   4469: 
                   4470: 
                   4471: =pod 
                   4472: 
                   4473: =item defaultFormData
                   4474: 
                   4475:   Returns html hidden inputs used to hold context/default values.
                   4476: 
                   4477:  Arguments:
                   4478:   $symb - $symb of the current resource 
                   4479: 
                   4480: =cut
1.422     foxr     4481: 
1.81      albertel 4482: sub defaultFormData {
1.324     albertel 4483:     my ($symb)=@_;
1.81      albertel 4484:     return '
1.418     albertel 4485:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4486:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4487:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4488: }
                   4489: 
1.423     albertel 4490: =pod 
                   4491: 
                   4492: =item getSequenceDropDown
                   4493: 
                   4494:    Return html dropdown of possible sequences to grade
                   4495:  
                   4496:  Arguments:
                   4497:    $symb - $symb of the current resource 
                   4498: 
                   4499: =cut
1.422     foxr     4500: 
1.75      albertel 4501: sub getSequenceDropDown {
1.423     albertel 4502:     my ($symb)=@_;
1.75      albertel 4503:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4504:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4505:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4506:     my $ctr=0;
                   4507:     foreach (@$titles) {
                   4508: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4509: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4510: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4511: 	    '>'.$showtitle.'</option>'."\n";
                   4512: 	$ctr++;
                   4513:     }
                   4514:     $result.= '</select>';
                   4515:     return $result;
                   4516: }
                   4517: 
1.423     albertel 4518: 
                   4519: =pod 
                   4520: 
                   4521: =item scantron_filenames
                   4522: 
                   4523:    Returns a list of the scantron files in the current course 
                   4524: 
                   4525: =cut
1.422     foxr     4526: 
1.202     albertel 4527: sub scantron_filenames {
1.257     albertel 4528:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4529:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4530:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4531: 				    &propath($cdom,$cname));
1.202     albertel 4532:     my @possiblenames;
1.201     albertel 4533:     foreach my $filename (sort(@files)) {
1.157     albertel 4534: 	($filename)=split(/&/,$filename);
                   4535: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4536: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4537: 	push(@possiblenames,$filename);
                   4538:     }
                   4539:     return @possiblenames;
                   4540: }
                   4541: 
1.423     albertel 4542: =pod 
                   4543: 
                   4544: =item scantron_uploads
                   4545: 
                   4546:    Returns  html drop-down list of scantron files in current course.
                   4547: 
                   4548:  Arguments:
                   4549:    $file2grade - filename to set as selected in the dropdown
                   4550: 
                   4551: =cut
1.422     foxr     4552: 
1.202     albertel 4553: sub scantron_uploads {
1.209     ng       4554:     my ($file2grade) = @_;
1.202     albertel 4555:     my $result=	'<select name="scantron_selectfile">';
                   4556:     $result.="<option></option>";
                   4557:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4558: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4559:     }
                   4560:     $result.="</select>";
                   4561:     return $result;
                   4562: }
                   4563: 
1.423     albertel 4564: =pod 
                   4565: 
                   4566: =item scantron_scantab
                   4567: 
                   4568:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4569:   file.
                   4570: 
                   4571: =cut
1.422     foxr     4572: 
1.82      albertel 4573: sub scantron_scantab {
                   4574:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4575:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4576:     $result.='<option></option>'."\n";
1.82      albertel 4577:     foreach my $line (<$fh>) {
                   4578: 	my ($name,$descrip)=split(/:/,$line);
                   4579: 	if ($name =~ /^\#/) { next; }
                   4580: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4581:     }
                   4582:     $result.='</select>'."\n";
                   4583: 
                   4584:     return $result;
                   4585: }
                   4586: 
1.423     albertel 4587: =pod 
                   4588: 
                   4589: =item scantron_CODElist
                   4590: 
                   4591:   Returns html drop down of the saved CODE lists from current course,
                   4592:   generated from earlier printings.
                   4593: 
                   4594: =cut
1.422     foxr     4595: 
1.186     albertel 4596: sub scantron_CODElist {
1.257     albertel 4597:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4598:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4599:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4600:     my $namechoice='<option></option>';
1.225     albertel 4601:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4602: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4603: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4604: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4605:     }
                   4606:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4607:     return $namechoice;
                   4608: }
                   4609: 
1.423     albertel 4610: =pod 
                   4611: 
                   4612: =item scantron_CODEunique
                   4613: 
                   4614:   Returns the html for "Each CODE to be used once" radio.
                   4615: 
                   4616: =cut
1.422     foxr     4617: 
1.186     albertel 4618: sub scantron_CODEunique {
1.381     albertel 4619:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4620:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4621:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4622:                 </span>
                   4623:                 <span style="white-space: nowrap;">
1.272     albertel 4624:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4625:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4626:                 </span>';
1.186     albertel 4627:     return $result;
                   4628: }
1.423     albertel 4629: 
                   4630: =pod 
                   4631: 
                   4632: =item scantron_selectphase
                   4633: 
                   4634:   Generates the initial screen to start the bubble sheet process.
                   4635:   Allows for - starting a grading run.
1.424     albertel 4636:              - downloading existing scan data (original, corrected
1.423     albertel 4637:                                                 or skipped info)
                   4638: 
                   4639:              - uploading new scan data
                   4640: 
                   4641:  Arguments:
                   4642:   $r          - The Apache request object
                   4643:   $file2grade - name of the file that contain the scanned data to score
                   4644: 
                   4645: =cut
1.186     albertel 4646: 
1.75      albertel 4647: sub scantron_selectphase {
1.209     ng       4648:     my ($r,$file2grade) = @_;
1.324     albertel 4649:     my ($symb)=&get_symb($r);
1.75      albertel 4650:     if (!$symb) {return '';}
1.423     albertel 4651:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4652:     my $default_form_data=&defaultFormData($symb);
                   4653:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4654:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4655:     my $format_selector=&scantron_scantab();
1.186     albertel 4656:     my $CODE_selector=&scantron_CODElist();
                   4657:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4658:     my $result;
1.422     foxr     4659: 
                   4660:     # Chunk of form to prompt for a file to grade and how:
                   4661: 
1.75      albertel 4662:     $result.= <<SCANTRONFORM;
1.162     albertel 4663:     <table width="100%" border="0">
1.75      albertel 4664:     <tr>
1.226     albertel 4665:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4666:       <td bgcolor="#777777">
1.203     albertel 4667:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4668:         $default_form_data
1.75      albertel 4669:         <table width="100%" border="0">
                   4670:           <tr bgcolor="#e6ffff">
1.174     albertel 4671:             <td colspan="2">
                   4672:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4673:             </td>
                   4674:           </tr>
                   4675:           <tr bgcolor="#ffffe6">
1.174     albertel 4676:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4677:           </tr>
                   4678:           <tr bgcolor="#ffffe6">
1.174     albertel 4679:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4680:           </tr>
1.82      albertel 4681:           <tr bgcolor="#ffffe6">
1.174     albertel 4682:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4683:           </tr>
1.157     albertel 4684:           <tr bgcolor="#ffffe6">
1.186     albertel 4685:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4686:           </tr>
                   4687:           <tr bgcolor="#ffffe6">
                   4688:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4689:           </tr>
                   4690:           <tr bgcolor="#ffffe6">
1.187     albertel 4691: 	    <td> Options: </td>
                   4692:             <td>
1.272     albertel 4693: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4694:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4695:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4696: 	    </td>
                   4697:           </tr>
                   4698:           <tr bgcolor="#ffffe6">
1.174     albertel 4699:             <td colspan="2">
1.265     www      4700:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4701:             </td>
                   4702:           </tr>
                   4703:         </table>
1.226     albertel 4704:        </td>
                   4705:      </form>
1.162     albertel 4706:     </tr>
                   4707: SCANTRONFORM
                   4708:    
                   4709:     $r->print($result);
                   4710: 
1.257     albertel 4711:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4712:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4713: 
1.422     foxr     4714: 	# Chunk of form to prompt for a scantron file upload.
                   4715: 
1.162     albertel 4716:         $r->print(<<SCANTRONFORM);
                   4717:     <tr>
                   4718:       <td bgcolor="#777777">
                   4719:         <table width="100%" border="0">
                   4720:           <tr bgcolor="#e6ffff">
                   4721:             <td>
1.174     albertel 4722:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4723:             </td>
                   4724:           </tr>
                   4725:           <tr bgcolor="#ffffe6">
                   4726:             <td>
                   4727: SCANTRONFORM
1.324     albertel 4728:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4729:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4730:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4731:     $r->print(<<UPLOAD);
                   4732:               <script type="text/javascript" language="javascript">
                   4733:     function checkUpload(formname) {
                   4734: 	if (formname.upfile.value == "") {
                   4735: 	    alert("Please use the browse button to select a file from your local directory.");
                   4736: 	    return false;
                   4737: 	}
                   4738: 	formname.submit();
                   4739:     }
                   4740:               </script>
                   4741: 
                   4742:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4743:                 $default_form_data
                   4744:                 <input name='courseid' type='hidden' value='$cnum' />
                   4745:                 <input name='domainid' type='hidden' value='$cdom' />
                   4746:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4747:                 File to upload:<input type="file" name="upfile" size="50" />
                   4748:                 <br />
                   4749:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4750:               </form>
                   4751: UPLOAD
1.162     albertel 4752: 
                   4753:         $r->print(<<SCANTRONFORM);
                   4754:             </td>
                   4755:           </tr>
1.75      albertel 4756:         </table>
                   4757:       </td>
                   4758:     </tr>
1.162     albertel 4759: SCANTRONFORM
                   4760:     }
1.422     foxr     4761: 
                   4762:     # Chunk of the form that prompts to view a scoring office file,
                   4763:     # corrected file, skipped records in a file.
                   4764: 
1.187     albertel 4765:     $r->print(<<SCANTRONFORM);
                   4766:     <tr>
1.226     albertel 4767:       <form action='/adm/grades' name='scantron_download'>
                   4768:         <td bgcolor="#777777">
1.379     albertel 4769: 	  $default_form_data
1.187     albertel 4770:           <input type="hidden" name="command" value="scantron_download" />
                   4771:           <table width="100%" border="0">
                   4772:             <tr bgcolor="#e6ffff">
                   4773:               <td colspan="2">
                   4774:                 &nbsp;<b>Download a scoring office file</b>
                   4775:               </td>
                   4776:             </tr>
                   4777:             <tr bgcolor="#ffffe6">
                   4778:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4779:             </tr>
                   4780:             <tr bgcolor="#ffffe6">
                   4781:               <td colspan="2">
1.293     www      4782:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4783:               </td>
                   4784:             </tr>
                   4785:           </table>
1.226     albertel 4786:         </td>
                   4787:       </form>
1.187     albertel 4788:     </tr>
                   4789: SCANTRONFORM
1.162     albertel 4790: 
                   4791:     $r->print(<<SCANTRONFORM);
1.75      albertel 4792:   </table>
1.81      albertel 4793: $grading_menu_button
1.75      albertel 4794: SCANTRONFORM
                   4795: 
1.162     albertel 4796:     return
1.75      albertel 4797: }
                   4798: 
1.423     albertel 4799: =pod
                   4800: 
                   4801: =item get_scantron_config
                   4802: 
                   4803:    Parse and return the scantron configuration line selected as a
                   4804:    hash of configuration file fields.
                   4805: 
                   4806:  Arguments:
                   4807:     which - the name of the configuration to parse from the file.
                   4808: 
                   4809: 
                   4810:  Returns:
                   4811:             If the named configuration is not in the file, an empty
                   4812:             hash is returned.
                   4813:     a hash with the fields
                   4814:       name         - internal name for the this configuration setup
                   4815:       description  - text to display to operator that describes this config
                   4816:       CODElocation - if 0 or the string 'none'
                   4817:                           - no CODE exists for this config
                   4818:                      if -1 || the string 'letter'
                   4819:                           - a CODE exists for this config and is
                   4820:                             a string of letters
                   4821:                      Unsupported value (but planned for future support)
                   4822:                           if a positive integer
                   4823:                                - The CODE exists as the first n items from
                   4824:                                  the question section of the form
                   4825:                           if the string 'number'
                   4826:                                - The CODE exists for this config and is
                   4827:                                  a string of numbers
                   4828:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4829:                      the CODE starts
                   4830:       CODElength  - length of the CODE
                   4831:       IDstart     - column where the student ID number starts
                   4832:       IDlength    - length of the student ID info
                   4833:       Qstart      - column where the information from the bubbled
                   4834:                     'questions' start
                   4835:       Qlength     - number of columns comprising a single bubble line from
                   4836:                     the sheet. (usually either 1 or 10)
1.424     albertel 4837:       Qon         - either a single character representing the character used
1.423     albertel 4838:                     to signal a bubble was chosen in the positional setup, or
                   4839:                     the string 'letter' if the letter of the chosen bubble is
                   4840:                     in the final, or 'number' if a number representing the
                   4841:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4842:       Qoff        - the character used to represent that a bubble was
                   4843:                     left blank
1.423     albertel 4844:       PaperID     - if the scanning process generates a unique number for each
                   4845:                     sheet scanned the column that this ID number starts in
                   4846:       PaperIDlength - number of columns that comprise the unique ID number
                   4847:                       for the sheet of paper
1.424     albertel 4848:       FirstName   - column that the first name starts in
1.423     albertel 4849:       FirstNameLength - number of columns that the first name spans
                   4850:  
                   4851:       LastName    - column that the last name starts in
                   4852:       LastNameLength - number of columns that the last name spans
                   4853: 
                   4854: =cut
1.422     foxr     4855: 
1.82      albertel 4856: sub get_scantron_config {
                   4857:     my ($which) = @_;
                   4858:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4859:     my %config;
1.157     albertel 4860:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4861:     foreach my $line (<$fh>) {
                   4862: 	my ($name,$descrip)=split(/:/,$line);
                   4863: 	if ($name ne $which ) { next; }
                   4864: 	chomp($line);
                   4865: 	my @config=split(/:/,$line);
                   4866: 	$config{'name'}=$config[0];
                   4867: 	$config{'description'}=$config[1];
                   4868: 	$config{'CODElocation'}=$config[2];
                   4869: 	$config{'CODEstart'}=$config[3];
                   4870: 	$config{'CODElength'}=$config[4];
                   4871: 	$config{'IDstart'}=$config[5];
                   4872: 	$config{'IDlength'}=$config[6];
                   4873: 	$config{'Qstart'}=$config[7];
                   4874: 	$config{'Qlength'}=$config[8];
                   4875: 	$config{'Qoff'}=$config[9];
                   4876: 	$config{'Qon'}=$config[10];
1.157     albertel 4877: 	$config{'PaperID'}=$config[11];
                   4878: 	$config{'PaperIDlength'}=$config[12];
                   4879: 	$config{'FirstName'}=$config[13];
                   4880: 	$config{'FirstNamelength'}=$config[14];
                   4881: 	$config{'LastName'}=$config[15];
                   4882: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4883: 	last;
                   4884:     }
                   4885:     return %config;
                   4886: }
                   4887: 
1.423     albertel 4888: =pod 
                   4889: 
                   4890: =item username_to_idmap
                   4891: 
                   4892:     creates a hash keyed by student id with values of the corresponding
                   4893:     student username:domain.
                   4894: 
                   4895:   Arguments:
                   4896: 
                   4897:     $classlist - reference to the class list hash. This is a hash
                   4898:                  keyed by student name:domain  whose elements are references
1.424     albertel 4899:                  to arrays containing various chunks of information
1.423     albertel 4900:                  about the student. (See loncoursedata for more info).
                   4901: 
                   4902:   Returns
                   4903:     %idmap - the constructed hash
                   4904: 
                   4905: =cut
                   4906: 
1.82      albertel 4907: sub username_to_idmap {
                   4908:     my ($classlist)= @_;
                   4909:     my %idmap;
                   4910:     foreach my $student (keys(%$classlist)) {
                   4911: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4912: 	    $student;
                   4913:     }
                   4914:     return %idmap;
                   4915: }
1.423     albertel 4916: 
                   4917: =pod
                   4918: 
1.424     albertel 4919: =item scantron_fixup_scanline
1.423     albertel 4920: 
                   4921:    Process a requested correction to a scanline.
                   4922: 
                   4923:   Arguments:
                   4924:     $scantron_config   - hash from &get_scantron_config()
                   4925:     $scan_data         - hash of correction information 
                   4926:                           (see &scantron_getfile())
                   4927:     $line              - existing scanline
                   4928:     $whichline         - line number of the passed in scanline
                   4929:     $field             - type of change to process 
                   4930:                          (either 
                   4931:                           'ID'     -> correct the student ID number
                   4932:                           'CODE'   -> correct the CODE
                   4933:                           'answer' -> fixup the submitted answers)
                   4934:     
                   4935:    $args               - hash of additional info,
                   4936:                           - 'ID' 
                   4937:                                'newid' -> studentID to use in replacement
1.424     albertel 4938:                                           of existing one
1.423     albertel 4939:                           - 'CODE' 
                   4940:                                'CODE_ignore_dup' - set to true if duplicates
                   4941:                                                    should be ignored.
                   4942: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4943:                                         if the existing unfound code should
1.423     albertel 4944:                                         be used as is
                   4945:                           - 'answer'
                   4946:                                'response' - new answer or 'none' if blank
                   4947:                                'question' - the bubble line to change
                   4948: 
                   4949:   Returns:
                   4950:     $line - the modified scanline
                   4951: 
                   4952:   Side effects: 
                   4953:     $scan_data - may be updated
                   4954: 
                   4955: =cut
                   4956: 
1.82      albertel 4957: 
1.157     albertel 4958: sub scantron_fixup_scanline {
                   4959:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4960: 
1.157     albertel 4961:     if ($field eq 'ID') {
                   4962: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4963: 	    return ($line,1,'New value too large');
1.157     albertel 4964: 	}
                   4965: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4966: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4967: 				     $args->{'newid'});
                   4968: 	}
                   4969: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4970: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4971: 	if ($args->{'newid'}=~/^\s*$/) {
                   4972: 	    &scan_data($scan_data,"$whichline.user",
                   4973: 		       $args->{'username'}.':'.$args->{'domain'});
                   4974: 	}
1.186     albertel 4975:     } elsif ($field eq 'CODE') {
1.192     albertel 4976: 	if ($args->{'CODE_ignore_dup'}) {
                   4977: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4978: 	}
                   4979: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4980: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4981: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4982: 		return ($line,1,'New CODE value too large');
                   4983: 	    }
                   4984: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4985: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4986: 	    }
                   4987: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4988: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4989: 	}
1.157     albertel 4990:     } elsif ($field eq 'answer') {
                   4991: 	my $length=$scantron_config->{'Qlength'};
                   4992: 	my $off=$scantron_config->{'Qoff'};
                   4993: 	my $on=$scantron_config->{'Qon'};
                   4994: 	my $answer=${off}x$length;
                   4995: 	if ($args->{'response'} eq 'none') {
                   4996: 	    &scan_data($scan_data,
                   4997: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4998: 	} else {
1.274     albertel 4999: 	    if ($on eq 'letter') {
                   5000: 		my @alphabet=('A'..'Z');
                   5001: 		$answer=$alphabet[$args->{'response'}];
                   5002: 	    } elsif ($on eq 'number') {
                   5003: 		$answer=$args->{'response'}+1;
1.389     albertel 5004: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 5005: 	    } else {
                   5006: 		substr($answer,$args->{'response'},1)=$on;
                   5007: 	    }
1.157     albertel 5008: 	    &scan_data($scan_data,
                   5009: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   5010: 	}
                   5011: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   5012: 	substr($line,$where-1,$length)=$answer;
                   5013:     }
                   5014:     return $line;
                   5015: }
1.423     albertel 5016: 
                   5017: =pod
                   5018: 
                   5019: =item scan_data
                   5020: 
                   5021:     Edit or look up  an item in the scan_data hash.
                   5022: 
                   5023:   Arguments:
                   5024:     $scan_data  - The hash (see scantron_getfile)
                   5025:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5026:                   scantronfilename_key).
1.423     albertel 5027:     $data        - New value of the hash entry.
                   5028:     $delete      - If true, the entry is removed from the hash.
                   5029: 
                   5030:   Returns:
                   5031:     The new value of the hash table field (undefined if deleted).
                   5032: 
                   5033: =cut
                   5034: 
                   5035: 
1.157     albertel 5036: sub scan_data {
                   5037:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5038:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5039:     if (defined($value)) {
                   5040: 	$scan_data->{$filename.'_'.$key} = $value;
                   5041:     }
                   5042:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5043:     return $scan_data->{$filename.'_'.$key};
                   5044: }
1.423     albertel 5045: 
                   5046: =pod 
                   5047: 
                   5048: =item scantron_parse_scanline
                   5049: 
                   5050:   Decodes a scanline from the selected scantron file
                   5051: 
                   5052:  Arguments:
                   5053:     line             - The text of the scantron file line to process
                   5054:     whichline        - Line number
                   5055:     scantron_config  - Hash describing the format of the scantron lines.
                   5056:     scan_data        - Hash of extra information about the scanline
                   5057:                        (see scantron_getfile for more information)
                   5058:     just_header      - True if should not process question answers but only
                   5059:                        the stuff to the left of the answers.
                   5060:  Returns:
                   5061:    Hash containing the result of parsing the scanline
                   5062: 
                   5063:    Keys are all proceeded by the string 'scantron.'
                   5064: 
                   5065:        CODE    - the CODE in use for this scanline
                   5066:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5067:                  by the operator
                   5068:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5069:                             CODEs were selected, but the usage has been
                   5070:                             forced by the operator
                   5071:        ID  - student ID
                   5072:        PaperID - if used, the ID number printed on the sheet when the 
                   5073:                  paper was scanned
                   5074:        FirstName - first name from the sheet
                   5075:        LastName  - last name from the sheet
                   5076: 
                   5077:      if just_header was not true these key may also exist
                   5078: 
                   5079:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5080:                       that is considered an error (if the operator had already
                   5081:                       okayed a blank bubble line as really being blank then
                   5082:                       that bubble line number won't appear here.
                   5083:        doubleerror  - a list of bubbled line numbers that had more than one
                   5084:                       bubble filled in and has not been corrected by the
                   5085:                       operator
                   5086:        maxquest     - the number of the last bubble line that was parsed
                   5087: 
                   5088:        (<number> starts at 1)
                   5089:        <number>.answer - zero or more letters representing the selected
                   5090:                          letters from the scanline for the bubble line 
                   5091:                          <number>.
                   5092:                          if blank there was either no bubble or there where
                   5093:                          multiple bubbles, (consult the keys missingerror and
                   5094:                          doubleerror if this is an error condition)
                   5095: 
                   5096: =cut
                   5097: 
1.82      albertel 5098: sub scantron_parse_scanline {
1.423     albertel 5099:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5100:     my %record;
1.422     foxr     5101:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5102:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5103:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5104: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5105: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5106: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5107: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5108: 	    $record{'scantron.CODE'}=substr($data,
                   5109: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5110: 					    $$scantron_config{'CODElength'});
1.191     albertel 5111: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5112: 		$record{'scantron.useCODE'}=1;
                   5113: 	    }
1.192     albertel 5114: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5115: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5116: 	    }
1.82      albertel 5117: 	} else {
                   5118: 	    #FIXME interpret first N questions
                   5119: 	}
                   5120:     }
1.83      albertel 5121:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5122: 				  $$scantron_config{'IDlength'});
1.157     albertel 5123:     $record{'scantron.PaperID'}=
                   5124: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5125: 	       $$scantron_config{'PaperIDlength'});
                   5126:     $record{'scantron.FirstName'}=
                   5127: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5128: 	       $$scantron_config{'FirstNamelength'});
                   5129:     $record{'scantron.LastName'}=
                   5130: 	substr($data,$$scantron_config{'LastName'}-1,
                   5131: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5132:     if ($just_header) { return \%record; }
1.194     albertel 5133: 
1.82      albertel 5134:     my @alphabet=('A'..'Z');
                   5135:     my $questnum=0;
                   5136:     while ($questions) {
                   5137: 	$questnum++;
                   5138: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5139: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5140: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5141: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5142: 	    if ($currentquest eq '?'
                   5143: 		|| $currentquest eq '*') {
1.274     albertel 5144: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5145: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5146: 	    } elsif (!defined($currentquest)
1.274     albertel 5147: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5148: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5149: 		$record{"scantron.$questnum.answer"}='';
                   5150: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5151: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5152: 		}
                   5153: 	    } else {
                   5154: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5155: 	    }
                   5156: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5157: 	    if ($currentquest eq '?'
                   5158: 		|| $currentquest eq '*') {
1.274     albertel 5159: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5160: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5161: 	    } elsif (!defined($currentquest)
                   5162: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5163: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5164: 		$record{"scantron.$questnum.answer"}='';
                   5165: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5166: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5167: 		}
                   5168: 	    } else {
1.371     albertel 5169: 		# wrap zero back to J
                   5170: 		if ($currentquest eq '0') {
                   5171: 		    $record{"scantron.$questnum.answer"}=
                   5172: 			$alphabet[9];
                   5173: 		} else {
                   5174: 		    $record{"scantron.$questnum.answer"}=
                   5175: 			$alphabet[$currentquest-1];
                   5176: 		}
1.239     albertel 5177: 	    }
1.82      albertel 5178: 	} else {
1.239     albertel 5179: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5180: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5181: 		$record{"scantron.$questnum.answer"}='';
                   5182: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5183: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5184: 		}
                   5185: 	    } else {
                   5186: 		$record{"scantron.$questnum.answer"}=
                   5187: 		    $alphabet[length($array[0])];
                   5188: 	    }
                   5189: 	    if (scalar(@array) gt 2) {
                   5190: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5191: 		my @ans=@array;
                   5192: 		my $i=length($ans[0]);shift(@ans);
                   5193: 		while ($#ans) {
                   5194: 		    $i+=length($ans[0])+1;
                   5195: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5196: 		    shift(@ans);
                   5197: 		}
                   5198: 	    }
1.82      albertel 5199: 	}
                   5200:     }
1.83      albertel 5201:     $record{'scantron.maxquest'}=$questnum;
                   5202:     return \%record;
1.82      albertel 5203: }
                   5204: 
1.423     albertel 5205: =pod
                   5206: 
                   5207: =item scantron_add_delay
                   5208: 
                   5209:    Adds an error message that occurred during the grading phase to a
                   5210:    queue of messages to be shown after grading pass is complete
                   5211: 
                   5212:  Arguments:
1.424     albertel 5213:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5214:    $scanline    - the scanline that caused the error
                   5215:    $errormesage - the error message
                   5216:    $errorcode   - a numeric code for the error
                   5217: 
                   5218:  Side Effects:
1.424     albertel 5219:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5220: 
                   5221: =cut
                   5222: 
1.82      albertel 5223: sub scantron_add_delay {
1.140     albertel 5224:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5225:     push(@$delayqueue,
                   5226: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5227: 	  'ecode' => $errorcode }
                   5228: 	 );
1.82      albertel 5229: }
                   5230: 
1.423     albertel 5231: =pod
                   5232: 
                   5233: =item scantron_find_student
                   5234: 
1.424     albertel 5235:    Finds the username for the current scanline
                   5236: 
                   5237:   Arguments:
                   5238:    $scantron_record - hash result from scantron_parse_scanline
                   5239:    $scan_data       - hash of correction information 
                   5240:                       (see &scantron_getfile() form more information)
                   5241:    $idmap           - hash from &username_to_idmap()
                   5242:    $line            - number of current scanline
                   5243:  
                   5244:   Returns:
                   5245:    Either 'username:domain' or undef if unknown
                   5246: 
1.423     albertel 5247: =cut
                   5248: 
1.82      albertel 5249: sub scantron_find_student {
1.157     albertel 5250:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5251:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5252:     if ($scanID =~ /^\s*$/) {
                   5253:  	return &scan_data($scan_data,"$line.user");
                   5254:     }
1.83      albertel 5255:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5256:  	if (lc($id) eq lc($scanID)) {
                   5257:  	    return $$idmap{$id};
                   5258:  	}
1.83      albertel 5259:     }
                   5260:     return undef;
                   5261: }
                   5262: 
1.423     albertel 5263: =pod
                   5264: 
                   5265: =item scantron_filter
                   5266: 
1.424     albertel 5267:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5268:    hidden resources was selected
                   5269: 
1.423     albertel 5270: =cut
                   5271: 
1.83      albertel 5272: sub scantron_filter {
                   5273:     my ($curres)=@_;
1.331     albertel 5274: 
                   5275:     if (ref($curres) && $curres->is_problem()) {
                   5276: 	# if the user has asked to not have either hidden
                   5277: 	# or 'randomout' controlled resources to be graded
                   5278: 	# don't include them
                   5279: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5280: 	    && $curres->randomout) {
                   5281: 	    return 0;
                   5282: 	}
1.83      albertel 5283: 	return 1;
                   5284:     }
                   5285:     return 0;
1.82      albertel 5286: }
                   5287: 
1.423     albertel 5288: =pod
                   5289: 
                   5290: =item scantron_process_corrections
                   5291: 
1.424     albertel 5292:    Gets correction information out of submitted form data and corrects
                   5293:    the scanline
                   5294: 
1.423     albertel 5295: =cut
                   5296: 
1.157     albertel 5297: sub scantron_process_corrections {
                   5298:     my ($r) = @_;
1.257     albertel 5299:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5300:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5301:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5302:     my $which=$env{'form.scantron_line'};
1.200     albertel 5303:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5304:     my ($skip,$err,$errmsg);
1.257     albertel 5305:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5306: 	$skip=1;
1.257     albertel 5307:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5308: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5309: 	    $env{'form.scantron_domain'};
1.157     albertel 5310: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5311: 	($line,$err,$errmsg)=
                   5312: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5313: 				     'ID',{'newid'=>$newid,
1.257     albertel 5314: 				    'username'=>$env{'form.scantron_username'},
                   5315: 				    'domain'=>$env{'form.scantron_domain'}});
                   5316:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5317: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5318: 	my $newCODE;
1.192     albertel 5319: 	my %args;
1.190     albertel 5320: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5321: 	    $newCODE='use_unfound';
1.190     albertel 5322: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5323: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5324: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5325: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5326: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5327: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5328: 	}
1.257     albertel 5329: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5330: 	    $args{'CODE_ignore_dup'}=1;
                   5331: 	}
                   5332: 	$args{'CODE'}=$newCODE;
1.186     albertel 5333: 	($line,$err,$errmsg)=
                   5334: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5335: 				     'CODE',\%args);
1.257     albertel 5336:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5337: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5338: 	    ($line,$err,$errmsg)=
                   5339: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5340: 					 $which,'answer',
                   5341: 					 { 'question'=>$question,
1.257     albertel 5342: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5343: 	    if ($err) { last; }
                   5344: 	}
                   5345:     }
                   5346:     if ($err) {
1.398     albertel 5347: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5348:     } else {
1.200     albertel 5349: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5350: 	&scantron_putfile($scanlines,$scan_data);
                   5351:     }
                   5352: }
                   5353: 
1.423     albertel 5354: =pod
                   5355: 
                   5356: =item reset_skipping_status
                   5357: 
1.424     albertel 5358:    Forgets the current set of remember skipped scanlines (and thus
                   5359:    reverts back to considering all lines in the
                   5360:    scantron_skipped_<filename> file)
                   5361: 
1.423     albertel 5362: =cut
                   5363: 
1.200     albertel 5364: sub reset_skipping_status {
                   5365:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5366:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5367:     &scantron_putfile(undef,$scan_data);
                   5368: }
                   5369: 
1.423     albertel 5370: =pod
                   5371: 
                   5372: =item start_skipping
                   5373: 
1.424     albertel 5374:    Marks a scanline to be skipped. 
                   5375: 
1.423     albertel 5376: =cut
                   5377: 
1.376     albertel 5378: sub start_skipping {
1.200     albertel 5379:     my ($scan_data,$i)=@_;
                   5380:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5381:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5382: 	$remembered{$i}=2;
                   5383:     } else {
                   5384: 	$remembered{$i}=1;
                   5385:     }
1.200     albertel 5386:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5387: }
                   5388: 
1.423     albertel 5389: =pod
                   5390: 
                   5391: =item should_be_skipped
                   5392: 
1.424     albertel 5393:    Checks whether a scanline should be skipped.
                   5394: 
1.423     albertel 5395: =cut
                   5396: 
1.200     albertel 5397: sub should_be_skipped {
1.376     albertel 5398:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5399:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5400: 	# not redoing old skips
1.376     albertel 5401: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5402: 	return 0;
                   5403:     }
                   5404:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5405: 
                   5406:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5407: 	return 0;
                   5408:     }
1.200     albertel 5409:     return 1;
                   5410: }
                   5411: 
1.423     albertel 5412: =pod
                   5413: 
                   5414: =item remember_current_skipped
                   5415: 
1.424     albertel 5416:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5417:    file and remembers them into scan_data for later use.
                   5418: 
1.423     albertel 5419: =cut
                   5420: 
1.200     albertel 5421: sub remember_current_skipped {
                   5422:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5423:     my %to_remember;
                   5424:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5425: 	if ($scanlines->{'skipped'}[$i]) {
                   5426: 	    $to_remember{$i}=1;
                   5427: 	}
                   5428:     }
1.376     albertel 5429: 
1.200     albertel 5430:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5431:     &scantron_putfile(undef,$scan_data);
                   5432: }
                   5433: 
1.423     albertel 5434: =pod
                   5435: 
                   5436: =item check_for_error
                   5437: 
1.424     albertel 5438:     Checks if there was an error when attempting to remove a specific
                   5439:     scantron_.. bubble sheet data file. Prints out an error if
                   5440:     something went wrong.
                   5441: 
1.423     albertel 5442: =cut
                   5443: 
1.200     albertel 5444: sub check_for_error {
                   5445:     my ($r,$result)=@_;
                   5446:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5447: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5448:     }
                   5449: }
1.157     albertel 5450: 
1.423     albertel 5451: =pod
                   5452: 
                   5453: =item scantron_warning_screen
                   5454: 
1.424     albertel 5455:    Interstitial screen to make sure the operator has selected the
                   5456:    correct options before we start the validation phase.
                   5457: 
1.423     albertel 5458: =cut
                   5459: 
1.203     albertel 5460: sub scantron_warning_screen {
                   5461:     my ($button_text)=@_;
1.257     albertel 5462:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5463:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5464:     my $CODElist;
1.284     albertel 5465:     if ($scantron_config{'CODElocation'} &&
                   5466: 	$scantron_config{'CODEstart'} &&
                   5467: 	$scantron_config{'CODElength'}) {
                   5468: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5469: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5470: 	$CODElist=
                   5471: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5472: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5473:     }
1.203     albertel 5474:     return (<<STUFF);
                   5475: <p>
1.398     albertel 5476: <span class="LC_warning">Please double check the information
                   5477:                  below before clicking on '$button_text'</span>
1.203     albertel 5478: </p>
                   5479: <table>
1.284     albertel 5480: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5481: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5482: $CODElist
1.203     albertel 5483: </table>
                   5484: <br />
                   5485: <p> If this information is correct, please click on '$button_text'.</p>
                   5486: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5487: 
                   5488: <br />
                   5489: STUFF
                   5490: }
                   5491: 
1.423     albertel 5492: =pod
                   5493: 
                   5494: =item scantron_do_warning
                   5495: 
1.424     albertel 5496:    Check if the operator has picked something for all required
                   5497:    fields. Error out if something is missing.
                   5498: 
1.423     albertel 5499: =cut
                   5500: 
1.203     albertel 5501: sub scantron_do_warning {
                   5502:     my ($r)=@_;
1.324     albertel 5503:     my ($symb)=&get_symb($r);
1.203     albertel 5504:     if (!$symb) {return '';}
1.324     albertel 5505:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5506:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5507:     if ( $env{'form.selectpage'} eq '' ||
                   5508: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5509: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5510: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5511: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5512: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5513: 	} 
1.257     albertel 5514: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5515: 	    $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 5516: 	} 
1.257     albertel 5517: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5518: 	    $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 5519: 	} 
                   5520:     } else {
1.265     www      5521: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5522: 	$r->print(<<STUFF);
1.203     albertel 5523: $warning
1.265     www      5524: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5525: <input type="hidden" name="command" value="scantron_validate" />
                   5526: STUFF
1.237     albertel 5527:     }
1.352     albertel 5528:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5529:     return '';
                   5530: }
                   5531: 
1.423     albertel 5532: =pod
                   5533: 
                   5534: =item scantron_form_start
                   5535: 
1.424     albertel 5536:     html hidden input for remembering all selected grading options
                   5537: 
1.423     albertel 5538: =cut
                   5539: 
1.203     albertel 5540: sub scantron_form_start {
                   5541:     my ($max_bubble)=@_;
                   5542:     my $result= <<SCANTRONFORM;
                   5543: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5544:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5545:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5546:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5547:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5548:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5549:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5550:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5551:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5552:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5553: SCANTRONFORM
                   5554:     return $result;
                   5555: }
                   5556: 
1.423     albertel 5557: =pod
                   5558: 
                   5559: =item scantron_validate_file
                   5560: 
1.424     albertel 5561:     Dispatch routine for doing validation of a bubble sheet data file.
                   5562: 
                   5563:     Also processes any necessary information resets that need to
                   5564:     occur before validation begins (ignore previous corrections,
                   5565:     restarting the skipped records processing)
                   5566: 
1.423     albertel 5567: =cut
                   5568: 
1.157     albertel 5569: sub scantron_validate_file {
                   5570:     my ($r) = @_;
1.324     albertel 5571:     my ($symb)=&get_symb($r);
1.157     albertel 5572:     if (!$symb) {return '';}
1.324     albertel 5573:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5574:     
                   5575:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5576:     # them when doing the corrections reset
1.257     albertel 5577:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5578: 	&reset_skipping_status();
                   5579:     }
1.257     albertel 5580:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5581: 	&remember_current_skipped();
1.257     albertel 5582: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5583:     }
                   5584: 
1.257     albertel 5585:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5586: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5587: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5588: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5589: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5590:     }
1.200     albertel 5591: 
1.257     albertel 5592:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5593: 	&scantron_process_corrections($r);
                   5594:     }
1.424     albertel 5595:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5596:     #get the student pick code ready
                   5597:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5598:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5599:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5600:     $r->print($result);
                   5601:     
1.334     albertel 5602:     my @validate_phases=( 'sequence',
                   5603: 			  'ID',
1.157     albertel 5604: 			  'CODE',
                   5605: 			  'doublebubble',
                   5606: 			  'missingbubbles');
1.257     albertel 5607:     if (!$env{'form.validatepass'}) {
                   5608: 	$env{'form.validatepass'} = 0;
1.157     albertel 5609:     }
1.257     albertel 5610:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5611: 
                   5612:     my $stop=0;
                   5613:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5614: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5615: 	$r->rflush();
                   5616: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5617: 	{
                   5618: 	    no strict 'refs';
                   5619: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5620: 	}
                   5621:     }
                   5622:     if (!$stop) {
1.203     albertel 5623: 	my $warning=&scantron_warning_screen('Start Grading');
                   5624: 	$r->print(<<STUFF);
                   5625: Validation process complete.<br />
                   5626: $warning
                   5627: <input type="submit" name="submit" value="Start Grading" />
                   5628: <input type="hidden" name="command" value="scantron_process" />
                   5629: STUFF
                   5630: 
1.157     albertel 5631:     } else {
                   5632: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5633: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5634:     }
                   5635:     if ($stop) {
1.334     albertel 5636: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5637: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5638: 	    $r->print(' this error <br />');
                   5639: 
                   5640: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5641: 	} else {
                   5642: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5643: 	    $r->print(' using corrected info <br />');
                   5644: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5645: 	    $r->print(" this scanline saving it for later.");
                   5646: 	}
1.157     albertel 5647:     }
1.352     albertel 5648:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5649:     return '';
                   5650: }
                   5651: 
1.423     albertel 5652: 
                   5653: =pod
                   5654: 
                   5655: =item scantron_remove_file
                   5656: 
1.424     albertel 5657:    Removes the requested bubble sheet data file, makes sure that
                   5658:    scantron_original_<filename> is never removed
                   5659: 
                   5660: 
1.423     albertel 5661: =cut
                   5662: 
1.200     albertel 5663: sub scantron_remove_file {
1.192     albertel 5664:     my ($which)=@_;
1.257     albertel 5665:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5666:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5667:     my $file='scantron_';
1.200     albertel 5668:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5669: 	$file.=$which.'_';
1.192     albertel 5670:     } else {
                   5671: 	return 'refused';
                   5672:     }
1.257     albertel 5673:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5674:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5675: }
                   5676: 
1.423     albertel 5677: 
                   5678: =pod
                   5679: 
                   5680: =item scantron_remove_scan_data
                   5681: 
1.424     albertel 5682:    Removes all scan_data correction for the requested bubble sheet
                   5683:    data file.  (In the case that both the are doing skipped records we need
                   5684:    to remember the old skipped lines for the time being so that element
                   5685:    persists for a while.)
                   5686: 
1.423     albertel 5687: =cut
                   5688: 
1.200     albertel 5689: sub scantron_remove_scan_data {
1.257     albertel 5690:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5691:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5692:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5693:     my @todelete;
1.257     albertel 5694:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5695:     foreach my $key (@keys) {
                   5696: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5697: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5698: 		$key=~/remember_skipping/) {
                   5699: 		next;
                   5700: 	    }
1.192     albertel 5701: 	    push(@todelete,$key);
                   5702: 	}
                   5703:     }
1.200     albertel 5704:     my $result;
1.192     albertel 5705:     if (@todelete) {
1.200     albertel 5706: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5707:     }
                   5708:     return $result;
                   5709: }
                   5710: 
1.423     albertel 5711: 
                   5712: =pod
                   5713: 
                   5714: =item scantron_getfile
                   5715: 
1.424     albertel 5716:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5717:     the scan_data hash
                   5718:   
                   5719:   Arguments:
                   5720:     None
                   5721: 
                   5722:   Returns:
                   5723:     2 hash references
                   5724: 
                   5725:      - first one has 
                   5726:          orig      -
                   5727:          corrected -
                   5728:          skipped   -  each of which points to an array ref of the specified
                   5729:                       file broken up into individual lines
                   5730:          count     - number of scanlines
                   5731:  
                   5732:      - second is the scan_data hash possible keys are
1.425     albertel 5733:        ($number refers to scanline numbered $number and thus the key affects
                   5734:         only that scanline
                   5735:         $bubline refers to the specific bubble line element and the aspects
                   5736:         refers to that specific bubble line element)
                   5737: 
                   5738:        $number.user - username:domain to use
                   5739:        $number.CODE_ignore_dup 
                   5740:                     - ignore the duplicate CODE error 
                   5741:        $number.useCODE
                   5742:                     - use the CODE in the scanline as is
                   5743:        $number.no_bubble.$bubline
                   5744:                     - it is valid that there is no bubbled in bubble
                   5745:                       at $number $bubline
                   5746:        remember_skipping
                   5747:                     - a frozen hash containing keys of $number and values
                   5748:                       of either 
                   5749:                         1 - we are on a 'do skipped records pass' and plan
                   5750:                             on processing this line
                   5751:                         2 - we are on a 'do skipped records pass' and this
                   5752:                             scanline has been marked to skip yet again
1.424     albertel 5753: 
1.423     albertel 5754: =cut
                   5755: 
1.157     albertel 5756: sub scantron_getfile {
1.200     albertel 5757:     #FIXME really would prefer a scantron directory
1.257     albertel 5758:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5759:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5760:     my $lines;
                   5761:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5762: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5763:     my %scanlines;
                   5764:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5765:     my $temp=$scanlines{'orig'};
                   5766:     $scanlines{'count'}=$#$temp;
                   5767: 
                   5768:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5769: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5770:     if ($lines eq '-1') {
                   5771: 	$scanlines{'corrected'}=[];
                   5772:     } else {
                   5773: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5774:     }
                   5775:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5776: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5777:     if ($lines eq '-1') {
                   5778: 	$scanlines{'skipped'}=[];
                   5779:     } else {
                   5780: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5781:     }
1.175     albertel 5782:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5783:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5784:     my %scan_data = @tmp;
                   5785:     return (\%scanlines,\%scan_data);
                   5786: }
                   5787: 
1.423     albertel 5788: =pod
                   5789: 
                   5790: =item lonnet_putfile
                   5791: 
1.424     albertel 5792:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5793: 
                   5794:  Arguments:
                   5795:    $contents - data to store
                   5796:    $filename - filename to store $contents into
                   5797: 
                   5798:  Returns:
                   5799:    result value from &Apache::lonnet::finishuserfileupload
                   5800: 
1.423     albertel 5801: =cut
                   5802: 
1.157     albertel 5803: sub lonnet_putfile {
                   5804:     my ($contents,$filename)=@_;
1.257     albertel 5805:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5806:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5807:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5808:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5809: 
                   5810: }
                   5811: 
1.423     albertel 5812: =pod
                   5813: 
                   5814: =item scantron_putfile
                   5815: 
1.424     albertel 5816:     Stores the current version of the bubble sheet data files, and the
                   5817:     scan_data hash. (Does not modify the original version only the
                   5818:     corrected and skipped versions.
                   5819: 
                   5820:  Arguments:
                   5821:     $scanlines - hash ref that looks like the first return value from
                   5822:                  &scantron_getfile()
                   5823:     $scan_data - hash ref that looks like the second return value from
                   5824:                  &scantron_getfile()
                   5825: 
1.423     albertel 5826: =cut
                   5827: 
1.157     albertel 5828: sub scantron_putfile {
                   5829:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5830:     #FIXME really would prefer a scantron directory
1.257     albertel 5831:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5832:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5833:     if ($scanlines) {
                   5834: 	my $prefix='scantron_';
1.157     albertel 5835: # no need to update orig, shouldn't change
                   5836: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5837: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5838: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5839: 			$prefix.'corrected_'.
1.257     albertel 5840: 			$env{'form.scantron_selectfile'});
1.200     albertel 5841: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5842: 			$prefix.'skipped_'.
1.257     albertel 5843: 			$env{'form.scantron_selectfile'});
1.200     albertel 5844:     }
1.175     albertel 5845:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5846: }
                   5847: 
1.423     albertel 5848: =pod
                   5849: 
                   5850: =item scantron_get_line
                   5851: 
1.424     albertel 5852:    Returns the correct version of the scanline
                   5853: 
                   5854:  Arguments:
                   5855:     $scanlines - hash ref that looks like the first return value from
                   5856:                  &scantron_getfile()
                   5857:     $scan_data - hash ref that looks like the second return value from
                   5858:                  &scantron_getfile()
                   5859:     $i         - number of the requested line (starts at 0)
                   5860: 
                   5861:  Returns:
                   5862:    A scanline, (either the original or the corrected one if it
                   5863:    exists), or undef if the requested scanline should be
                   5864:    skipped. (Either because it's an skipped scanline, or it's an
                   5865:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5866:    pass.
                   5867: 
1.423     albertel 5868: =cut
                   5869: 
1.157     albertel 5870: sub scantron_get_line {
1.200     albertel 5871:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5872:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5873:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5874:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5875:     return $scanlines->{'orig'}[$i]; 
                   5876: }
                   5877: 
1.423     albertel 5878: =pod
                   5879: 
                   5880: =item scantron_todo_count
                   5881: 
1.424     albertel 5882:     Counts the number of scanlines that need processing.
                   5883: 
                   5884:  Arguments:
                   5885:     $scanlines - hash ref that looks like the first return value from
                   5886:                  &scantron_getfile()
                   5887:     $scan_data - hash ref that looks like the second return value from
                   5888:                  &scantron_getfile()
                   5889: 
                   5890:  Returns:
                   5891:     $count - number of scanlines to process
                   5892: 
1.423     albertel 5893: =cut
                   5894: 
1.200     albertel 5895: sub get_todo_count {
                   5896:     my ($scanlines,$scan_data)=@_;
                   5897:     my $count=0;
                   5898:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5899: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5900: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5901: 	$count++;
                   5902:     }
                   5903:     return $count;
                   5904: }
                   5905: 
1.423     albertel 5906: =pod
                   5907: 
                   5908: =item scantron_put_line
                   5909: 
1.424     albertel 5910:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5911:     data file.
                   5912: 
                   5913:  Arguments:
                   5914:     $scanlines - hash ref that looks like the first return value from
                   5915:                  &scantron_getfile()
                   5916:     $scan_data - hash ref that looks like the second return value from
                   5917:                  &scantron_getfile()
                   5918:     $i         - line number to update
                   5919:     $newline   - contents of the updated scanline
                   5920:     $skip      - if true make the line for skipping and update the
                   5921:                  'skipped' file
                   5922: 
1.423     albertel 5923: =cut
                   5924: 
1.157     albertel 5925: sub scantron_put_line {
1.200     albertel 5926:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5927:     if ($skip) {
                   5928: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5929: 	&start_skipping($scan_data,$i);
1.157     albertel 5930: 	return;
                   5931:     }
                   5932:     $scanlines->{'corrected'}[$i]=$newline;
                   5933: }
                   5934: 
1.423     albertel 5935: =pod
                   5936: 
                   5937: =item scantron_clear_skip
                   5938: 
1.424     albertel 5939:    Remove a line from the 'skipped' file
                   5940: 
                   5941:  Arguments:
                   5942:     $scanlines - hash ref that looks like the first return value from
                   5943:                  &scantron_getfile()
                   5944:     $scan_data - hash ref that looks like the second return value from
                   5945:                  &scantron_getfile()
                   5946:     $i         - line number to update
                   5947: 
1.423     albertel 5948: =cut
                   5949: 
1.376     albertel 5950: sub scantron_clear_skip {
                   5951:     my ($scanlines,$scan_data,$i)=@_;
                   5952:     if (exists($scanlines->{'skipped'}[$i])) {
                   5953: 	undef($scanlines->{'skipped'}[$i]);
                   5954: 	return 1;
                   5955:     }
                   5956:     return 0;
                   5957: }
                   5958: 
1.423     albertel 5959: =pod
                   5960: 
                   5961: =item scantron_filter_not_exam
                   5962: 
1.424     albertel 5963:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5964:    filter out resources that are not marked as 'exam' mode
                   5965: 
1.423     albertel 5966: =cut
                   5967: 
1.334     albertel 5968: sub scantron_filter_not_exam {
                   5969:     my ($curres)=@_;
                   5970:     
                   5971:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5972: 	# if the user has asked to not have either hidden
                   5973: 	# or 'randomout' controlled resources to be graded
                   5974: 	# don't include them
                   5975: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5976: 	    && $curres->randomout) {
                   5977: 	    return 0;
                   5978: 	}
                   5979: 	return 1;
                   5980:     }
                   5981:     return 0;
                   5982: }
                   5983: 
1.423     albertel 5984: =pod
                   5985: 
                   5986: =item scantron_validate_sequence
                   5987: 
1.424     albertel 5988:     Validates the selected sequence, checking for resource that are
                   5989:     not set to exam mode.
                   5990: 
1.423     albertel 5991: =cut
                   5992: 
1.334     albertel 5993: sub scantron_validate_sequence {
                   5994:     my ($r,$currentphase) = @_;
                   5995: 
                   5996:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5997:     my (undef,undef,$sequence)=
                   5998: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5999: 
                   6000:     my $map=$navmap->getResourceByUrl($sequence);
                   6001: 
                   6002:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   6003:                                     value="ignore" />');
                   6004:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   6005: 	my @resources=
                   6006: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   6007: 	if (@resources) {
1.357     banghart 6008: 	    $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 6009: 	    return (1,$currentphase);
                   6010: 	}
                   6011:     }
                   6012: 
                   6013:     return (0,$currentphase+1);
                   6014: }
                   6015: 
1.423     albertel 6016: =pod
                   6017: 
                   6018: =item scantron_validate_ID
                   6019: 
1.424     albertel 6020:    Validates all scanlines in the selected file to not have any
                   6021:    invalid or underspecified student IDs
                   6022: 
1.423     albertel 6023: =cut
                   6024: 
1.157     albertel 6025: sub scantron_validate_ID {
                   6026:     my ($r,$currentphase) = @_;
                   6027:     
                   6028:     #get student info
                   6029:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6030:     my %idmap=&username_to_idmap($classlist);
                   6031: 
                   6032:     #get scantron line setup
1.257     albertel 6033:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6034:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6035: 
                   6036:     my %found=('ids'=>{},'usernames'=>{});
                   6037:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6038: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6039: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6040: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6041: 						 $scan_data);
                   6042: 	my $id=$$scan_record{'scantron.ID'};
                   6043: 	my $found;
                   6044: 	foreach my $checkid (keys(%idmap)) {
                   6045: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6046: 	}
                   6047: 	if ($found) {
                   6048: 	    my $username=$idmap{$found};
                   6049: 	    if ($found{'ids'}{$found}) {
                   6050: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6051: 					 $line,'duplicateID',$found);
1.194     albertel 6052: 		return(1,$currentphase);
1.157     albertel 6053: 	    } elsif ($found{'usernames'}{$username}) {
                   6054: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6055: 					 $line,'duplicateID',$username);
1.194     albertel 6056: 		return(1,$currentphase);
1.157     albertel 6057: 	    }
1.186     albertel 6058: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6059: 	    $found{'ids'}{$found}++;
                   6060: 	    $found{'usernames'}{$username}++;
                   6061: 	} else {
                   6062: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6063: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6064: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6065: 		    &scantron_get_correction($r,$i,$scan_record,
                   6066: 					     \%scantron_config,
                   6067: 					     $line,'duplicateID',$username);
1.194     albertel 6068: 		    return(1,$currentphase);
1.157     albertel 6069: 		} elsif (!defined($username)) {
                   6070: 		    &scantron_get_correction($r,$i,$scan_record,
                   6071: 					     \%scantron_config,
                   6072: 					     $line,'incorrectID');
1.194     albertel 6073: 		    return(1,$currentphase);
1.157     albertel 6074: 		}
                   6075: 		$found{'usernames'}{$username}++;
                   6076: 	    } else {
                   6077: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6078: 					 $line,'incorrectID');
1.194     albertel 6079: 		return(1,$currentphase);
1.157     albertel 6080: 	    }
                   6081: 	}
                   6082:     }
                   6083: 
                   6084:     return (0,$currentphase+1);
                   6085: }
                   6086: 
1.423     albertel 6087: =pod
                   6088: 
                   6089: =item scantron_get_correction
                   6090: 
1.424     albertel 6091:    Builds the interface screen to interact with the operator to fix a
                   6092:    specific error condition in a specific scanline
                   6093: 
                   6094:  Arguments:
                   6095:     $r           - Apache request object
                   6096:     $i           - number of the current scanline
                   6097:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6098:     $scan_config - hash ref as returned from &get_scantron_config()
                   6099:     $line        - full contents of the current scanline
                   6100:     $error       - error condition, valid values are
                   6101:                    'incorrectCODE', 'duplicateCODE',
                   6102:                    'doublebubble', 'missingbubble',
                   6103:                    'duplicateID', 'incorrectID'
                   6104:     $arg         - extra information needed
                   6105:        For errors:
                   6106:          - duplicateID   - paper number that this studentID was seen before on
                   6107:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6108:                            seen on before
                   6109:          - incorrectCODE - current incorrect CODE 
                   6110:          - doublebubble  - array ref of the bubble lines that have double
                   6111:                            bubble errors
                   6112:          - missingbubble - array ref of the bubble lines that have missing
                   6113:                            bubble errors
                   6114: 
1.423     albertel 6115: =cut
                   6116: 
1.157     albertel 6117: sub scantron_get_correction {
                   6118:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6119: 
                   6120: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6121: #to show both the current line and the previous one and allow skipping
                   6122: #the previous one or the current one
                   6123: 
1.161     albertel 6124:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6125:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6126: 	$r->print(" for PaperID <tt>".
                   6127: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6128:     } else {
                   6129: 	$r->print(" in scanline $i <pre>".
                   6130: 		  $line."</pre> \n");
                   6131:     }
1.242     albertel 6132:     my $message="<p>The ID on the form is  <tt>".
                   6133: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6134: 	"The name on the paper is ".
                   6135: 	$$scan_record{'scantron.LastName'}.",".
                   6136: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6137: 
1.157     albertel 6138:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6139:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6140:     if ($error =~ /ID$/) {
1.186     albertel 6141: 	if ($error eq 'incorrectID') {
1.157     albertel 6142: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6143: 	} elsif ($error eq 'duplicateID') {
                   6144: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6145: 	}
1.242     albertel 6146: 	$r->print($message);
1.157     albertel 6147: 	$r->print("<p>How should I handle this? <br /> \n");
                   6148: 	$r->print("\n<ul><li> ");
                   6149: 	#FIXME it would be nice if this sent back the user ID and
                   6150: 	#could do partial userID matches
                   6151: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6152: 				       'scantron_username','scantron_domain'));
                   6153: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6154: 	$r->print("\n@".
1.257     albertel 6155: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6156: 
                   6157: 	$r->print('</li>');
1.186     albertel 6158:     } elsif ($error =~ /CODE$/) {
                   6159: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6160: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6161: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6162: 	    $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 6163: 	}
1.224     albertel 6164: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6165: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6166: 	$r->print($message);
1.186     albertel 6167: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6168: 	$r->print("\n<br /> ");
1.194     albertel 6169: 	my $i=0;
1.273     albertel 6170: 	if ($error eq 'incorrectCODE' 
                   6171: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6172: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6173: 	    if ($closest > 0) {
                   6174: 		foreach my $testcode (@{$closest}) {
                   6175: 		    my $checked='';
1.401     albertel 6176: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6177: 		    $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' />");
                   6178: 		    $r->print("\n<br />");
                   6179: 		    $i++;
                   6180: 		}
1.194     albertel 6181: 	    }
                   6182: 	}
1.273     albertel 6183: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6184: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6185: 	    $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>");
                   6186: 	    $r->print("\n<br />");
                   6187: 	}
1.194     albertel 6188: 
1.188     albertel 6189: 	$r->print(<<ENDSCRIPT);
                   6190: <script type="text/javascript">
                   6191: function change_radio(field) {
1.190     albertel 6192:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6193:     var i;
                   6194:     for (i=0;i<slct.length;i++) {
                   6195:         if (slct[i].value==field) { slct[i].checked=true; }
                   6196:     }
                   6197: }
                   6198: </script>
                   6199: ENDSCRIPT
1.187     albertel 6200: 	my $href="/adm/pickcode?".
1.359     www      6201: 	   "form=".&escape("scantronupload").
                   6202: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6203: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6204: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6205: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6206: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6207: 	    $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')\" />");
                   6208: 	    $r->print("\n<br />");
                   6209: 	}
1.272     albertel 6210: 	$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 6211: 	$r->print("\n<br /><br />");
1.157     albertel 6212:     } elsif ($error eq 'doublebubble') {
                   6213: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6214: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6215: 		  join(',',@{$arg}).'" />');
1.242     albertel 6216: 	$r->print($message);
1.157     albertel 6217: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6218: 	foreach my $question (@{$arg}) {
                   6219: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6220: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6221: 				      split('',$selected));
1.157     albertel 6222: 	}
                   6223:     } elsif ($error eq 'missingbubble') {
                   6224: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6225: 	$r->print($message);
1.157     albertel 6226: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6227: 	$r->print("Some questions have no scanned bubbles\n");
                   6228: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6229: 		  join(',',@{$arg}).'" />');
                   6230: 	foreach my $question (@{$arg}) {
                   6231: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6232: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6233: 	}
                   6234:     } else {
                   6235: 	$r->print("\n<ul>");
                   6236:     }
                   6237:     $r->print("\n</li></ul>");
                   6238: 
                   6239: }
1.423     albertel 6240: 
                   6241: =pod
                   6242: 
                   6243: =item scantron_bubble_selector
                   6244:   
                   6245:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6246:    possibly showing the existing the selected bubbles if known
1.423     albertel 6247: 
                   6248:  Arguments:
                   6249:     $r           - Apache request object
                   6250:     $scan_config - hash from &get_scantron_config()
                   6251:     $quest       - number of the bubble line to make a corrector for
                   6252:     $selected    - array of letters of previously selected bubbles
                   6253:     $lines       - if present, number of bubble lines to show
                   6254: 
                   6255: =cut
                   6256: 
1.157     albertel 6257: sub scantron_bubble_selector {
1.422     foxr     6258:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6259:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6260: 
                   6261:     my $scmode=$$scan_config{'Qon'};
                   6262:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6263: 
1.422     foxr     6264: 
                   6265:     if (!defined($lines)) {
                   6266: 	$lines = 1;
                   6267:     }
                   6268:     my $total_lines = $lines*2;
1.157     albertel 6269:     my @alphabet=('A'..'Z');
1.422     foxr     6270:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6271: 
                   6272:     for (my $l = 0; $l < $lines; $l++) {
                   6273: 	if ($l != 0) {
                   6274: 	    $r->print('<tr>');
                   6275: 	}
                   6276: 
                   6277: 	# FIXME:  This loop probably has to be considerably more clever for
                   6278: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6279: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6280: 
                   6281: 	for (my $i=0;$i<$max;$i++) {
                   6282: 	    $r->print("\n".'<td align="center">');
                   6283: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6284: 		$r->print('X'); 
                   6285: 		shift(@selected) ;
                   6286: 	    } else { 
                   6287: 		$r->print('&nbsp;'); 
                   6288: 	    }
                   6289: 	    $r->print('</td>');
                   6290: 	    
                   6291: 	}
                   6292: 
                   6293: 	if ($l == 0) {
                   6294: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6295: 
                   6296: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6297: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6298: 	
                   6299: 	}
                   6300: 
                   6301: 	$r->print('</tr><tr>');
                   6302: 
                   6303: 	# FIXME: This may have to be a bit more clever for
                   6304: 	#        multiline questions (different values e.g..).
                   6305: 
                   6306: 	for (my $i=0;$i<$max;$i++) {
                   6307: 	    $r->print("\n".
                   6308: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6309: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6310: 	}
                   6311: 	$r->print('</tr>');
                   6312: 
                   6313: 	    
1.157     albertel 6314:     }
1.422     foxr     6315:     $r->print('</table>');
1.157     albertel 6316: }
                   6317: 
1.423     albertel 6318: =pod
                   6319: 
                   6320: =item num_matches
                   6321: 
1.424     albertel 6322:    Counts the number of characters that are the same between the two arguments.
                   6323: 
                   6324:  Arguments:
                   6325:    $orig - CODE from the scanline
                   6326:    $code - CODE to match against
                   6327: 
                   6328:  Returns:
                   6329:    $count - integer count of the number of same characters between the
                   6330:             two arguments
                   6331: 
1.423     albertel 6332: =cut
                   6333: 
1.194     albertel 6334: sub num_matches {
                   6335:     my ($orig,$code) = @_;
                   6336:     my @code=split(//,$code);
                   6337:     my @orig=split(//,$orig);
                   6338:     my $same=0;
                   6339:     for (my $i=0;$i<scalar(@code);$i++) {
                   6340: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6341:     }
                   6342:     return $same;
                   6343: }
                   6344: 
1.423     albertel 6345: =pod
                   6346: 
                   6347: =item scantron_get_closely_matching_CODEs
                   6348: 
1.424     albertel 6349:    Cycles through all CODEs and finds the set that has the greatest
                   6350:    number of same characters as the provided CODE
                   6351: 
                   6352:  Arguments:
                   6353:    $allcodes - hash ref returned by &get_codes()
                   6354:    $CODE     - CODE from the current scanline
                   6355: 
                   6356:  Returns:
                   6357:    2 element list
                   6358:     - first elements is number of how closely matching the best fit is 
                   6359:       (5 means best set has 5 matching characters)
                   6360:     - second element is an arrary ref containing the set of valid CODEs
                   6361:       that best fit the passed in CODE
                   6362: 
1.423     albertel 6363: =cut
                   6364: 
1.194     albertel 6365: sub scantron_get_closely_matching_CODEs {
                   6366:     my ($allcodes,$CODE)=@_;
                   6367:     my @CODEs;
                   6368:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6369: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6370:     }
                   6371: 
                   6372:     return ($#CODEs,$CODEs[-1]);
                   6373: }
                   6374: 
1.423     albertel 6375: =pod
                   6376: 
                   6377: =item get_codes
                   6378: 
1.424     albertel 6379:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6380:    set of remembered CODEs.
                   6381: 
                   6382:  Arguments:
                   6383:   $old_name - name of the set of remembered CODEs
                   6384:   $cdom     - domain of the course
                   6385:   $cnum     - internal course name
                   6386: 
                   6387:  Returns:
                   6388:   %allcodes - keys are the valid CODEs, values are all 1
                   6389: 
1.423     albertel 6390: =cut
                   6391: 
1.194     albertel 6392: sub get_codes {
1.280     foxr     6393:     my ($old_name, $cdom, $cnum) = @_;
                   6394:     if (!$old_name) {
                   6395: 	$old_name=$env{'form.scantron_CODElist'};
                   6396:     }
                   6397:     if (!$cdom) {
                   6398: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6399:     }
                   6400:     if (!$cnum) {
                   6401: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6402:     }
1.278     albertel 6403:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6404: 				    $cdom,$cnum);
                   6405:     my %allcodes;
                   6406:     if ($result{"type\0$old_name"} eq 'number') {
                   6407: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6408:     } else {
                   6409: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6410:     }
1.194     albertel 6411:     return %allcodes;
                   6412: }
                   6413: 
1.423     albertel 6414: =pod
                   6415: 
                   6416: =item scantron_validate_CODE
                   6417: 
1.424     albertel 6418:    Validates all scanlines in the selected file to not have any
                   6419:    invalid or underspecified CODEs and that none of the codes are
                   6420:    duplicated if this was requested.
                   6421: 
1.423     albertel 6422: =cut
                   6423: 
1.157     albertel 6424: sub scantron_validate_CODE {
                   6425:     my ($r,$currentphase) = @_;
1.257     albertel 6426:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6427:     if ($scantron_config{'CODElocation'} &&
                   6428: 	$scantron_config{'CODEstart'} &&
                   6429: 	$scantron_config{'CODElength'}) {
1.257     albertel 6430: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6431: 	    &FIXME_blow_up()
                   6432: 	}
                   6433:     } else {
                   6434: 	return (0,$currentphase+1);
                   6435:     }
                   6436:     
                   6437:     my %usedCODEs;
                   6438: 
1.194     albertel 6439:     my %allcodes=&get_codes();
1.186     albertel 6440: 
                   6441:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6442:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6443: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6444: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6445: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6446: 						 $scan_data);
                   6447: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6448: 	my $error=0;
1.224     albertel 6449: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6450: 	    &scantron_get_correction($r,$i,$scan_record,
                   6451: 				     \%scantron_config,
                   6452: 				     $line,'incorrectCODE',\%allcodes);
                   6453: 	    return(1,$currentphase);
                   6454: 	}
1.221     albertel 6455: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6456: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6457: 	    &scantron_get_correction($r,$i,$scan_record,
                   6458: 				     \%scantron_config,
1.194     albertel 6459: 				     $line,'incorrectCODE',\%allcodes);
                   6460: 	    return(1,$currentphase);
1.186     albertel 6461: 	}
1.214     albertel 6462: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6463: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6464: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6465: 	    &scantron_get_correction($r,$i,$scan_record,
                   6466: 				     \%scantron_config,
1.194     albertel 6467: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6468: 	    return(1,$currentphase);
1.186     albertel 6469: 	}
1.194     albertel 6470: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6471:     }
1.157     albertel 6472:     return (0,$currentphase+1);
                   6473: }
                   6474: 
1.423     albertel 6475: =pod
                   6476: 
                   6477: =item scantron_validate_doublebubble
                   6478: 
1.424     albertel 6479:    Validates all scanlines in the selected file to not have any
                   6480:    bubble lines with multiple bubbles marked.
                   6481: 
1.423     albertel 6482: =cut
                   6483: 
1.157     albertel 6484: sub scantron_validate_doublebubble {
                   6485:     my ($r,$currentphase) = @_;
                   6486:     #get student info
                   6487:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6488:     my %idmap=&username_to_idmap($classlist);
                   6489: 
                   6490:     #get scantron line setup
1.257     albertel 6491:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6492:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6493:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6494: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6495: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6496: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6497: 						 $scan_data);
                   6498: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6499: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6500: 				 'doublebubble',
                   6501: 				 $$scan_record{'scantron.doubleerror'});
                   6502:     	return (1,$currentphase);
                   6503:     }
                   6504:     return (0,$currentphase+1);
                   6505: }
                   6506: 
1.423     albertel 6507: =pod
                   6508: 
                   6509: =item scantron_get_maxbubble
                   6510: 
1.424     albertel 6511:    Returns the maximum number of bubble lines that are expected to
                   6512:    occur. Does this by walking the selected sequence rendering the
                   6513:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6514:    for what the current value of the problem counter is.
                   6515: 
                   6516:    Caches the result to $env{'form.scantron_maxbubble'}
                   6517: 
1.423     albertel 6518: =cut
                   6519: 
1.330     albertel 6520: sub scantron_get_maxbubble {    
1.435     foxr     6521: 
1.257     albertel 6522:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6523: 	$env{'form.scantron_maxbubble'}) {
                   6524: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6525:     }
1.330     albertel 6526: 
1.191     albertel 6527:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6528:     my (undef,undef,$sequence)=
1.257     albertel 6529: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6530: 
1.191     albertel 6531:     my $map=$navmap->getResourceByUrl($sequence);
                   6532:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6533: 
                   6534:     &Apache::lonxml::clear_problem_counter();
                   6535: 
1.435     foxr     6536:     my $uname       = $env{'form.student'};
                   6537:     my $udom        = $env{'form.userdom'};
                   6538:     my $cid         = $env{'request.course.id'};
                   6539:     my $total_lines = 0;
                   6540:     %bubble_lines_per_response = ();
                   6541: 
1.191     albertel 6542:     foreach my $resource (@resources) {
1.435     foxr     6543: 	my $symb = $resource->symb();
1.330     albertel 6544: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6545: 					('symb' => $resource->symb()),
                   6546: 					('grade_target' => 'analyze'),
                   6547: 					('grade_courseid' => $cid),
                   6548: 					('grade_domain' => $udom),
                   6549: 					('grade_username' => $uname));
1.436     albertel 6550: 	my (undef, $an) =
1.435     foxr     6551: 	    split(/_HASH_REF__/,$result, 2);
                   6552: 
                   6553: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6554: 
                   6555: 
                   6556: 
                   6557: 	foreach my $part_id (@{$analysis{'parts'}}) {
                   6558: 	    my $bubble_lines = $analysis{"$part_id.bubble_lines"}[0];
                   6559: 	    if (!$bubble_lines) {
                   6560: 		$bubble_lines = 1;
                   6561: 	    }
                   6562: 	    $bubble_lines_per_response{"$symb.$part_id"} = $bubble_lines;
                   6563: 	    $total_lines = $total_lines + $bubble_lines;
                   6564: 	}
                   6565: 
1.191     albertel 6566:     }
                   6567:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6568:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6569: 	$total_lines;
1.257     albertel 6570:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6571: }
                   6572: 
1.423     albertel 6573: =pod
                   6574: 
                   6575: =item scantron_validate_missingbubbles
                   6576: 
1.424     albertel 6577:    Validates all scanlines in the selected file to not have any
                   6578:    bubble lines with missing bubbles that haven't been verified as missing.
                   6579: 
1.423     albertel 6580: =cut
                   6581: 
1.157     albertel 6582: sub scantron_validate_missingbubbles {
                   6583:     my ($r,$currentphase) = @_;
                   6584:     #get student info
                   6585:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6586:     my %idmap=&username_to_idmap($classlist);
                   6587: 
                   6588:     #get scantron line setup
1.257     albertel 6589:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6590:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6591:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6592:     if (!$max_bubble) { $max_bubble=2**31; }
                   6593:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6594: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6595: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6596: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6597: 						 $scan_data);
                   6598: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6599: 	my @to_correct;
                   6600: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6601: 	    if ($missing > $max_bubble) { next; }
                   6602: 	    push(@to_correct,$missing);
                   6603: 	}
                   6604: 	if (@to_correct) {
                   6605: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6606: 				     $line,'missingbubble',\@to_correct);
                   6607: 	    return (1,$currentphase);
                   6608: 	}
                   6609: 
                   6610:     }
                   6611:     return (0,$currentphase+1);
                   6612: }
                   6613: 
1.423     albertel 6614: =pod
                   6615: 
                   6616: =item scantron_process_students
                   6617: 
                   6618:    Routine that does the actual grading of the bubble sheet information.
                   6619: 
                   6620:    The parsed scanline hash is added to %env 
                   6621: 
                   6622:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6623:    foreach resource , with the form data of
                   6624: 
                   6625: 	'submitted'     =>'scantron' 
                   6626: 	'grade_target'  =>'grade',
                   6627: 	'grade_username'=> username of student
                   6628: 	'grade_domain'  => domain of student
                   6629: 	'grade_courseid'=> of course
                   6630: 	'grade_symb'    => symb of resource to grade
                   6631: 
                   6632:     This triggers a grading pass. The problem grading code takes care
                   6633:     of converting the bubbled letter information (now in %env) into a
                   6634:     valid submission.
                   6635: 
                   6636: =cut
                   6637: 
1.82      albertel 6638: sub scantron_process_students {
1.75      albertel 6639:     my ($r) = @_;
1.257     albertel 6640:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6641:     my ($symb)=&get_symb($r);
1.81      albertel 6642:     if (!$symb) {return '';}
1.324     albertel 6643:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6644: 
1.257     albertel 6645:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6646:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6647:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6648:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6649:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6650:     my $map=$navmap->getResourceByUrl($sequence);
                   6651:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6652: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6653:     my $result= <<SCANTRONFORM;
1.81      albertel 6654: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6655:   <input type="hidden" name="command" value="scantron_configphase" />
                   6656:   $default_form_data
                   6657: SCANTRONFORM
1.82      albertel 6658:     $r->print($result);
                   6659: 
                   6660:     my @delayqueue;
1.140     albertel 6661:     my %completedstudents;
                   6662:     
1.200     albertel 6663:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6664:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6665:  				    'Scantron Progress',$count,
1.195     albertel 6666: 				    'inline',undef,'scantronupload');
1.140     albertel 6667:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6668: 					  'Processing first student');
                   6669:     my $start=&Time::HiRes::time();
1.158     albertel 6670:     my $i=-1;
1.200     albertel 6671:     my ($uname,$udom,$started);
1.157     albertel 6672:     while ($i<$scanlines->{'count'}) {
                   6673:  	($uname,$udom)=('','');
                   6674:  	$i++;
1.200     albertel 6675:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6676:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6677: 	if ($started) {
                   6678: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6679: 						     'last student');
                   6680: 	}
                   6681: 	$started=1;
1.157     albertel 6682:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6683:  						 $scan_data);
                   6684:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6685:  					      \%idmap,$i)) {
                   6686:   	    &scantron_add_delay(\@delayqueue,$line,
                   6687:  				'Unable to find a student that matches',1);
                   6688:  	    next;
                   6689:   	}
                   6690:  	if (exists $completedstudents{$uname}) {
                   6691:  	    &scantron_add_delay(\@delayqueue,$line,
                   6692:  				'Student '.$uname.' has multiple sheets',2);
                   6693:  	    next;
                   6694:  	}
                   6695:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6696: 
                   6697: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6698:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6699: 
                   6700: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6701: 	    &scantron_putfile($scanlines,$scan_data);
                   6702: 	}
1.161     albertel 6703: 	
                   6704: 	my $i=0;
1.83      albertel 6705: 	foreach my $resource (@resources) {
1.85      albertel 6706: 	    $i++;
1.193     albertel 6707: 	    my %form=('submitted'     =>'scantron',
                   6708: 		      'grade_target'  =>'grade',
                   6709: 		      'grade_username'=>$uname,
                   6710: 		      'grade_domain'  =>$udom,
1.257     albertel 6711: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6712: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6713: 	    if (exists($scan_record->{'scantron.CODE'})
                   6714: 		&& 
                   6715: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6716: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6717: 	    } else {
                   6718: 		$form{'CODE'}='';
1.193     albertel 6719: 	    }
                   6720: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6721: 	    if ($result ne '') {
                   6722: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6723: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6724: 	    }
1.213     albertel 6725: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6726: 	}
1.140     albertel 6727: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6728: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6729:     } continue {
1.330     albertel 6730: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6731: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6732:     }
1.140     albertel 6733:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6734: #    my $lasttime = &Time::HiRes::time()-$start;
                   6735: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6736: 
1.200     albertel 6737:     $r->print("</form>");
1.324     albertel 6738:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6739:     return '';
1.75      albertel 6740: }
1.157     albertel 6741: 
1.423     albertel 6742: =pod
                   6743: 
                   6744: =item scantron_upload_scantron_data
                   6745: 
                   6746:     Creates the screen for adding a new bubble sheet data file to a course.
                   6747: 
                   6748: =cut
                   6749: 
1.157     albertel 6750: sub scantron_upload_scantron_data {
                   6751:     my ($r)=@_;
1.257     albertel 6752:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6753:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6754: 							  'domainid',
                   6755: 							  'coursename');
1.257     albertel 6756:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6757: 						   'domainid');
1.324     albertel 6758:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6759:     $r->print(<<UPLOAD);
                   6760: <script type="text/javascript" language="javascript">
                   6761:     function checkUpload(formname) {
                   6762: 	if (formname.upfile.value == "") {
                   6763: 	    alert("Please use the browse button to select a file from your local directory.");
                   6764: 	    return false;
                   6765: 	}
                   6766: 	formname.submit();
                   6767:     }
                   6768: </script>
                   6769: 
                   6770: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6771: $default_form_data
1.181     albertel 6772: <table>
                   6773: <tr><td>$select_link </td></tr>
                   6774: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6775: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6776: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6777: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6778: </table>
1.157     albertel 6779: <input name='command' value='scantronupload_save' type='hidden' />
                   6780: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6781: </form>
                   6782: UPLOAD
                   6783:     return '';
                   6784: }
                   6785: 
1.423     albertel 6786: =pod
                   6787: 
                   6788: =item scantron_upload_scantron_data_save
                   6789: 
                   6790:    Adds a provided bubble information data file to the course if user
                   6791:    has the correct privileges to do so.  
                   6792: 
                   6793: =cut
                   6794: 
1.157     albertel 6795: sub scantron_upload_scantron_data_save {
                   6796:     my($r)=@_;
1.324     albertel 6797:     my ($symb)=&get_symb($r,1);
1.182     albertel 6798:     my $doanotherupload=
                   6799: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6800: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6801: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6802: 	'</form>'."\n";
1.257     albertel 6803:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6804: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6805: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6806: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6807: 	if ($symb) {
1.324     albertel 6808: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6809: 	} else {
                   6810: 	    $r->print($doanotherupload);
                   6811: 	}
1.162     albertel 6812: 	return '';
                   6813:     }
1.257     albertel 6814:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6815:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6816:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6817:     #FIXME
                   6818:     #copied from lonnet::userfileupload()
                   6819:     #make that function able to target a specified course
                   6820:     # Replace Windows backslashes by forward slashes
                   6821:     $fname=~s/\\/\//g;
                   6822:     # Get rid of everything but the actual filename
                   6823:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6824:     # Replace spaces by underscores
                   6825:     $fname=~s/\s+/\_/g;
                   6826:     # Replace all other weird characters by nothing
                   6827:     $fname=~s/[^\w\.\-]//g;
                   6828:     # See if there is anything left
                   6829:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6830:     my $uploadedfile=$fname;
1.157     albertel 6831:     $fname='scantron_orig_'.$fname;
1.257     albertel 6832:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6833: 	$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 6834:     } else {
1.275     albertel 6835: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6836: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6837: 	    $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 6838: 	} else {
1.398     albertel 6839: 	    $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 6840: 	}
                   6841:     }
1.174     albertel 6842:     if ($symb) {
1.209     ng       6843: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6844:     } else {
1.182     albertel 6845: 	$r->print($doanotherupload);
1.174     albertel 6846:     }
1.157     albertel 6847:     return '';
                   6848: }
                   6849: 
1.423     albertel 6850: =pod
                   6851: 
                   6852: =item valid_file
                   6853: 
1.424     albertel 6854:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6855: 
                   6856: =cut
                   6857: 
1.202     albertel 6858: sub valid_file {
                   6859:     my ($requested_file)=@_;
                   6860:     foreach my $filename (sort(&scantron_filenames())) {
                   6861: 	if ($requested_file eq $filename) { return 1; }
                   6862:     }
                   6863:     return 0;
                   6864: }
                   6865: 
1.423     albertel 6866: =pod
                   6867: 
                   6868: =item scantron_download_scantron_data
                   6869: 
                   6870:    Shows a list of the three internal files (original, corrected,
                   6871:    skipped) for a specific bubble sheet data file that exists in the
                   6872:    course.
                   6873: 
                   6874: =cut
                   6875: 
1.202     albertel 6876: sub scantron_download_scantron_data {
                   6877:     my ($r)=@_;
1.324     albertel 6878:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6879:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6880:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6881:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6882:     if (! &valid_file($file)) {
                   6883: 	$r->print(<<ERROR);
                   6884: 	<p>
                   6885: 	    The requested file name was invalid.
                   6886:         </p>
                   6887: ERROR
1.324     albertel 6888: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6889: 	return;
                   6890:     }
                   6891:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6892:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6893:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6894:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6895:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6896:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6897:     $r->print(<<DOWNLOAD);
                   6898:     <p>
                   6899: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6900:     </p>
                   6901:     <p>
                   6902: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6903:     </p>
                   6904:     <p>
                   6905: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6906:     </p>
                   6907: DOWNLOAD
1.324     albertel 6908:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6909:     return '';
                   6910: }
1.157     albertel 6911: 
1.423     albertel 6912: =pod
                   6913: 
                   6914: =back
                   6915: 
                   6916: =cut
                   6917: 
1.75      albertel 6918: #-------- end of section for handling grading scantron forms -------
                   6919: #
                   6920: #-------------------------------------------------------------------
                   6921: 
1.72      ng       6922: #-------------------------- Menu interface -------------------------
                   6923: #
                   6924: #--- Show a Grading Menu button - Calls the next routine ---
                   6925: sub show_grading_menu_form {
1.324     albertel 6926:     my ($symb)=@_;
1.125     ng       6927:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6928: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6929: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6930: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6931: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6932: 	'</form>'."\n";
                   6933:     return $result;
                   6934: }
                   6935: 
1.77      ng       6936: # -- Retrieve choices for grading form
                   6937: sub savedState {
                   6938:     my %savedState = ();
1.257     albertel 6939:     if ($env{'form.saveState'}) {
                   6940: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6941: 	    my ($key,$value) = split(/=/,$_,2);
                   6942: 	    $savedState{$key} = $value;
                   6943: 	}
                   6944:     }
                   6945:     return \%savedState;
                   6946: }
1.76      ng       6947: 
1.443     banghart 6948: sub grading_menu {
                   6949:     my ($request) = @_;
                   6950:     my ($symb)=&get_symb($request);
                   6951:     if (!$symb) {return '';}
                   6952:     my $probTitle = &Apache::lonnet::gettitle($symb);
                   6953:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
                   6954: 
                   6955:     #
                   6956:     # Define menu data
1.444   ! banghart 6957:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
        !          6958:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
        !          6959:     $request->print($table);
1.443     banghart 6960:     my %fields = ('symb'=>&Apache::lonenc::check_encrypt($symb),
                   6961:                   'handgrade'=>$hdgrade,
                   6962:                   'probTitle'=>$probTitle,
                   6963:                   'command'=>'submit_options',
                   6964:                   'saveState'=>"",
                   6965:                   'gradingMenu'=>1,
                   6966:                   'showgrading'=>"yes");
                   6967:     my $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   6968:     my @menu = ({ url => $url,
                   6969:                      name => &mt('Manual Grading/View Submissions'),
                   6970:                      short_description => 
                   6971:     &mt('Start the process of hand grading submissions.'),
                   6972:                  });
                   6973:     $fields{'command'} = 'csvform';
                   6974:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   6975:     push (@menu, { url => $url,
                   6976:                    name => &mt('Upload Scores'),
                   6977:                    short_description => 
                   6978:             &mt('Specify a file containing the class scores for current resource.')});
                   6979:     $fields{'command'} = 'processclicker';
                   6980:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   6981:     push (@menu, { url => $url,
                   6982:                    name => &mt('Process Clicker'),
                   6983:                    short_description => 
                   6984:             &mt('Specify a file containing the clicker information for this resource.')});
                   6985:     $fields{'command'} = 'scantron_selectphase';
                   6986:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   6987:     push (@menu, { url => $url,
                   6988:                    name => &mt('Grade Scantron Forms'),
                   6989:                    short_description => 
                   6990:             &mt('')});
                   6991:     $fields{'command'} = 'verify';
                   6992:     $url = &Apache::lonhtmlcommon::build_url('grades/',\%fields);
                   6993:     push (@menu, { url => $url,
1.444   ! banghart 6994:                    jscript => ' onChange="javascript:checkReceiptNo(this.form,\'OK\')" ',
1.443     banghart 6995:                    name => &mt('Verify Receipt'),
                   6996:                    short_description => 
                   6997:             &mt('')});
                   6998:     $fields{'command'} = 'manage';
                   6999:     $url = &Apache::lonhtmlcommon::build_url('/adm/helper/resettimes.helper',\%fields);
                   7000:     push (@menu, { url => $url,
                   7001:                    name => &mt('Manage Access Times'),
                   7002:                    short_description => 
                   7003:             &mt('')});
                   7004:     $fields{'command'} = 'view';
                   7005:     $url = &Apache::lonhtmlcommon::build_url('/adm/pickcode',\%fields);
                   7006:     push (@menu, { url => $url,
                   7007:                    name => &mt('View Saved CODEs'),
                   7008:                    short_description => 
                   7009:             &mt('')});
                   7010: 
                   7011:     #
                   7012:     # Create the menu
                   7013:     my $Str;
1.444   ! banghart 7014:     # $Str .= '<h2>'.&mt('Please select a grading task').'</h2>';
        !          7015:     $Str .= '<form method="post" action="adm/grades" name="gradingMenu">';
1.443     banghart 7016:     foreach my $menudata (@menu) {
1.444   ! banghart 7017:         $Str .='    <h3><a '.
        !          7018:             $menudata->{'jscript'}.
        !          7019:             ' href="'.
1.443     banghart 7020:             $menudata->{'url'}.'" >'.
                   7021:             $menudata->{'name'}."</a></h3>\n";
1.444   ! banghart 7022:         if ($menudata->{'name'} eq &mt('Verify Receipt')) {
        !          7023:             $Str .= ' receipt: 156-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />';
        !          7024:         }
1.443     banghart 7025:         $Str .= '    '.('&nbsp;'x8).$menudata->{'short_description'}.
                   7026:             "\n";
                   7027:     }
                   7028:     $Str .="</dl>\n";
1.444   ! banghart 7029:     $Str .="</form>\n";
1.443     banghart 7030:     $request->print(<<GRADINGMENUJS);
                   7031: <script type="text/javascript" language="javascript">
                   7032:     function checkChoice(formname,val,cmdx) {
                   7033: 	if (val <= 2) {
                   7034: 	    var cmd = radioSelection(formname.radioChoice);
                   7035: 	    var cmdsave = cmd;
                   7036: 	} else {
                   7037: 	    cmd = cmdx;
                   7038: 	    cmdsave = 'submission';
                   7039: 	}
                   7040: 	formname.command.value = cmd;
                   7041: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
                   7042: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
                   7043: 	if (val < 5) formname.submit();
                   7044: 	if (val == 5) {
                   7045: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7046: 	    formname.submit();
                   7047: 	}
                   7048: 	if (val < 7) formname.submit();
                   7049:     }
                   7050: 
                   7051:     function checkReceiptNo(formname,nospace) {
                   7052: 	var receiptNo = formname.receipt.value;
                   7053: 	var checkOpt = false;
                   7054: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7055: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7056: 	if (checkOpt) {
                   7057: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7058: 	    formname.receipt.value = "";
                   7059: 	    formname.receipt.focus();
                   7060: 	    return false;
                   7061: 	}
                   7062: 	return true;
                   7063:     }
                   7064: </script>
                   7065: GRADINGMENUJS
                   7066:     &commonJSfunctions($request);
                   7067:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
                   7068:     $result.=$table;
                   7069:     my (undef,$sections) = &getclasslist('all','0');
                   7070:     my $savedState = &savedState();
                   7071:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
                   7072:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
                   7073:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
                   7074:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
                   7075: 
                   7076:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   7077: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
                   7078: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7079: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" ue="" />'."\n".
                   7080: 	'<input type="hidden" name="saveState"   value="" />'."\n".
                   7081: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
                   7082: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7083: 
                   7084:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7085: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
                   7086: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
                   7087: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7088: 
                   7089:     $result.='<table width="100%" border="0">';
                   7090:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7091:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7092: #    $result.='<td>Groups</td>';
                   7093:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7094:     $result.='</tr>';
                   7095:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
                   7096: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
                   7097:     if (ref($sections)) {
                   7098: 	foreach (sort (@$sections)) {
                   7099: 	    $result.='<option value="'.$_.'" '.
                   7100: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
                   7101: 	}
                   7102:     }
                   7103:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
                   7104:     return $Str;    
                   7105: }
                   7106: 
                   7107: 
                   7108: #--- Displays the submissions first page -------
                   7109: sub submit_options {
1.72      ng       7110:     my ($request) = @_;
1.324     albertel 7111:     my ($symb)=&get_symb($request);
1.72      ng       7112:     if (!$symb) {return '';}
1.76      ng       7113:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       7114: 
                   7115:     $request->print(<<GRADINGMENUJS);
                   7116: <script type="text/javascript" language="javascript">
1.116     ng       7117:     function checkChoice(formname,val,cmdx) {
                   7118: 	if (val <= 2) {
                   7119: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       7120: 	    var cmdsave = cmd;
1.116     ng       7121: 	} else {
                   7122: 	    cmd = cmdx;
1.118     ng       7123: 	    cmdsave = 'submission';
1.116     ng       7124: 	}
                   7125: 	formname.command.value = cmd;
1.118     ng       7126: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 7127: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       7128: 	if (val < 5) formname.submit();
                   7129: 	if (val == 5) {
1.72      ng       7130: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   7131: 	    formname.submit();
                   7132: 	}
1.238     albertel 7133: 	if (val < 7) formname.submit();
1.72      ng       7134:     }
                   7135: 
                   7136:     function checkReceiptNo(formname,nospace) {
                   7137: 	var receiptNo = formname.receipt.value;
                   7138: 	var checkOpt = false;
                   7139: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   7140: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   7141: 	if (checkOpt) {
                   7142: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   7143: 	    formname.receipt.value = "";
                   7144: 	    formname.receipt.focus();
                   7145: 	    return false;
                   7146: 	}
                   7147: 	return true;
                   7148:     }
                   7149: </script>
                   7150: GRADINGMENUJS
1.118     ng       7151:     &commonJSfunctions($request);
1.398     albertel 7152:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 7153:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       7154:     $result.=$table;
1.76      ng       7155:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       7156:     my $savedState = &savedState();
1.118     ng       7157:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       7158:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       7159:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       7160:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       7161: 
                   7162:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 7163: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       7164: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   7165: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       7166: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       7167: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       7168: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       7169: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   7170: 
1.326     albertel 7171:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   7172: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       7173: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       7174: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   7175: 
1.326     albertel 7176:     $result.='<table width="100%" border="0">';
1.442     banghart 7177:     $result.='<tr bgcolor="#ffffe6" valign="top">'."\n";
                   7178:     $result.='<td><b>'.&mt('Sections').'</b></td>';
                   7179: #    $result.='<td>Groups</td>';
                   7180:     $result.='<td><b>'.&mt('Access Status').'</td>'."\n";
                   7181:     $result.='</tr>';
1.116     ng       7182:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.442     banghart 7183: 	'&nbsp;<select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7184:     if (ref($sections)) {
1.155     albertel 7185: 	foreach (sort (@$sections)) {
                   7186: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7187: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7188: 	}
1.116     ng       7189:     }
1.401     albertel 7190:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.442     banghart 7191: #    $result.= '</td><td>'."\n";
                   7192: #    $result.='Put group select here'."\n";
                   7193:     $result.='</td><td>'."\n";
                   7194:     $result.=&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,3,undef,'mult');
1.72      ng       7195: 
1.116     ng       7196:     $result.='</td></tr>';
                   7197: 
1.442     banghart 7198:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="3"><label>'.
1.118     ng       7199: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7200: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7201: 	'</label> <select name="submitonly">'.
1.145     albertel 7202: 	'<option value="yes" '.
1.401     albertel 7203: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7204: 	'<option value="queued" '.
1.401     albertel 7205: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7206: 	'<option value="graded" '.
1.401     albertel 7207: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7208: 	'<option value="incorrect" '.
1.401     albertel 7209: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7210: 	'<option value="all" '.
1.401     albertel 7211: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7212: 
1.442     banghart 7213:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.288     albertel 7214: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7215: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7216: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7217: 
1.442     banghart 7218:     $result.='<tr bgcolor="#ffffe6" valign="top"><td colspan="2">'.
1.288     albertel 7219: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7220: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7221: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7222: 
1.442     banghart 7223:     $result.='<tr bgcolor="#ffffe6"><td colspan="2"><br />'.
1.126     ng       7224: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7225: 	'</td></tr></table>'."\n";
                   7226: 
                   7227:     $result.='</td><td valign="top">';
                   7228: 
1.326     albertel 7229:     $result.='<table width="100%" border="0">';
1.116     ng       7230:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      7231: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7232: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       7233: 
1.404     www      7234:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7235:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7236:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7237: 
1.75      albertel 7238:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7239: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7240: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7241: 
1.257     albertel 7242:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7243: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7244: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7245: 	    ' '.&mt('receipt').': '.
1.257     albertel 7246: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7247: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7248: 	    '</td></tr>'."\n";
                   7249:     } 
1.238     albertel 7250:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7251: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7252: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7253:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7254: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7255: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7256: 
1.401     albertel 7257:     $result.='</table>'."\n".
1.72      ng       7258: 	'</td></tr></table>'."\n".
1.401     albertel 7259: 	'</td></tr></table></form>'."\n";
1.44      ng       7260:     return $result;
1.2       albertel 7261: }
                   7262: 
1.285     albertel 7263: sub reset_perm {
                   7264:     undef(%perm);
                   7265: }
                   7266: 
                   7267: sub init_perm {
                   7268:     &reset_perm();
1.300     albertel 7269:     foreach my $test_perm ('vgr','mgr','opa') {
                   7270: 
                   7271: 	my $scope = $env{'request.course.id'};
                   7272: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7273: 
                   7274: 	    $scope .= '/'.$env{'request.course.sec'};
                   7275: 	    if ( $perm{$test_perm}=
                   7276: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7277: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7278: 	    } else {
                   7279: 		delete($perm{$test_perm});
                   7280: 	    }
1.285     albertel 7281: 	}
                   7282:     }
                   7283: }
                   7284: 
1.400     www      7285: sub gather_clicker_ids {
1.408     albertel 7286:     my %clicker_ids;
1.400     www      7287: 
                   7288:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7289: 
                   7290:     # Set up a couple variables.
1.407     albertel 7291:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7292:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7293:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7294: 
1.407     albertel 7295:     foreach my $student (keys(%$classlist)) {
1.438     www      7296:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7297:         my $username = $classlist->{$student}->[$username_idx];
                   7298:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7299:         my $clickers =
1.408     albertel 7300: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7301:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7302:             $id=~s/^[\#0]+//;
1.421     www      7303:             $id=~s/[\-\:]//g;
1.407     albertel 7304:             if (exists($clicker_ids{$id})) {
1.408     albertel 7305: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7306:             } else {
1.408     albertel 7307: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7308:             }
                   7309:         }
                   7310:     }
1.407     albertel 7311:     return %clicker_ids;
1.400     www      7312: }
                   7313: 
1.402     www      7314: sub gather_adv_clicker_ids {
1.408     albertel 7315:     my %clicker_ids;
1.402     www      7316:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7317:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7318:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7319:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7320:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7321:             my ($puname,$pudom)=split(/\:/,$person);
                   7322:             my $clickers =
1.408     albertel 7323: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7324:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7325: 		$id=~s/^[\#0]+//;
1.421     www      7326:                 $id=~s/[\-\:]//g;
1.408     albertel 7327: 		if (exists($clicker_ids{$id})) {
                   7328: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7329: 		} else {
                   7330: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7331: 		}
1.405     www      7332:             }
1.402     www      7333:         }
                   7334:     }
1.407     albertel 7335:     return %clicker_ids;
1.402     www      7336: }
                   7337: 
1.413     www      7338: sub clicker_grading_parameters {
                   7339:     return ('gradingmechanism' => 'scalar',
                   7340:             'upfiletype' => 'scalar',
                   7341:             'specificid' => 'scalar',
                   7342:             'pcorrect' => 'scalar',
                   7343:             'pincorrect' => 'scalar');
                   7344: }
                   7345: 
1.400     www      7346: sub process_clicker {
                   7347:     my ($r)=@_;
                   7348:     my ($symb)=&get_symb($r);
                   7349:     if (!$symb) {return '';}
                   7350:     my $result=&checkforfile_js();
                   7351:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7352:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7353:     $result.=$table;
                   7354:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7355:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7356:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7357:         '.</b></td></tr>'."\n";
                   7358:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7359: # Attempt to restore parameters from last session, set defaults if not present
                   7360:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7361:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7362:                                                  \%Saveable_Parameters);
                   7363:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7364:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7365:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7366:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7367: 
                   7368:     my %checked;
                   7369:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7370:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7371:           $checked{$gradingmechanism}="checked='checked'";
                   7372:        }
                   7373:     }
                   7374: 
1.400     www      7375:     my $upload=&mt("Upload File");
                   7376:     my $type=&mt("Type");
1.402     www      7377:     my $attendance=&mt("Award points just for participation");
                   7378:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7379:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7380:     my $pcorrect=&mt("Percentage points for correct solution");
                   7381:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7382:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7383: 						   ('iclicker' => 'i>clicker',
                   7384:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7385:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7386:     $result.=<<ENDUPFORM;
1.402     www      7387: <script type="text/javascript">
                   7388: function sanitycheck() {
                   7389: // Accept only integer percentages
                   7390:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7391:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7392: // Find out grading choice
                   7393:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7394:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7395:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7396:       }
                   7397:    }
                   7398: // By default, new choice equals user selection
                   7399:    newgradingchoice=gradingchoice;
                   7400: // Not good to give more points for false answers than correct ones
                   7401:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7402:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7403:    }
                   7404: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7405:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7406:       document.forms.gradesupload.pcorrect.value=100;
                   7407:       document.forms.gradesupload.pincorrect.value=100;
                   7408:    }
                   7409: // If the values are different, cannot be attendance only
                   7410:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7411:        (gradingchoice=='attendance')) {
                   7412:        newgradingchoice='personnel';
                   7413:    }
                   7414: // Change grading choice to new one
                   7415:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7416:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7417:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7418:       } else {
                   7419:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7420:       }
                   7421:    }
                   7422: // Remember the old state
                   7423:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7424: }
                   7425: </script>
1.400     www      7426: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7427: <input type="hidden" name="symb" value="$symb" />
                   7428: <input type="hidden" name="command" value="processclickerfile" />
                   7429: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7430: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7431: <input type="file" name="upfile" size="50" />
                   7432: <br /><label>$type: $selectform</label>
1.413     www      7433: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7434: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7435: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7436: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7437: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7438: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7439: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7440: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7441: </form>
                   7442: ENDUPFORM
                   7443:     $result.='</td></tr></table>'."\n".
                   7444:              '</td></tr></table><br /><br />'."\n";
                   7445:     $result.=&show_grading_menu_form($symb);
                   7446:     return $result;
                   7447: }
                   7448: 
                   7449: sub process_clicker_file {
                   7450:     my ($r)=@_;
                   7451:     my ($symb)=&get_symb($r);
                   7452:     if (!$symb) {return '';}
1.413     www      7453: 
                   7454:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7455:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7456:                                               \%Saveable_Parameters);
                   7457: 
1.400     www      7458:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7459:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7460: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7461: 	return $result.&show_grading_menu_form($symb);
1.404     www      7462:     }
1.407     albertel 7463:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7464:     my %correct_ids;
1.404     www      7465:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7466: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7467:     }
                   7468:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7469: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7470: 	   $correct_id=~tr/a-z/A-Z/;
                   7471: 	   $correct_id=~s/\s//gs;
                   7472: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7473:            $correct_id=~s/[\-\:]//g;
1.414     www      7474:            if ($correct_id) {
                   7475: 	      $correct_ids{$correct_id}='specified';
                   7476:            }
                   7477:         }
1.400     www      7478:     }
1.404     www      7479:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7480: 	$result.=&mt('Score based on attendance only');
1.404     www      7481:     } else {
1.408     albertel 7482: 	my $number=0;
1.411     www      7483: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7484: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7485: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7486: 	    if ($correct_ids{$id} eq 'specified') {
                   7487: 		$result.=&mt('specified');
                   7488: 	    } else {
                   7489: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7490: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7491: 	    }
                   7492: 	    $number++;
                   7493: 	}
1.411     www      7494:         $result.="</p>\n";
1.408     albertel 7495: 	if ($number==0) {
                   7496: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7497: 	    return $result.&show_grading_menu_form($symb);
                   7498: 	}
1.404     www      7499:     }
1.405     www      7500:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7501:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7502: 		     '<span class="LC_error">',
                   7503: 		     '</span>',
                   7504: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7505:         return $result.&show_grading_menu_form($symb);
                   7506:     }
1.410     www      7507: 
                   7508: # Were able to get all the info needed, now analyze the file
                   7509: 
1.411     www      7510:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7511:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7512:     my $heading=&mt('Scanning clicker file');
                   7513:     $result.=(<<ENDHEADER);
                   7514: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7515: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7516: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7517: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7518: <input type="hidden" name="symb" value="$symb" />
                   7519: <input type="hidden" name="command" value="assignclickergrades" />
                   7520: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7521: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7522: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7523: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7524: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7525: ENDHEADER
1.408     albertel 7526:     my %responses;
                   7527:     my @questiontitles;
1.405     www      7528:     my $errormsg='';
                   7529:     my $number=0;
                   7530:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7531: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7532:     }
1.419     www      7533:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7534:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7535:     }
1.411     www      7536:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7537:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.443     banghart 7538:              &mt('Awarding [_1] percent for corrion(s)',$number).'<br />'.
                   7539:              '<input type="hidden" name="number" value="'.$number.'" />'.
1.411     www      7540:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7541:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7542:              '<br />';
1.414     www      7543: # Remember Question Titles
                   7544: # FIXME: Possibly need delimiter other than ":"
                   7545:     for (my $i=0;$i<$number;$i++) {
                   7546:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7547:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7548:     }
1.411     www      7549:     my $correct_count=0;
                   7550:     my $student_count=0;
                   7551:     my $unknown_count=0;
1.414     www      7552: # Match answers with usernames
                   7553: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7554:     foreach my $id (keys(%responses)) {
1.410     www      7555:        if ($correct_ids{$id}) {
1.414     www      7556:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7557:           $correct_count++;
1.410     www      7558:        } elsif ($clicker_ids{$id}) {
1.437     www      7559:           if ($clicker_ids{$id}=~/\,/) {
                   7560: # More than one user with the same clicker!
                   7561:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7562:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7563:                            "<select name='multi".$id."'>";
                   7564:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7565:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7566:              }
                   7567:              $result.='</select>';
                   7568:              $unknown_count++;
                   7569:           } else {
                   7570: # Good: found one and only one user with the right clicker
                   7571:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7572:              $student_count++;
                   7573:           }
1.410     www      7574:        } else {
1.411     www      7575:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7576:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7577:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7578:                    "\n".&mt("Domain").": ".
                   7579:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7580:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7581:           $unknown_count++;
1.410     www      7582:        }
1.405     www      7583:     }
1.412     www      7584:     $result.='<hr />'.
                   7585:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7586:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7587:        if ($correct_count==0) {
                   7588:           $errormsg.="Found no correct answers answers for grading!";
                   7589:        } elsif ($correct_count>1) {
1.414     www      7590:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7591:        }
                   7592:     }
1.428     www      7593:     if ($number<1) {
                   7594:        $errormsg.="Found no questions.";
                   7595:     }
1.412     www      7596:     if ($errormsg) {
                   7597:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7598:     } else {
                   7599:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7600:     }
                   7601:     $result.='</form></td></tr></table>'."\n".
1.410     www      7602:              '</td></tr></table><br /><br />'."\n";
1.404     www      7603:     return $result.&show_grading_menu_form($symb);
1.400     www      7604: }
                   7605: 
1.405     www      7606: sub iclicker_eval {
1.406     www      7607:     my ($questiontitles,$responses)=@_;
1.405     www      7608:     my $number=0;
                   7609:     my $errormsg='';
                   7610:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7611:         my %components=&Apache::loncommon::record_sep($line);
                   7612:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7613: 	if ($entries[0] eq 'Question') {
                   7614: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7615: 		$$questiontitles[$number]=$entries[$i];
                   7616: 		$number++;
                   7617: 	    }
                   7618: 	}
                   7619: 	if ($entries[0]=~/^\#/) {
                   7620: 	    my $id=$entries[0];
                   7621: 	    my @idresponses;
                   7622: 	    $id=~s/^[\#0]+//;
                   7623: 	    for (my $i=0;$i<$number;$i++) {
                   7624: 		my $idx=3+$i*6;
                   7625: 		push(@idresponses,$entries[$idx]);
                   7626: 	    }
                   7627: 	    $$responses{$id}=join(',',@idresponses);
                   7628: 	}
1.405     www      7629:     }
                   7630:     return ($errormsg,$number);
                   7631: }
                   7632: 
1.419     www      7633: sub interwrite_eval {
                   7634:     my ($questiontitles,$responses)=@_;
                   7635:     my $number=0;
                   7636:     my $errormsg='';
1.420     www      7637:     my $skipline=1;
                   7638:     my $questionnumber=0;
                   7639:     my %idresponses=();
1.419     www      7640:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7641:         my %components=&Apache::loncommon::record_sep($line);
                   7642:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7643:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7644:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7645:         next if $skipline;
                   7646:         if ($entries[0]!=$questionnumber) {
                   7647:            $questionnumber=$entries[0];
                   7648:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7649:            $number++;
1.419     www      7650:         }
1.420     www      7651:         my $id=$entries[4];
                   7652:         $id=~s/^[\#0]+//;
1.421     www      7653:         $id=~s/^v\d*\://i;
                   7654:         $id=~s/[\-\:]//g;
1.420     www      7655:         $idresponses{$id}[$number]=$entries[6];
                   7656:     }
                   7657:     foreach my $id (keys %idresponses) {
                   7658:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7659:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7660:     }
                   7661:     return ($errormsg,$number);
                   7662: }
                   7663: 
1.414     www      7664: sub assign_clicker_grades {
                   7665:     my ($r)=@_;
                   7666:     my ($symb)=&get_symb($r);
                   7667:     if (!$symb) {return '';}
1.416     www      7668: # See which part we are saving to
                   7669:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7670: # FIXME: This should probably look for the first handgradeable part
                   7671:     my $part=$$partlist[0];
                   7672: # Start screen output
1.414     www      7673:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7674: 
1.414     www      7675:     my $heading=&mt('Assigning grades based on clicker file');
                   7676:     $result.=(<<ENDHEADER);
                   7677: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7678: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7679: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7680: ENDHEADER
                   7681: # Get correct result
                   7682: # FIXME: Possibly need delimiter other than ":"
                   7683:     my @correct=();
1.415     www      7684:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7685:     my $number=$env{'form.number'};
                   7686:     if ($gradingmechanism ne 'attendance') {
1.414     www      7687:        foreach my $key (keys(%env)) {
                   7688:           if ($key=~/^form\.correct\:/) {
                   7689:              my @input=split(/\,/,$env{$key});
                   7690:              for (my $i=0;$i<=$#input;$i++) {
                   7691:                  if (($correct[$i]) && ($input[$i]) &&
                   7692:                      ($correct[$i] ne $input[$i])) {
                   7693:                     $result.='<br /><span class="LC_warning">'.
                   7694:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7695:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7696:                  } elsif ($input[$i]) {
                   7697:                     $correct[$i]=$input[$i];
                   7698:                  }
                   7699:              }
                   7700:           }
                   7701:        }
1.415     www      7702:        for (my $i=0;$i<$number;$i++) {
1.414     www      7703:           if (!$correct[$i]) {
                   7704:              $result.='<br /><span class="LC_error">'.
                   7705:                       &mt('No correct result given for question "[_1]"!',
                   7706:                           $env{'form.question:'.$i}).'</span>';
                   7707:           }
                   7708:        }
                   7709:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7710:     }
                   7711: # Start grading
1.415     www      7712:     my $pcorrect=$env{'form.pcorrect'};
                   7713:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7714:     my $storecount=0;
1.415     www      7715:     foreach my $key (keys(%env)) {
1.420     www      7716:        my $user='';
1.415     www      7717:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7718:           $user=$1;
                   7719:        }
                   7720:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7721:           my $id=$1;
                   7722:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7723:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7724:           } elsif ($env{'form.multi'.$id}) {
                   7725:              $user=$env{'form.multi'.$id};
1.420     www      7726:           }
                   7727:        }
                   7728:        if ($user) { 
1.415     www      7729:           my @answer=split(/\,/,$env{$key});
                   7730:           my $sum=0;
                   7731:           for (my $i=0;$i<$number;$i++) {
                   7732:              if ($answer[$i]) {
                   7733:                 if ($gradingmechanism eq 'attendance') {
                   7734:                    $sum+=$pcorrect;
                   7735:                 } else {
                   7736:                    if ($answer[$i] eq $correct[$i]) {
                   7737:                       $sum+=$pcorrect;
                   7738:                    } else {
                   7739:                       $sum+=$pincorrect;
                   7740:                    }
                   7741:                 }
                   7742:              }
                   7743:           }
1.416     www      7744:           my $ave=$sum/(100*$number);
                   7745: # Store
                   7746:           my ($username,$domain)=split(/\:/,$user);
                   7747:           my %grades=();
                   7748:           $grades{"resource.$part.solved"}='correct_by_override';
                   7749:           $grades{"resource.$part.awarded"}=$ave;
                   7750:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7751:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7752:                                                  $env{'request.course.id'},
                   7753:                                                  $domain,$username);
                   7754:           if ($returncode ne 'ok') {
                   7755:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7756:           } else {
                   7757:              $storecount++;
                   7758:           }
1.415     www      7759:        }
                   7760:     }
                   7761: # We are done
1.416     www      7762:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7763:              '</td></tr></table>'."\n".
1.414     www      7764:              '</td></tr></table><br /><br />'."\n";
                   7765:     return $result.&show_grading_menu_form($symb);
                   7766: }
                   7767: 
1.1       albertel 7768: sub handler {
1.41      ng       7769:     my $request=$_[0];
1.102     albertel 7770: 
1.434     albertel 7771:     &reset_caches();
1.257     albertel 7772:     if ($env{'browser.mathml'}) {
1.141     www      7773: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7774:     } else {
1.141     www      7775: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7776:     }
                   7777:     $request->send_http_header;
1.44      ng       7778:     return '' if $request->header_only;
1.41      ng       7779:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7780:     my $symb=&get_symb($request,1);
1.160     albertel 7781:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7782:     my $command=$commands[0];
                   7783:     if ($#commands > 0) {
                   7784: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7785:     }
1.353     albertel 7786:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7787:     if ($symb eq '' && $command eq '') {
1.257     albertel 7788: 	if ($env{'user.adv'}) {
                   7789: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7790: 		($env{'form.codethree'})) {
                   7791: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7792: 		    $env{'form.codethree'};
1.41      ng       7793: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7794: 		    &Apache::lonnet::checkin($token);
                   7795: 		if ($tsymb) {
1.137     albertel 7796: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7797: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7798: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7799: 					  ('grade_username' => $tuname,
                   7800: 					   'grade_domain' => $tudom,
                   7801: 					   'grade_courseid' => $tcrsid,
                   7802: 					   'grade_symb' => $tsymb)));
1.41      ng       7803: 		    } else {
1.45      ng       7804: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7805: 		    }
1.41      ng       7806: 		} else {
1.45      ng       7807: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7808: 		}
1.14      www      7809: 	    } else {
1.41      ng       7810: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7811: 	    }
                   7812: 	}
                   7813:     } else {
1.285     albertel 7814: 	&init_perm();
1.104     albertel 7815: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7816: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7817: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7818: 	    &pickStudentPage($request);
1.103     albertel 7819: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7820: 	    &displayPage($request);
1.104     albertel 7821: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7822: 	    &updateGradeByPage($request);
1.104     albertel 7823: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7824: 	    &processGroup($request);
1.104     albertel 7825: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.443     banghart 7826: 	    $request->print(&grading_menu($request));
                   7827: 	} elsif ($command eq 'submit_options' && $perm{'vgr'}) {
                   7828: 	    $request->print(&submit_options($request));
1.104     albertel 7829: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7830: 	    $request->print(&viewgrades($request));
1.104     albertel 7831: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7832: 	    $request->print(&processHandGrade($request));
1.106     albertel 7833: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7834: 	    $request->print(&editgrades($request));
1.106     albertel 7835: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7836: 	    $request->print(&verifyreceipt($request));
1.400     www      7837:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7838:             $request->print(&process_clicker($request));
                   7839:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7840:             $request->print(&process_clicker_file($request));
1.414     www      7841:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7842:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7843: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7844: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7845: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7846: 	    $request->print(&csvupload($request));
1.106     albertel 7847: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7848: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7849: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7850: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7851: 		$request->print(&csvuploadoptions($request));
1.41      ng       7852: 	    } else {
1.257     albertel 7853: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7854: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7855: 		} else {
1.257     albertel 7856: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7857: 		}
                   7858: 		$request->print(&csvuploadmap($request));
                   7859: 	    }
1.246     albertel 7860: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7861: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7862: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7863: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7864:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7865:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7866: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7867: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7868: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7869: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7870:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7871:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7872: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7873:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7874:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7875:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7876: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7877:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7878:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7879: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7880:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7881: 	} elsif ($command) {
1.157     albertel 7882: 	    $request->print("Access Denied ($command)");
1.26      albertel 7883: 	}
1.2       albertel 7884:     }
1.353     albertel 7885:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 7886:     &reset_caches();
1.44      ng       7887:     return '';
                   7888: }
                   7889: 
1.1       albertel 7890: 1;
                   7891: 
1.13      albertel 7892: __END__;

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