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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.439   ! albertel    4: # $Id: grades.pm,v 1.438 2007/09/02 02:10:31 www 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: 	}
                    352:        
1.122     ng        353:     }
1.118     ng        354:     return $answer;
                    355: }
                    356: 
                    357: #-- A couple of common js functions
                    358: sub commonJSfunctions {
                    359:     my $request = shift;
                    360:     $request->print(<<COMMONJSFUNCTIONS);
                    361: <script type="text/javascript" language="javascript">
                    362:     function radioSelection(radioButton) {
                    363: 	var selection=null;
                    364: 	if (radioButton.length > 1) {
                    365: 	    for (var i=0; i<radioButton.length; i++) {
                    366: 		if (radioButton[i].checked) {
                    367: 		    return radioButton[i].value;
                    368: 		}
                    369: 	    }
                    370: 	} else {
                    371: 	    if (radioButton.checked) return radioButton.value;
                    372: 	}
                    373: 	return selection;
                    374:     }
                    375: 
                    376:     function pullDownSelection(selectOne) {
                    377: 	var selection="";
                    378: 	if (selectOne.length > 1) {
                    379: 	    for (var i=0; i<selectOne.length; i++) {
                    380: 		if (selectOne[i].selected) {
                    381: 		    return selectOne[i].value;
                    382: 		}
                    383: 	    }
                    384: 	} else {
1.138     albertel  385:             // only one value it must be the selected one
                    386: 	    return selectOne.value;
1.118     ng        387: 	}
                    388:     }
                    389: </script>
                    390: COMMONJSFUNCTIONS
                    391: }
                    392: 
1.44      ng        393: #--- Dumps the class list with usernames,list of sections,
                    394: #--- section, ids and fullnames for each user.
                    395: sub getclasslist {
1.76      ng        396:     my ($getsec,$filterlist) = @_;
1.291     albertel  397:     my @getsec;
                    398:     if (!ref($getsec)) {
                    399: 	if ($getsec ne '' && $getsec ne 'all') {
                    400: 	    @getsec=($getsec);
                    401: 	}
                    402:     } else {
                    403: 	@getsec=@{$getsec};
                    404:     }
                    405:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    406: 
1.56      matthew   407:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  408:     # Bail out if we were unable to get the classlist
1.56      matthew   409:     return if (! defined($classlist));
                    410:     #
                    411:     my %sections;
                    412:     my %fullnames;
1.205     matthew   413:     foreach my $student (keys(%$classlist)) {
                    414:         my $end      = 
                    415:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    416:         my $start    = 
                    417:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    418:         my $id       = 
                    419:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    420:         my $section  = 
                    421:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    422:         my $fullname = 
                    423:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    424:         my $status   = 
                    425:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        426: 	# filter students according to status selected
1.257     albertel  427: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    428: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   429: 		delete ($classlist->{$student});
1.76      ng        430: 		next;
                    431: 	    }
                    432: 	}
1.205     matthew   433: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  434: 	if (&canview($section)) {
1.291     albertel  435: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  436: 		$sections{$section}++;
1.205     matthew   437: 		$fullnames{$student}=$fullname;
1.103     albertel  438: 	    } else {
1.205     matthew   439: 		delete($classlist->{$student});
1.103     albertel  440: 	    }
                    441: 	} else {
1.205     matthew   442: 	    delete($classlist->{$student});
1.103     albertel  443: 	}
1.44      ng        444:     }
                    445:     my %seen = ();
1.56      matthew   446:     my @sections = sort(keys(%sections));
                    447:     return ($classlist,\@sections,\%fullnames);
1.44      ng        448: }
                    449: 
1.103     albertel  450: sub canmodify {
                    451:     my ($sec)=@_;
                    452:     if ($perm{'mgr'}) {
                    453: 	if (!defined($perm{'mgr_section'})) {
                    454: 	    # can modify whole class
                    455: 	    return 1;
                    456: 	} else {
                    457: 	    if ($sec eq $perm{'mgr_section'}) {
                    458: 		#can modify the requested section
                    459: 		return 1;
                    460: 	    } else {
                    461: 		# can't modify the request section
                    462: 		return 0;
                    463: 	    }
                    464: 	}
                    465:     }
                    466:     #can't modify
                    467:     return 0;
                    468: }
                    469: 
                    470: sub canview {
                    471:     my ($sec)=@_;
                    472:     if ($perm{'vgr'}) {
                    473: 	if (!defined($perm{'vgr_section'})) {
                    474: 	    # can modify whole class
                    475: 	    return 1;
                    476: 	} else {
                    477: 	    if ($sec eq $perm{'vgr_section'}) {
                    478: 		#can modify the requested section
                    479: 		return 1;
                    480: 	    } else {
                    481: 		# can't modify the request section
                    482: 		return 0;
                    483: 	    }
                    484: 	}
                    485:     }
                    486:     #can't modify
                    487:     return 0;
                    488: }
                    489: 
1.44      ng        490: #--- Retrieve the grade status of a student for all the parts
                    491: sub student_gradeStatus {
1.324     albertel  492:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  493:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        494:     my %partstatus = ();
                    495:     foreach (@$partlist) {
1.128     ng        496: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        497: 	$status              = 'nothing' if ($status eq '');
                    498: 	$partstatus{$_}      = $status;
                    499: 	my $subkey           = "resource.$_.submitted_by";
                    500: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    501:     }
                    502:     return %partstatus;
                    503: }
                    504: 
1.45      ng        505: # hidden form and javascript that calls the form
                    506: # Use by verifyscript and viewgrades
                    507: # Shows a student's view of problem and submission
                    508: sub jscriptNform {
1.324     albertel  509:     my ($symb) = @_;
1.45      ng        510:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    511: 	'    function viewOneStudent(user,domain) {'."\n".
                    512: 	'	document.onestudent.student.value = user;'."\n".
                    513: 	'	document.onestudent.userdom.value = domain;'."\n".
                    514: 	'	document.onestudent.submit();'."\n".
                    515: 	'    }'."\n".
                    516: 	'</script>'."\n";
                    517:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
1.418     albertel  518: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel  519: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    520: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    521: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        522: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    523: 	'<input type="hidden" name="student" value="" />'."\n".
                    524: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    525: 	'</form>'."\n";
                    526:     return $jscript;
                    527: }
1.39      ng        528: 
1.315     bowersj2  529: # Given the score (as a number [0-1] and the weight) what is the final
                    530: # point value? This function will round to the nearest tenth, third,
                    531: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  532: sub compute_points {
1.315     bowersj2  533:     my ($score, $weight) = @_;
                    534:     
                    535:     my $tolerance = .00001;
                    536:     my $points = $score * $weight;
                    537: 
                    538:     # Check for nearness to 1/x.
                    539:     my $check_for_nearness = sub {
                    540:         my ($factor) = @_;
                    541:         my $num = ($points * $factor) + $tolerance;
                    542:         my $floored_num = floor($num);
1.316     albertel  543:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  544:             return $floored_num / $factor;
                    545:         }
                    546:         return $points;
                    547:     };
                    548: 
                    549:     $points = $check_for_nearness->(10);
                    550:     $points = $check_for_nearness->(3);
                    551:     $points = $check_for_nearness->(4);
                    552:     
                    553:     return $points;
                    554: }
                    555: 
1.44      ng        556: #------------------ End of general use routines --------------------
1.87      www       557: 
                    558: #
                    559: # Find most similar essay
                    560: #
                    561: 
                    562: sub most_similar {
1.426     albertel  563:     my ($uname,$udom,$uessay,$old_essays)=@_;
1.87      www       564: 
                    565: # ignore spaces and punctuation
                    566: 
                    567:     $uessay=~s/\W+/ /gs;
                    568: 
1.282     www       569: # ignore empty submissions (occuring when only files are sent)
                    570: 
                    571:     unless ($uessay=~/\w+/) { return ''; }
                    572: 
1.87      www       573: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       574:     my $limit=0.6;
1.87      www       575:     my $sname='';
                    576:     my $sdom='';
                    577:     my $scrsid='';
                    578:     my $sessay='';
                    579: # go through all essays ...
1.426     albertel  580:     foreach my $tkey (keys(%$old_essays)) {
                    581: 	my ($tname,$tdom,$tcrsid)=map {&unescape($_)} (split(/\./,$tkey));
1.87      www       582: # ... except the same student
1.426     albertel  583:         next if (($tname eq $uname) && ($tdom eq $udom));
                    584: 	my $tessay=$old_essays->{$tkey};
                    585: 	$tessay=~s/\W+/ /gs;
1.87      www       586: # String similarity gives up if not even limit
1.426     albertel  587: 	my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       588: # Found one
1.426     albertel  589: 	if ($tsimilar>$limit) {
                    590: 	    $limit=$tsimilar;
                    591: 	    $sname=$tname;
                    592: 	    $sdom=$tdom;
                    593: 	    $scrsid=$tcrsid;
                    594: 	    $sessay=$old_essays->{$tkey};
                    595: 	}
1.87      www       596:     }
1.88      www       597:     if ($limit>0.6) {
1.87      www       598:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    599:     } else {
                    600:        return ('','','','',0);
                    601:     }
                    602: }
                    603: 
1.44      ng        604: #-------------------------------------------------------------------
                    605: 
                    606: #------------------------------------ Receipt Verification Routines
1.45      ng        607: #
1.44      ng        608: #--- Check whether a receipt number is valid.---
                    609: sub verifyreceipt {
                    610:     my $request  = shift;
                    611: 
1.257     albertel  612:     my $courseid = $env{'request.course.id'};
1.184     www       613:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  614: 	$env{'form.receipt'};
1.44      ng        615:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  616:     my ($symb)   = &get_symb($request);
1.44      ng        617: 
1.398     albertel  618:     my $title.='<h3><span class="LC_info">Verifying Submission Receipt '.
                    619: 	$receipt.'</h3></span>'."\n".
                    620: 	'<h4><b>Resource: </b>'.$env{'form.probTitle'}.'</h4><br /><br />'."\n";
1.44      ng        621: 
                    622:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   623:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  624:     
                    625:     my $receiptparts=0;
1.390     albertel  626:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2' ||
                    627: 	$env{"course.$courseid.receiptalg"} eq 'receipt3') { $receiptparts=1; }
1.177     albertel  628:     my $parts=['0'];
1.324     albertel  629:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  630:     foreach (sort 
                    631: 	     {
                    632: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    633: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    634: 		 }
                    635: 		 return $a cmp $b;
                    636: 	     } (keys(%$fullname))) {
1.44      ng        637: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  638: 	foreach my $part (@$parts) {
                    639: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    640: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    641: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel  642: 		    '\');" target="_self">'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
1.177     albertel  643: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    644: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    645: 		if ($receiptparts) {
                    646: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    647: 		}
                    648: 		$contents.='</tr>'."\n";
                    649: 		
                    650: 		$matches++;
                    651: 	    }
1.44      ng        652: 	}
                    653:     }
                    654:     if ($matches == 0) {
                    655: 	$string = $title.'No match found for the above receipt.';
                    656:     } else {
1.324     albertel  657: 	$string = &jscriptNform($symb).$title.
1.44      ng        658: 	    'The above receipt matches the following student'.
                    659: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    660: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    661: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    662: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    663: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  664: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    665: 	if ($receiptparts) {
                    666: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    667: 	}
                    668: 	$string.='</tr>'."\n".$contents.
1.44      ng        669: 	    '</table></td></tr></table>'."\n";
                    670:     }
1.324     albertel  671:     return $string.&show_grading_menu_form($symb);
1.44      ng        672: }
                    673: 
                    674: #--- This is called by a number of programs.
                    675: #--- Called from the Grading Menu - View/Grade an individual student
                    676: #--- Also called directly when one clicks on the subm button 
                    677: #    on the problem page.
1.30      ng        678: sub listStudents {
1.41      ng        679:     my ($request) = shift;
1.49      albertel  680: 
1.324     albertel  681:     my ($symb) = &get_symb($request);
1.257     albertel  682:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    683:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    684:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    685:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    686: 
                    687:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    688:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    689: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  690: 
1.398     albertel  691:     my $result='<h3><span class="LC_info">&nbsp;'.$viewgrade.
                    692: 	' Submissions for a Student or a Group of Students</span></h3>';
1.118     ng        693: 
1.324     albertel  694:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  695: 
1.45      ng        696:     $request->print(<<LISTJAVASCRIPT);
                    697: <script type="text/javascript" language="javascript">
1.110     ng        698:     function checkSelect(checkBox) {
                    699: 	var ctr=0;
                    700: 	var sense="";
                    701: 	if (checkBox.length > 1) {
                    702: 	    for (var i=0; i<checkBox.length; i++) {
                    703: 		if (checkBox[i].checked) {
                    704: 		    ctr++;
                    705: 		}
                    706: 	    }
                    707: 	    sense = "a student or group of students";
                    708: 	} else {
                    709: 	    if (checkBox.checked) {
                    710: 		ctr = 1;
                    711: 	    }
                    712: 	    sense = "the student";
                    713: 	}
                    714: 	if (ctr == 0) {
1.126     ng        715: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        716: 	    return false;
                    717: 	}
                    718: 	document.gradesub.submit();
                    719:     }
                    720: 
                    721:     function reLoadList(formname) {
1.112     ng        722: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        723: 	formname.command.value = 'submission';
                    724: 	formname.submit();
                    725:     }
1.45      ng        726: </script>
                    727: LISTJAVASCRIPT
                    728: 
1.118     ng        729:     &commonJSfunctions($request);
1.41      ng        730:     $request->print($result);
1.39      ng        731: 
1.401     albertel  732:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked="checked"' : '';
                    733:     my $checklastsub = $checkhdgrade eq '' ? 'checked="checked"' : '';
1.154     albertel  734:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    735: 	"\n".$table.
1.401     albertel  736: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.267     albertel  737: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    738: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    739: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    740: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
1.401     albertel  741: 	'<label><input type="radio" name="vAns" value="all" checked="checked" /> all students </label><br />'."\n".
1.49      albertel  742: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  743:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  744: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  745:     }
1.110     ng        746: 
1.257     albertel  747:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    748:     $env{'form.Status'} = $saveStatus;
1.267     albertel  749:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    750: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    751: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  752: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    753:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    754:         '<option value="1">Whole Points</option>'.
                    755:         '<option value=".5">Half Points</option>'.
1.349     albertel  756:         '<option value=".25">Quarter Points</option>'.
                    757:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  758:         '</select>'.
1.432     banghart  759:         &build_section_inputs().
1.45      ng        760: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  761: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    762: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    763: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    764: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.418     albertel  765: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.110     ng        766: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    767: 
1.257     albertel  768:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    769: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        770:     } else {
                    771: 	$gradeTable.='<b>Student Status:</b> '.
                    772: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    773:     }
1.112     ng        774: 
1.126     ng        775:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    776: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        777: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  778: 
                    779: # checkall buttons
                    780:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        781:     $gradeTable.='<input type="button" '."\n".
1.45      ng        782: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  783: 	'value="Next->" /> <br />'."\n";
                    784:     $gradeTable.=&check_buttons();
1.401     albertel  785:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="checked" />Check For Plagiarism</label>';
1.249     albertel  786:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        787:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        788: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    789:     my $loop = 0;
                    790:     while ($loop < 2) {
1.126     ng        791: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  792: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  793: 	if ($env{'form.showgrading'} eq 'yes' 
                    794: 	    && $submitonly ne 'queued'
                    795: 	    && $submitonly ne 'all') {
1.110     ng        796: 	    foreach (sort(@$partlist)) {
1.324     albertel  797: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  798: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    799: 		    ' Status&nbsp;</b></td>';
1.110     ng        800: 	    }
1.301     albertel  801: 	} elsif ($submitonly eq 'queued') {
                    802: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        803: 	}
                    804: 	$loop++;
1.126     ng        805: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        806:     }
1.45      ng        807:     $gradeTable.='</tr>'."\n";
1.41      ng        808: 
1.45      ng        809:     my $ctr = 0;
1.294     albertel  810:     foreach my $student (sort 
                    811: 			 {
                    812: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    813: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    814: 			     }
                    815: 			     return $a cmp $b;
                    816: 			 }
                    817: 			 (keys(%$fullname))) {
1.41      ng        818: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  819: 
1.110     ng        820: 	my %status = ();
1.301     albertel  821: 
                    822: 	if ($submitonly eq 'queued') {
                    823: 	    my %queue_status = 
                    824: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    825: 							$udom,$uname);
                    826: 	    next if (!defined($queue_status{'gradingqueue'}));
                    827: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    828: 	}
                    829: 
                    830: 	if ($env{'form.showgrading'} eq 'yes' 
                    831: 	    && $submitonly ne 'queued'
                    832: 	    && $submitonly ne 'all') {
1.324     albertel  833: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  834: 	    my $submitted = 0;
1.164     albertel  835: 	    my $graded = 0;
1.248     albertel  836: 	    my $incorrect = 0;
1.110     ng        837: 	    foreach (keys(%status)) {
1.145     albertel  838: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  839: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    840: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    841: 		
1.110     ng        842: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    843: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  844: 		    $submitted = 0;
1.150     albertel  845: 		    my ($part)=split(/\./,$partid);
1.110     ng        846: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  847: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        848: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    849: 		}
1.41      ng        850: 	    }
1.248     albertel  851: 	    
1.156     albertel  852: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    853: 				     $submitonly eq 'incorrect' ||
                    854: 				     $submitonly eq 'graded'));
1.248     albertel  855: 	    next if (!$graded && ($submitonly eq 'graded'));
                    856: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        857: 	}
1.34      ng        858: 
1.45      ng        859: 	$ctr++;
1.249     albertel  860: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    861: 
1.104     albertel  862: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        863: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        864: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  865:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    866:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    867: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    868: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    869: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        870: 
1.257     albertel  871: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        872: 		foreach (sort keys(%status)) {
                    873: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  874: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        875: 		}
1.41      ng        876: 	    }
1.126     ng        877: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        878: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        879: 	}
                    880:     }
1.110     ng        881:     if ($ctr%2 ==1) {
1.126     ng        882: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  883: 	    if ($env{'form.showgrading'} eq 'yes' 
                    884: 		&& $submitonly ne 'queued'
                    885: 		&& $submitonly ne 'all') {
1.110     ng        886: 		foreach (@$partlist) {
                    887: 		    $gradeTable.='<td>&nbsp;</td>';
                    888: 		}
1.301     albertel  889: 	    } elsif ($submitonly eq 'queued') {
                    890: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        891: 	    }
                    892: 	$gradeTable.='</tr>';
                    893:     }
                    894: 
1.249     albertel  895:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        896: 	'<input type="button" '.
                    897: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        898: 	'value="Next->" /></form>'."\n";
1.45      ng        899:     if ($ctr == 0) {
1.96      albertel  900: 	my $num_students=(scalar(keys(%$fullname)));
                    901: 	if ($num_students eq 0) {
1.398     albertel  902: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">There are no students currently enrolled.</span>';
1.96      albertel  903: 	} else {
1.171     albertel  904: 	    my $submissions='submissions';
                    905: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    906: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  907: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.398     albertel  908: 	    $gradeTable='<br />&nbsp;<span class="LC_warning">'.
1.171     albertel  909: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
1.398     albertel  910: 		' students checked for '.$submissions.')</span><br />';
1.96      albertel  911: 	}
1.46      ng        912:     } elsif ($ctr == 1) {
                    913: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        914:     }
1.324     albertel  915:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        916:     $request->print($gradeTable);
1.44      ng        917:     return '';
1.10      ng        918: }
                    919: 
1.44      ng        920: #---- Called from the listStudents routine
1.249     albertel  921: 
                    922: sub check_script {
                    923:     my ($form, $type)=@_;
                    924:     my $chkallscript='<script type="text/javascript">
                    925:     function checkall() {
                    926:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    927:             ele = document.forms.'.$form.'.elements[i];
                    928:             if (ele.name == "'.$type.'") {
                    929:             document.forms.'.$form.'.elements[i].checked=true;
                    930:                                        }
                    931:         }
                    932:     }
                    933: 
                    934:     function checksec() {
                    935:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    936:             ele = document.forms.'.$form.'.elements[i];
                    937:            string = document.forms.'.$form.'.chksec.value;
                    938:            if
                    939:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    940:               document.forms.'.$form.'.elements[i].checked=true;
                    941:             }
                    942:         }
                    943:     }
                    944: 
                    945: 
                    946:     function uncheckall() {
                    947:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    948:             ele = document.forms.'.$form.'.elements[i];
                    949:             if (ele.name == "'.$type.'") {
                    950:             document.forms.'.$form.'.elements[i].checked=false;
                    951:                                        }
                    952:         }
                    953:     }
                    954: 
                    955: </script>'."\n";
                    956:     return $chkallscript;
                    957: }
                    958: 
                    959: sub check_buttons {
                    960:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    961:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    962:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    963:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    964:     return $buttons;
                    965: }
                    966: 
1.44      ng        967: #     Displays the submissions for one student or a group of students
1.34      ng        968: sub processGroup {
1.41      ng        969:     my ($request)  = shift;
                    970:     my $ctr        = 0;
1.155     albertel  971:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        972:     my $total      = scalar(@stuchecked)-1;
1.45      ng        973: 
1.396     banghart  974:     foreach my $student (@stuchecked) {
                    975: 	my ($uname,$udom,$fullname) = split(/:/,$student);
1.257     albertel  976: 	$env{'form.student'}        = $uname;
                    977: 	$env{'form.userdom'}        = $udom;
                    978: 	$env{'form.fullname'}       = $fullname;
1.41      ng        979: 	&submission($request,$ctr,$total);
                    980: 	$ctr++;
                    981:     }
                    982:     return '';
1.35      ng        983: }
1.34      ng        984: 
1.44      ng        985: #------------------------------------------------------------------------------------
                    986: #
                    987: #-------------------------- Next few routines handles grading by student, essentially
                    988: #                           handles essay response type problem/part
                    989: #
                    990: #--- Javascript to handle the submission page functionality ---
                    991: sub sub_page_js {
                    992:     my $request = shift;
                    993:     $request->print(<<SUBJAVASCRIPT);
                    994: <script type="text/javascript" language="javascript">
1.71      ng        995:     function updateRadio(formname,id,weight) {
1.125     ng        996: 	var gradeBox = formname["GD_BOX"+id];
                    997: 	var radioButton = formname["RADVAL"+id];
                    998: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        999: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng       1000: 	gradeBox.value = pts;
                   1001: 	var resetbox = false;
                   1002: 	if (isNaN(pts) || pts < 0) {
                   1003: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                   1004: 	    for (var i=0; i<radioButton.length; i++) {
                   1005: 		if (radioButton[i].checked) {
                   1006: 		    gradeBox.value = i;
                   1007: 		    resetbox = true;
                   1008: 		}
                   1009: 	    }
                   1010: 	    if (!resetbox) {
                   1011: 		formtextbox.value = "";
                   1012: 	    }
                   1013: 	    return;
1.44      ng       1014: 	}
1.71      ng       1015: 
                   1016: 	if (pts > weight) {
                   1017: 	    var resp = confirm("You entered a value ("+pts+
                   1018: 			       ") greater than the weight for the part. Accept?");
                   1019: 	    if (resp == false) {
1.125     ng       1020: 		gradeBox.value = oldpts;
1.71      ng       1021: 		return;
                   1022: 	    }
1.44      ng       1023: 	}
1.13      albertel 1024: 
1.71      ng       1025: 	for (var i=0; i<radioButton.length; i++) {
                   1026: 	    radioButton[i].checked=false;
                   1027: 	    if (pts == i && pts != "") {
                   1028: 		radioButton[i].checked=true;
                   1029: 	    }
                   1030: 	}
                   1031: 	updateSelect(formname,id);
1.125     ng       1032: 	formname["stores"+id].value = "0";
1.41      ng       1033:     }
1.5       albertel 1034: 
1.72      ng       1035:     function writeBox(formname,id,pts) {
1.125     ng       1036: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1037: 	if (checkSolved(formname,id) == 'update') {
                   1038: 	    gradeBox.value = pts;
                   1039: 	} else {
1.125     ng       1040: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1041: 	    gradeBox.value = oldpts;
1.125     ng       1042: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1043: 	    for (var i=0; i<radioButton.length; i++) {
                   1044: 		radioButton[i].checked=false;
1.72      ng       1045: 		if (i == oldpts) {
1.71      ng       1046: 		    radioButton[i].checked=true;
                   1047: 		}
                   1048: 	    }
1.41      ng       1049: 	}
1.125     ng       1050: 	formname["stores"+id].value = "0";
1.71      ng       1051: 	updateSelect(formname,id);
                   1052: 	return;
1.41      ng       1053:     }
1.44      ng       1054: 
1.71      ng       1055:     function clearRadBox(formname,id) {
                   1056: 	if (checkSolved(formname,id) == 'noupdate') {
                   1057: 	    updateSelect(formname,id);
                   1058: 	    return;
                   1059: 	}
1.125     ng       1060: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1061: 	for (var i=0; i<gradeSelect.length; i++) {
                   1062: 	    if (gradeSelect[i].selected) {
                   1063: 		var selectx=i;
                   1064: 	    }
                   1065: 	}
1.125     ng       1066: 	var stores = formname["stores"+id];
1.71      ng       1067: 	if (selectx == stores.value) { return };
1.125     ng       1068: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1069: 	gradeBox.value = "";
1.125     ng       1070: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1071: 	for (var i=0; i<radioButton.length; i++) {
                   1072: 	    radioButton[i].checked=false;
                   1073: 	}
                   1074: 	stores.value = selectx;
                   1075:     }
1.5       albertel 1076: 
1.71      ng       1077:     function checkSolved(formname,id) {
1.125     ng       1078: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1079: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1080: 	    if (!reply) {return "noupdate";}
1.120     ng       1081: 	    formname.overRideScore.value = 'yes';
1.41      ng       1082: 	}
1.71      ng       1083: 	return "update";
1.13      albertel 1084:     }
1.71      ng       1085: 
                   1086:     function updateSelect(formname,id) {
1.125     ng       1087: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1088: 	return;
1.41      ng       1089:     }
1.33      ng       1090: 
1.121     ng       1091: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1092:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1093: 	formname.gradeOpt.value = val;
1.71      ng       1094: 	if (val == "Save & Next") {
                   1095: 	    for (i=0;i<=total;i++) {
                   1096: 		for (j=0;j<parttot;j++) {
1.125     ng       1097: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1098: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1099: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1100: 			if (points == "") {
1.125     ng       1101: 			    var name = formname["name"+i].value;
1.129     ng       1102: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1103: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1104: 					       ", part "+partid+". Continue?");
1.71      ng       1105: 			    if (resp == false) {
1.125     ng       1106: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1107: 				return false;
                   1108: 			    }
                   1109: 			}
                   1110: 		    }
                   1111: 		    
                   1112: 		}
                   1113: 	    }
                   1114: 	    
                   1115: 	}
1.121     ng       1116: 	if (val == "Grade Student") {
                   1117: 	    formname.showgrading.value = "yes";
                   1118: 	    if (formname.Status.value == "") {
                   1119: 		formname.Status.value = "Active";
                   1120: 	    }
                   1121: 	    formname.studentNo.value = total;
                   1122: 	}
1.120     ng       1123: 	formname.submit();
                   1124:     }
                   1125: 
1.71      ng       1126: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1127:     function checkSubmitPage(formname,total) {
                   1128: 	noscore = new Array(100);
                   1129: 	var ptr = 0;
                   1130: 	for (i=1;i<total;i++) {
1.125     ng       1131: 	    var partid = formname["q_"+i].value;
1.127     ng       1132: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1133: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1134: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1135: 		if (points == "" && status != "correct_by_student") {
                   1136: 		    noscore[ptr] = i;
                   1137: 		    ptr++;
                   1138: 		}
                   1139: 	    }
                   1140: 	}
                   1141: 	if (ptr != 0) {
                   1142: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1143: 	    var prolist = "";
                   1144: 	    if (ptr == 1) {
                   1145: 		prolist = noscore[0];
                   1146: 	    } else {
                   1147: 		var i = 0;
                   1148: 		while (i < ptr-1) {
                   1149: 		    prolist += noscore[i]+", ";
                   1150: 		    i++;
                   1151: 		}
                   1152: 		prolist += "and "+noscore[i];
                   1153: 	    }
                   1154: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1155: 	    if (resp == false) {
                   1156: 		return false;
                   1157: 	    }
                   1158: 	}
1.45      ng       1159: 
1.71      ng       1160: 	formname.submit();
                   1161:     }
                   1162: </script>
                   1163: SUBJAVASCRIPT
                   1164: }
1.45      ng       1165: 
1.71      ng       1166: #--- javascript for essay type problem --
                   1167: sub sub_page_kw_js {
                   1168:     my $request = shift;
1.80      ng       1169:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1170:     &commonJSfunctions($request);
1.350     albertel 1171: 
1.351     albertel 1172:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1173:     <script text="text/javascript">
                   1174:     function checkInput() {
                   1175:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1176:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1177:       var usrctr = document.msgcenter.usrctr.value;
                   1178:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1179:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1180: 
                   1181:       var msgchk = "";
                   1182:       if (document.msgcenter.subchk.checked) {
                   1183:          msgchk = "msgsub,";
                   1184:       }
                   1185:       var includemsg = 0;
                   1186:       for (var i=1; i<=nmsg; i++) {
                   1187:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1188:           var frmmsg = document.msgcenter["msg"+i];
                   1189:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1190:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1191:           showflg.value = "1";
                   1192:           var chkbox = document.msgcenter["msgn"+i];
                   1193:           if (chkbox.checked) {
                   1194:              msgchk += "savemsg"+i+",";
                   1195:              includemsg = 1;
                   1196:           }
                   1197:       }
                   1198:       if (document.msgcenter.newmsgchk.checked) {
                   1199:          msgchk += "newmsg"+usrctr;
                   1200:          includemsg = 1;
                   1201:       }
                   1202:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1203:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1204:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1205:       includemsg.value = msgchk;
                   1206: 
                   1207:       self.close()
                   1208: 
                   1209:     }
                   1210:     </script>
                   1211: INNERJS
                   1212: 
1.351     albertel 1213:     my $inner_js_highlight_central=<<INNERJS;
                   1214:  <script type="text/javascript">
                   1215:     function updateChoice(flag) {
                   1216:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1217:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1218:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1219:       opener.document.SCORE.refresh.value = "on";
                   1220:       if (opener.document.SCORE.keywords.value!=""){
                   1221:          opener.document.SCORE.submit();
                   1222:       }
                   1223:       self.close()
                   1224:     }
                   1225: </script>
                   1226: INNERJS
                   1227: 
                   1228:     my $start_page_msg_central = 
                   1229:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1230: 				       {'js_ready'  => 1,
                   1231: 					'only_body' => 1,
                   1232: 					'bgcolor'   =>'#FFFFFF',});
                   1233:     my $end_page_msg_central = 
                   1234: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1235: 
                   1236: 
                   1237:     my $start_page_highlight_central = 
                   1238:         &Apache::loncommon::start_page('Highlight Central',
                   1239: 				       $inner_js_highlight_central,
1.350     albertel 1240: 				       {'js_ready'  => 1,
                   1241: 					'only_body' => 1,
                   1242: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1243:     my $end_page_highlight_central = 
1.350     albertel 1244: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1245: 
1.219     www      1246:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1247:     $docopen=~s/^document\.//;
1.71      ng       1248:     $request->print(<<SUBJAVASCRIPT);
                   1249: <script type="text/javascript" language="javascript">
1.45      ng       1250: 
1.44      ng       1251: //===================== Show list of keywords ====================
1.122     ng       1252:   function keywords(formname) {
                   1253:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1254:     if (nret==null) return;
1.122     ng       1255:     formname.keywords.value = nret;
1.44      ng       1256: 
1.122     ng       1257:     if (formname.keywords.value != "") {
1.128     ng       1258: 	formname.refresh.value = "on";
1.122     ng       1259: 	formname.submit();
1.44      ng       1260:     }
                   1261:     return;
                   1262:   }
                   1263: 
                   1264: //===================== Script to view submitted by ==================
                   1265:   function viewSubmitter(submitter) {
                   1266:     document.SCORE.refresh.value = "on";
                   1267:     document.SCORE.NCT.value = "1";
                   1268:     document.SCORE.unamedom0.value = submitter;
                   1269:     document.SCORE.submit();
                   1270:     return;
                   1271:   }
                   1272: 
                   1273: //===================== Script to add keyword(s) ==================
                   1274:   function getSel() {
                   1275:     if (document.getSelection) txt = document.getSelection();
                   1276:     else if (document.selection) txt = document.selection.createRange().text;
                   1277:     else return;
                   1278:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1279:     if (cleantxt=="") {
1.46      ng       1280: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1281: 	return;
                   1282:     }
                   1283:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1284:     if (nret==null) return;
1.127     ng       1285:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1286:     if (document.SCORE.keywords.value != "") {
1.127     ng       1287: 	document.SCORE.refresh.value = "on";
1.44      ng       1288: 	document.SCORE.submit();
                   1289:     }
                   1290:     return;
                   1291:   }
                   1292: 
                   1293: //====================== Script for composing message ==============
1.80      ng       1294:    // preload images
                   1295:    img1 = new Image();
                   1296:    img1.src = "$iconpath/mailbkgrd.gif";
                   1297:    img2 = new Image();
                   1298:    img2.src = "$iconpath/mailto.gif";
                   1299: 
1.44      ng       1300:   function msgCenter(msgform,usrctr,fullname) {
                   1301:     var Nmsg  = msgform.savemsgN.value;
                   1302:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1303:     var subject = msgform.msgsub.value;
1.127     ng       1304:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1305:     re = /msgsub/;
                   1306:     var shwsel = "";
                   1307:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1308:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1309:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1310:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1311: 	var testmsg = "savemsg"+i+",";
                   1312: 	re = new RegExp(testmsg,"g");
1.44      ng       1313: 	shwsel = "";
                   1314: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1315: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1316: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1317: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1318: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1319:     }
1.125     ng       1320:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1321:     shwsel = "";
                   1322:     re = /newmsg/;
                   1323:     if (re.test(msgchk)) { shwsel = "checked" }
                   1324:     newMsg(newmsg,shwsel);
                   1325:     msgTail(); 
                   1326:     return;
                   1327:   }
                   1328: 
1.123     ng       1329:   function checkEntities(strx) {
                   1330:     if (strx.length == 0) return strx;
                   1331:     var orgStr = ["&", "<", ">", '"']; 
                   1332:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1333:     var counter = 0;
                   1334:     while (counter < 4) {
                   1335: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1336: 	counter++;
                   1337:     }
                   1338:     return strx;
                   1339:   }
                   1340: 
                   1341:   function strReplace(strx, orgStr, newStr) {
                   1342:     return strx.split(orgStr).join(newStr);
                   1343:   }
                   1344: 
1.44      ng       1345:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1346:     var height = 70*Nmsg+250;
1.44      ng       1347:     var scrollbar = "no";
                   1348:     if (height > 600) {
                   1349: 	height = 600;
                   1350: 	scrollbar = "yes";
                   1351:     }
1.118     ng       1352:     var xpos = (screen.width-600)/2;
                   1353:     xpos = (xpos < 0) ? '0' : xpos;
                   1354:     var ypos = (screen.height-height)/2-30;
                   1355:     ypos = (ypos < 0) ? '0' : ypos;
                   1356: 
1.206     albertel 1357:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1358:     pWin.focus();
                   1359:     pDoc = pWin.document;
1.219     www      1360:     pDoc.$docopen;
1.351     albertel 1361:     pDoc.write('$start_page_msg_central');
1.76      ng       1362: 
                   1363:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1364:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.398     albertel 1365:     pDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Compose Message for \"+fullname+\"</span></h3><br /><br />");
1.76      ng       1366: 
                   1367:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1368:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1369:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1370: }
                   1371:     function displaySubject(msg,shwsel) {
1.76      ng       1372:     pDoc = pWin.document;
                   1373:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1374:     pDoc.write("<td>Subject</td>");
                   1375:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1376:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1377: }
                   1378: 
1.72      ng       1379:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1380:     pDoc = pWin.document;
                   1381:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1382:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1383:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1384:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1385: }
                   1386: 
                   1387:   function newMsg(newmsg,shwsel) {
1.76      ng       1388:     pDoc = pWin.document;
                   1389:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1390:     pDoc.write("<td align=\\"center\\">New</td>");
                   1391:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1392:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1393: }
                   1394: 
                   1395:   function msgTail() {
1.76      ng       1396:     pDoc = pWin.document;
                   1397:     pDoc.write("</table>");
                   1398:     pDoc.write("</td></tr></table>&nbsp;");
                   1399:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1400:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1401:     pDoc.write("</form>");
1.351     albertel 1402:     pDoc.write('$end_page_msg_central');
1.128     ng       1403:     pDoc.close();
1.44      ng       1404: }
                   1405: 
                   1406: //====================== Script for keyword highlight options ==============
                   1407:   function kwhighlight() {
                   1408:     var kwclr    = document.SCORE.kwclr.value;
                   1409:     var kwsize   = document.SCORE.kwsize.value;
                   1410:     var kwstyle  = document.SCORE.kwstyle.value;
                   1411:     var redsel = "";
                   1412:     var grnsel = "";
                   1413:     var blusel = "";
                   1414:     if (kwclr=="red")   {var redsel="checked"};
                   1415:     if (kwclr=="green") {var grnsel="checked"};
                   1416:     if (kwclr=="blue")  {var blusel="checked"};
                   1417:     var sznsel = "";
                   1418:     var sz1sel = "";
                   1419:     var sz2sel = "";
                   1420:     if (kwsize=="0")  {var sznsel="checked"};
                   1421:     if (kwsize=="+1") {var sz1sel="checked"};
                   1422:     if (kwsize=="+2") {var sz2sel="checked"};
                   1423:     var synsel = "";
                   1424:     var syisel = "";
                   1425:     var sybsel = "";
                   1426:     if (kwstyle=="")    {var synsel="checked"};
                   1427:     if (kwstyle=="<i>") {var syisel="checked"};
                   1428:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1429:     highlightCentral();
                   1430:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1431:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1432:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1433:     highlightend();
                   1434:     return;
                   1435:   }
                   1436: 
                   1437:   function highlightCentral() {
1.76      ng       1438: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1439:     var xpos = (screen.width-400)/2;
                   1440:     xpos = (xpos < 0) ? '0' : xpos;
                   1441:     var ypos = (screen.height-330)/2-30;
                   1442:     ypos = (ypos < 0) ? '0' : ypos;
                   1443: 
1.206     albertel 1444:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1445:     hwdWin.focus();
                   1446:     var hDoc = hwdWin.document;
1.219     www      1447:     hDoc.$docopen;
1.351     albertel 1448:     hDoc.write('$start_page_highlight_central');
1.76      ng       1449:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.398     albertel 1450:     hDoc.write("<h3><span class=\\"LC_info\\">&nbsp;Keyword Highlight Options</span></h3><br /><br />");
1.76      ng       1451: 
                   1452:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1453:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1454:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1455:   }
                   1456: 
                   1457:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1458:     var hDoc = hwdWin.document;
                   1459:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1460:     hDoc.write("<td align=\\"left\\">");
                   1461:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1462:     hDoc.write("<td align=\\"left\\">");
                   1463:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1464:     hDoc.write("<td align=\\"left\\">");
                   1465:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1466:     hDoc.write("</tr>");
1.44      ng       1467:   }
                   1468: 
                   1469:   function highlightend() { 
1.76      ng       1470:     var hDoc = hwdWin.document;
                   1471:     hDoc.write("</table>");
                   1472:     hDoc.write("</td></tr></table>&nbsp;");
                   1473:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1474:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1475:     hDoc.write("</form>");
1.351     albertel 1476:     hDoc.write('$end_page_highlight_central');
1.128     ng       1477:     hDoc.close();
1.44      ng       1478:   }
                   1479: 
                   1480: </script>
                   1481: SUBJAVASCRIPT
                   1482: }
                   1483: 
1.349     albertel 1484: sub get_increment {
1.348     bowersj2 1485:     my $increment = $env{'form.increment'};
                   1486:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1487:         $increment != .1) {
                   1488:         $increment = 1;
                   1489:     }
                   1490:     return $increment;
                   1491: }
                   1492: 
1.71      ng       1493: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1494: sub gradeBox {
1.322     albertel 1495:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1496:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1497: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1498: 	'/check.gif" height="16" border="0" />';
                   1499:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1500:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
1.398     albertel 1501: 		  '<span class="LC_info">problem weight assigned by computer</span>');
1.71      ng       1502:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1503:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1504: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1505:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1506:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1507:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1508: 				       [$partid]);
                   1509:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1510:     if ($last_resets{$partid}) {
                   1511:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1512:     }
1.71      ng       1513:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1514: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1515:     my $ctr = 0;
1.348     bowersj2 1516:     my $thisweight = 0;
1.349     albertel 1517:     my $increment = &get_increment();
1.71      ng       1518:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1519:     while ($thisweight<=$wgt) {
1.381     albertel 1520: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1521: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1522: 	    $thisweight.')" value="'.$thisweight.'" '.
1.401     albertel 1523: 	    ($score eq $thisweight ? 'checked="checked"':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1524: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1525:         $thisweight += $increment;
1.71      ng       1526: 	$ctr++;
                   1527:     }
                   1528:     $result.='</tr></table>';
                   1529:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1530:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1531: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1532: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1533: 	$wgt.')" /></td>'."\n";
                   1534:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1535: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1536: 	' </td><td>'."\n";
                   1537:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1538: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1539:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.384     albertel 1540: 	$result.='<option></option>'.
1.401     albertel 1541: 	    '<option selected="selected">excused</option>';
1.71      ng       1542:     } else {
1.401     albertel 1543: 	$result.='<option selected="selected"></option>'.
1.125     ng       1544: 	    '<option>excused</option>';
1.71      ng       1545:     }
1.125     ng       1546:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1547:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1548:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1549: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1550: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1551: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1552:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1553:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1554:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1555:         $aggtries.'" />'."\n";
1.71      ng       1556:     $result.='</td></tr></table>'."\n";
1.323     banghart 1557:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1558:     return $result;
                   1559: }
1.322     albertel 1560: 
                   1561: sub handback_box {
1.323     banghart 1562:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1563:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1564:     my (@respids);
1.375     albertel 1565:      my @part_response_id = &flatten_responseType($responseType);
                   1566:     foreach my $part_response_id (@part_response_id) {
                   1567:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1568:         if ($part eq $partid) {
1.375     albertel 1569:             push(@respids,$resp);
1.323     banghart 1570:         }
                   1571:     }
1.318     banghart 1572:     my $result;
1.323     banghart 1573:     foreach my $respid (@respids) {
1.322     albertel 1574: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1575: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1576: 	next if (!@$files);
                   1577: 	my $file_counter = 1;
1.313     banghart 1578: 	foreach my $file (@$files) {
1.368     banghart 1579: 	    if ($file =~ /\/portfolio\//) {
                   1580:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1581:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1582:     	        $file_disp = "$name.$ext";
                   1583:     	        $file = $file_path.$file_disp;
                   1584:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1585:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1586:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1587:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1588:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1589:     	        $file_counter++;
                   1590: 	    }
1.322     albertel 1591: 	}
1.313     banghart 1592:     }
1.318     banghart 1593:     return $result;    
1.71      ng       1594: }
1.44      ng       1595: 
1.58      albertel 1596: sub show_problem {
1.382     albertel 1597:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1598:     my $rendered;
1.382     albertel 1599:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1600:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1601:     if ($mode eq 'both' or $mode eq 'text') {
                   1602: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382     albertel 1603: 						       $env{'request.course.id'},
                   1604: 						       undef,\%form);
1.144     albertel 1605:     }
1.58      albertel 1606:     if ($removeform) {
                   1607: 	$rendered=~s|<form(.*?)>||g;
                   1608: 	$rendered=~s|</form>||g;
1.374     albertel 1609: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1610:     }
1.144     albertel 1611:     my $companswer;
                   1612:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1613: 	&Apache::lonxml::restore_problem_counter();
1.382     albertel 1614: 	$companswer=
                   1615: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
                   1616: 						    $env{'request.course.id'},
                   1617: 						    %form);
1.144     albertel 1618:     }
1.58      albertel 1619:     if ($removeform) {
                   1620: 	$companswer=~s|<form(.*?)>||g;
                   1621: 	$companswer=~s|</form>||g;
1.144     albertel 1622: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1623:     }
                   1624:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1625:     $result.='<table border="0" width="100%">';
1.144     albertel 1626:     if ($viewon) {
                   1627: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1628: 	if ($mode eq 'both' or $mode eq 'text') {
                   1629: 	    $result.='View of the problem - ';
                   1630: 	} else {
                   1631: 	    $result.='Correct answer: ';
                   1632: 	}
1.257     albertel 1633: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1634:     }
                   1635:     if ($mode eq 'both') {
                   1636: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1637: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1638:     } elsif ($mode eq 'text') {
                   1639: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1640:     } elsif ($mode eq 'answer') {
                   1641: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1642:     }
1.58      albertel 1643:     $result.='</td></tr></table>';
                   1644:     $result.='</td></tr></table><br />';
1.71      ng       1645:     return $result;
1.58      albertel 1646: }
1.397     albertel 1647: 
1.396     banghart 1648: sub files_exist {
                   1649:     my ($r, $symb) = @_;
                   1650:     my @students = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.397     albertel 1651: 
1.396     banghart 1652:     foreach my $student (@students) {
                   1653:         my ($uname,$udom,$fullname) = split(/:/,$student);
1.397     albertel 1654:         my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   1655: 					      $udom,$uname);
1.396     banghart 1656:         my ($string,$timestamp)= &get_last_submission(\%record);
1.397     albertel 1657:         foreach my $submission (@$string) {
                   1658:             my ($partid,$respid) =
                   1659: 		($submission =~ /^resource\.([^\.]*)\.([^\.]*)\.submission/);
                   1660:             my $files=&get_submitted_files($udom,$uname,$partid,$respid,
                   1661: 					   \%record);
                   1662:             return 1 if (@$files);
1.396     banghart 1663:         }
                   1664:     }
1.397     albertel 1665:     return 0;
1.396     banghart 1666: }
1.397     albertel 1667: 
1.394     banghart 1668: sub download_all_link {
                   1669:     my ($r,$symb) = @_;
1.395     albertel 1670:     my $all_students = 
                   1671: 	join("\n", &Apache::loncommon::get_env_multiple('form.stuinfo'));
                   1672: 
                   1673:     my $parts =
                   1674: 	join("\n",&Apache::loncommon::get_env_multiple('form.vPart'));
                   1675: 
1.394     banghart 1676:     my $identifier = &Apache::loncommon::get_cgi_id();
                   1677:     &Apache::lonnet::appenv('cgi.'.$identifier.'.students' => $all_students,
                   1678:                             'cgi.'.$identifier.'.symb' => $symb,
1.395     albertel 1679:                             'cgi.'.$identifier.'.parts' => $parts,);
                   1680:     $r->print('<a href="/cgi-bin/multidownload.pl?'.$identifier.'">'.
                   1681: 	      &mt('Download All Submitted Documents').'</a>');
1.394     banghart 1682:     return
                   1683: }
1.395     albertel 1684: 
1.432     banghart 1685: sub build_section_inputs {
                   1686:     my $section_inputs;
                   1687:     if ($env{'form.section'} eq '') {
                   1688:         $section_inputs .= '<input type="hidden" name="section" value="all" />'."\n";
                   1689:     } else {
                   1690:         my @sections = &Apache::loncommon::get_env_multiple('form.section');
1.434     albertel 1691:         foreach my $section (@sections) {
1.432     banghart 1692:             $section_inputs .= '<input type="hidden" name="section" value="'.$section.'" />'."\n";
                   1693:         }
                   1694:     }
                   1695:     return $section_inputs;
                   1696: }
                   1697: 
1.44      ng       1698: # --------------------------- show submissions of a student, option to grade 
                   1699: sub submission {
                   1700:     my ($request,$counter,$total) = @_;
                   1701: 
1.257     albertel 1702:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1703:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1704:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1705:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1706: 
1.324     albertel 1707:     my $symb = &get_symb($request); 
                   1708:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1709: 
                   1710:     if (!&canview($usec)) {
1.398     albertel 1711: 	$request->print('<span class="LC_warning">Unable to view requested student.('.
                   1712: 			$uname.':'.$udom.' in section '.$usec.' in course id '.
                   1713: 			$env{'request.course.id'}.')</span>');
1.324     albertel 1714: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1715: 	return;
                   1716:     }
                   1717: 
1.257     albertel 1718:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1719:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1720:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1721:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1722:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1723: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1724: 	'/check.gif" height="16" border="0" />';
1.41      ng       1725: 
1.426     albertel 1726:     my %old_essays;
1.41      ng       1727:     # header info
                   1728:     if ($counter == 0) {
                   1729: 	&sub_page_js($request);
1.257     albertel 1730: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1731: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1732: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.397     albertel 1733: 	if ($env{'form.handgrade'} eq 'yes' && &files_exist($request, $symb)) {
1.396     banghart 1734: 	    &download_all_link($request, $symb);
                   1735: 	}
1.398     albertel 1736: 	$request->print('<h3>&nbsp;<span class="LC_info">Submission Record</span></h3>'."\n".
                   1737: 			'<h4>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n");
1.118     ng       1738: 
1.257     albertel 1739: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1740: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1741: 		$checkIcon.' symbol.'."\n";
                   1742: 	    $request->print($checkMark);
                   1743: 	}
1.41      ng       1744: 
1.44      ng       1745: 	# option to display problem, only once else it cause problems 
                   1746:         # with the form later since the problem has a form.
1.257     albertel 1747: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1748: 	    my $mode;
1.257     albertel 1749: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1750: 		$mode='both';
1.257     albertel 1751: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1752: 		$mode='text';
1.257     albertel 1753: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1754: 		$mode='answer';
                   1755: 	    }
1.329     albertel 1756: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1757: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1758: 	}
                   1759: 	
1.44      ng       1760: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1761:         # if this subroutine has been called once.
1.41      ng       1762: 	my %keyhash = ();
1.257     albertel 1763: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1764: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1765: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1766: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1767: 
1.257     albertel 1768: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1769: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1770: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1771: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1772: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1773: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1774: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1775: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1776: 	}
1.257     albertel 1777: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.303     banghart 1778: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1779: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1780: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1781: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1782: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1783: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1784: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1785: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1786: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.418     albertel 1787: 			'<input type="hidden" name="symb"       value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 1788: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1789: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1790: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1791: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.432     banghart 1792: 			&build_section_inputs().
1.326     albertel 1793: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1794: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1795: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1796: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1797: 	if ($env{'form.handgrade'} eq 'yes') {
                   1798: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1799: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1800: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1801: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1802: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1803: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1804: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1805: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1806: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1807: 	    }
1.123     ng       1808: 	}
1.41      ng       1809: 	
                   1810: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1811: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1812: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1813: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1814: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1815: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1816: 		'" />'."\n".
                   1817: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1818: 	    $cts++;
                   1819: 	}
                   1820: 	$request->print($prnmsg);
1.32      ng       1821: 
1.257     albertel 1822: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1823: #
                   1824: # Print out the keyword options line
                   1825: #
1.41      ng       1826: 	    $request->print(<<KEYWORDS);
1.38      ng       1827: &nbsp;<b>Keyword Options:</b>&nbsp;
1.417     albertel 1828: <a href="javascript:keywords(document.SCORE);" target="_self">List</a>&nbsp; &nbsp;
1.38      ng       1829: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1830:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
1.417     albertel 1831: <a href="javascript:kwhighlight();" target="_self">Highlight Attribute</a><br /><br />
1.38      ng       1832: KEYWORDS
1.88      www      1833: #
                   1834: # Load the other essays for similarity check
                   1835: #
1.324     albertel 1836:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.384     albertel 1837: 	    my ($adom,$aname,$apath)=($essayurl=~/^($LONCAPA::domain_re)\/($LONCAPA::username_re)\/(.*)$/);
1.359     www      1838: 	    $apath=&escape($apath);
1.88      www      1839: 	    $apath=~s/\W/\_/gs;
1.426     albertel 1840: 	    %old_essays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1841:         }
                   1842:     }
1.44      ng       1843: 
1.257     albertel 1844:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1845: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1846: 	my $mode;
1.257     albertel 1847: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1848: 	    $mode='both';
1.257     albertel 1849: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1850: 	    $mode='text';
1.257     albertel 1851: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1852: 	    $mode='answer';
                   1853: 	}
1.329     albertel 1854: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1855: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1856:     }
1.144     albertel 1857: 
1.257     albertel 1858:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1859:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1860: 
1.44      ng       1861:     # Display student info
1.41      ng       1862:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1863:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1864: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1865: 
1.257     albertel 1866:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1867:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1868: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1869: 
1.118     ng       1870:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1871:     my @col_fullnames;
1.56      matthew  1872:     my ($classlist,$fullname);
1.257     albertel 1873:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1874: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1875: 	for (keys (%$handgrade)) {
1.44      ng       1876: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1877: 					    '.maxcollaborators',
                   1878:                                             $symb,$udom,$uname);
                   1879: 	    next if ($ncol <= 0);
                   1880:             s/\_/\./g;
                   1881:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1882:             my @goodcollaborators = ();
                   1883:             my @badcollaborators  = ();
                   1884: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1885: 		$_ =~ s/[\$\^\(\)]//g;
                   1886: 		next if ($_ eq '');
1.80      ng       1887: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1888: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1889: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1890: 		# Doing this grep allows 'fuzzy' specification
                   1891: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1892: 		if (! scalar(@Matches)) {
                   1893: 		    push @badcollaborators,$_;
                   1894: 		} else {
                   1895: 		    push @goodcollaborators, @Matches;
                   1896: 		}
1.80      ng       1897: 	    }
1.86      ng       1898:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1899:                 $result.='<b>Collaborators: </b>';
1.86      ng       1900:                 foreach (@goodcollaborators) {
                   1901: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1902: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1903: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1904: 		}
1.57      matthew  1905:                 $result.='<br />'."\n";
1.150     albertel 1906: 		my ($part)=split(/\./,$_);
1.86      ng       1907: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1908: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1909: 		    "\n";
1.86      ng       1910: 	    }
                   1911: 	    if (scalar(@badcollaborators) > 0) {
                   1912: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1913: 		$result.='This student has submitted ';
                   1914: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1915: 		$result .= ': '.join(', ',@badcollaborators);
                   1916: 		$result .= '</td></tr></table>';
                   1917: 	    }         
                   1918: 	    if (scalar(@badcollaborators > $ncol)) {
                   1919: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1920: 		$result .= 'This student has submitted too many '.
                   1921: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1922: 		$result .= '</td></tr></table>';
                   1923: 	    }
1.41      ng       1924: 	}
                   1925:     }
1.44      ng       1926:     $request->print($result."\n");
1.33      ng       1927: 
1.44      ng       1928:     # print student answer/submission
                   1929:     # Options are (1) Handgaded submission only
                   1930:     #             (2) Last submission, includes submission that is not handgraded 
                   1931:     #                  (for multi-response type part)
                   1932:     #             (3) Last submission plus the parts info
                   1933:     #             (4) The whole record for this student
1.257     albertel 1934:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1935: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1936: 	my $lastsubonly=''.
                   1937: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1938: 	     $$timestamp)."</td></tr>\n";
                   1939: 	if ($$timestamp eq '') {
                   1940: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1941: 	} else {
                   1942: 	    my %seenparts;
1.375     albertel 1943: 	    my @part_response_id = &flatten_responseType($responseType);
                   1944: 	    foreach my $part (@part_response_id) {
1.393     albertel 1945: 		next if ($env{'form.lastSub'} eq 'hdgrade' 
                   1946: 			 && $$handgrade{$$part[0].'_'.$$part[1]} ne 'yes');
                   1947: 
1.375     albertel 1948: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1949: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1950: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1951: 		    if (exists($seenparts{$partid})) { next; }
                   1952: 		    $seenparts{$partid}=1;
1.207     albertel 1953: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1954: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1955: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1956: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.417     albertel 1957: 			'\');" target="_self">'.
1.257     albertel 1958: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1959: 		    $request->print($submitby);
                   1960: 		    next;
                   1961: 		}
                   1962: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1963: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1964: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
1.398     albertel 1965: 			$display_part.' <span class="LC_internal_info">( ID '.$respid.
                   1966: 			' )</span>&nbsp; &nbsp;'.
                   1967: 			'<span class="LC_warning">Nothing submitted - no attempts</span><br /><br />';
1.151     albertel 1968: 		    next;
                   1969: 		}
                   1970: 		foreach (@$string) {
                   1971: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1972: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1973: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1974: 		    # Similarity check
                   1975: 		    my $similar='';
1.257     albertel 1976: 		    if($env{'form.checkPlag'}){
1.151     albertel 1977: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
1.426     albertel 1978: 			    &most_similar($uname,$udom,$subval,\%old_essays);
1.151     albertel 1979: 			if ($osim) {
                   1980: 			    $osim=int($osim*100.0);
1.426     albertel 1981: 			    my %old_course_desc = 
                   1982: 				&Apache::lonnet::coursedescription($ocrsid,
                   1983: 								   {'one_time' => 1});
                   1984: 
                   1985: 			    $similar="<hr /><h3><span class=\"LC_warning\">".
1.427     albertel 1986: 				&mt('Essay is [_1]% similar to an essay by [_2] ([_3]:[_4]) in course [_5] (course id [_6]:[_7])',
1.426     albertel 1987: 				    $osim,
                   1988: 				    &Apache::loncommon::plainname($oname,$odom),
1.427     albertel 1989: 				    $oname,$odom,
1.426     albertel 1990: 				    $old_course_desc{'description'},
1.427     albertel 1991: 				    $old_course_desc{'num'},
1.426     albertel 1992: 				    $old_course_desc{'domain'}).
1.398     albertel 1993: 				'</span></h3><blockquote><i>'.
1.151     albertel 1994: 				&keywords_highlight($oessay).
                   1995: 				'</i></blockquote><hr />';
                   1996: 			}
1.150     albertel 1997: 		    }
1.151     albertel 1998: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1999: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   2000: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 2001: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 2002: 			my $display_part=&get_display_part($partid,$symb);
1.403     albertel 2003: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   2004: 			    $display_part.' <span class="LC_internal_info">( ID '.$respid.
1.398     albertel 2005: 			    ' )</span>&nbsp; &nbsp;';
1.313     banghart 2006: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   2007: 			if (@$files) {
1.398     albertel 2008: 			    $lastsubonly.='<br /><span class="LC_warning">Like all files provided by users, this file may contain virusses</span><br />';
1.303     banghart 2009: 			    my $file_counter = 0;
1.313     banghart 2010: 			    foreach my $file (@$files) {
1.303     banghart 2011: 			        $file_counter ++;
1.232     albertel 2012: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 2013: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 2014: 			    }
1.236     albertel 2015: 			    $lastsubonly.='<br />';
1.41      ng       2016: 			}
1.151     albertel 2017: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   2018: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   2019: 					 $respid,\%record,$order);
                   2020: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       2021: 		    }
                   2022: 		}
                   2023: 	    }
1.151     albertel 2024: 	}
                   2025: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   2026: 	$request->print($lastsubonly);
1.257     albertel 2027:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 2028: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 2029: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 2030:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       2031: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 2032: 								 $env{'request.course.id'},
1.44      ng       2033: 								 $last,'.submission',
                   2034: 								 'Apache::grades::keywords_highlight'));
1.41      ng       2035:     }
1.120     ng       2036: 
1.121     ng       2037:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   2038: 	.$udom.'" />'."\n");
1.41      ng       2039:     
1.44      ng       2040:     # return if view submission with no grading option
1.257     albertel 2041:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       2042: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       2043: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
1.417     albertel 2044: 	    .$counter.'\');" target="_self" /> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 2045: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 2046: 	if (($env{'form.command'} eq 'submission') || 
                   2047: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 2048: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 2049: 	}
1.180     albertel 2050: 	$request->print($toGrade);
1.41      ng       2051: 	return;
1.180     albertel 2052:     } else {
                   2053: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       2054:     }
1.33      ng       2055: 
1.121     ng       2056:     # essay grading message center
1.257     albertel 2057:     if ($env{'form.handgrade'} eq 'yes') {
                   2058: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       2059: 	my $msgfor = $givenn.' '.$lastname;
                   2060: 	if (scalar(@col_fullnames) > 0) {
                   2061: 	    my $lastone = pop @col_fullnames;
                   2062: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   2063: 	}
                   2064: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       2065: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   2066: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   2067: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.417     albertel 2068: 	    ',\''.$msgfor.'\');" target="_self">'.
1.350     albertel 2069: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   2070: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       2071: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   2072: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      2073: 	    '<br />&nbsp;('.
                   2074: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       2075: 	$request->print($result);
1.118     ng       2076:     }
1.300     albertel 2077:     if ($perm{'vgr'}) {
1.297     www      2078: 	$request->print('<br />'.
1.300     albertel 2079: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   2080: 						   $uname,$udom,'check'));
1.297     www      2081:     }
1.300     albertel 2082:     if ($perm{'opa'}) {
1.297     www      2083: 	$request->print('<br />'.
1.300     albertel 2084: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   2085: 					 $uname,$udom,$symb,'check'));
1.297     www      2086:     }
1.41      ng       2087: 
                   2088:     my %seen = ();
                   2089:     my @partlist;
1.129     ng       2090:     my @gradePartRespid;
1.375     albertel 2091:     my @part_response_id = &flatten_responseType($responseType);
                   2092:     foreach my $part_response_id (@part_response_id) {
                   2093:     	my ($partid,$respid) = @{ $part_response_id };
                   2094: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2095: 	next if ($seen{$partid} > 0);
1.41      ng       2096: 	$seen{$partid}++;
1.393     albertel 2097: 	next if ($$handgrade{$part_resp} ne 'yes' 
                   2098: 		 && $env{'form.lastSub'} eq 'hdgrade');
1.41      ng       2099: 	push @partlist,$partid;
1.129     ng       2100: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2101: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2102:     }
1.45      ng       2103:     $result='<input type="hidden" name="partlist'.$counter.
                   2104: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2105:     $result.='<input type="hidden" name="gradePartRespid'.
                   2106: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2107:     my $ctr = 0;
                   2108:     while ($ctr < scalar(@partlist)) {
                   2109: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2110: 	    $partlist[$ctr].'" />'."\n";
                   2111: 	$ctr++;
                   2112:     }
                   2113:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2114: 
                   2115:     # print end of form
                   2116:     if ($counter == $total) {
1.297     www      2117: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2118: 	$endform.='<input type="button" value="Save & Next" '.
                   2119: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
1.417     albertel 2120: 	    $total.','.scalar(@partlist).');" target="_self" /> &nbsp;'."\n";
1.119     ng       2121: 	my $ntstu ='<select name="NTSTU">'.
                   2122: 	    '<option>1</option><option>2</option>'.
                   2123: 	    '<option>3</option><option>5</option>'.
                   2124: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2125: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.401     albertel 2126: 	$ntstu =~ s/<option>$nsel</<option selected="selected">$nsel</;
1.119     ng       2127: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2128: 	$endform.='<input type="button" value="Previous" '.
1.417     albertel 2129: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" target="_self" /> &nbsp;'."\n".
1.126     ng       2130: 	    '<input type="button" value="Next" '.
1.417     albertel 2131: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" target="_self" /> &nbsp;';
1.126     ng       2132: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2133:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2134:             "' name='increment' />";
1.45      ng       2135: 	$endform.='</td><tr></table></form>';
1.324     albertel 2136: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2137: 	$request->print($endform);
                   2138:     }
                   2139:     return '';
1.38      ng       2140: }
                   2141: 
1.44      ng       2142: #--- Retrieve the last submission for all the parts
1.38      ng       2143: sub get_last_submission {
1.119     ng       2144:     my ($returnhash)=@_;
1.46      ng       2145:     my (@string,$timestamp);
1.119     ng       2146:     if ($$returnhash{'version'}) {
1.46      ng       2147: 	my %lasthash=();
                   2148: 	my ($version);
1.119     ng       2149: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
1.397     albertel 2150: 	    foreach my $key (sort(split(/\:/,
                   2151: 					$$returnhash{$version.':keys'}))) {
                   2152: 		$lasthash{$key}=$$returnhash{$version.':'.$key};
                   2153: 		$timestamp = 
                   2154: 		    scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2155: 	    }
                   2156: 	}
1.397     albertel 2157: 	foreach my $key (keys(%lasthash)) {
                   2158: 	    next if ($key !~ /\.submission$/);
                   2159: 
                   2160: 	    my ($partid,$foo) = split(/submission$/,$key);
                   2161: 	    my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
1.398     albertel 2162: 		'<span class="LC_warning">Draft Copy</span> ' : '';
1.397     albertel 2163: 	    push(@string, join(':', $key, $draft.$lasthash{$key}));
1.41      ng       2164: 	}
                   2165:     }
1.397     albertel 2166:     if (!@string) {
                   2167: 	$string[0] =
1.398     albertel 2168: 	    '<span class="LC_warning">Nothing submitted - no attempts.</span>';
1.397     albertel 2169:     }
                   2170:     return (\@string,\$timestamp);
1.38      ng       2171: }
1.35      ng       2172: 
1.44      ng       2173: #--- High light keywords, with style choosen by user.
1.38      ng       2174: sub keywords_highlight {
1.44      ng       2175:     my $string    = shift;
1.257     albertel 2176:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2177:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2178:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2179:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.398     albertel 2180:     foreach my $keyword (@keylist) {
                   2181: 	$string =~ s/\b\Q$keyword\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$keyword$styleoff<\/font>/gi;
1.41      ng       2182:     }
                   2183:     return $string;
1.38      ng       2184: }
1.36      ng       2185: 
1.44      ng       2186: #--- Called from submission routine
1.38      ng       2187: sub processHandGrade {
1.41      ng       2188:     my ($request) = shift;
1.324     albertel 2189:     my $symb   = &get_symb($request);
                   2190:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2191:     my $button = $env{'form.gradeOpt'};
                   2192:     my $ngrade = $env{'form.NCT'};
                   2193:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2194:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2195:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2196: 
1.44      ng       2197:     if ($button eq 'Save & Next') {
                   2198: 	my $ctr = 0;
                   2199: 	while ($ctr < $ngrade) {
1.257     albertel 2200: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2201: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2202: 	    if ($errorflag eq 'no_score') {
                   2203: 		$ctr++;
                   2204: 		next;
                   2205: 	    }
1.104     albertel 2206: 	    if ($errorflag eq 'not_allowed') {
1.398     albertel 2207: 		$request->print("<span class=\"LC_warning\">Not allowed to modify grades for $uname:$udom</span>");
1.104     albertel 2208: 		$ctr++;
                   2209: 		next;
                   2210: 	    }
1.257     albertel 2211: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2212: 	    my ($subject,$message,$msgstatus) = ('','','');
1.418     albertel 2213: 	    my $restitle = &Apache::lonnet::gettitle($symb);
                   2214:             my ($feedurl,$showsymb) =
                   2215: 		&get_feedurl_and_symb($symb,$uname,$udom);
                   2216: 	    my $messagetail;
1.62      albertel 2217: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2218: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2219: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.386     raeburn  2220: 		$subject.=' ['.$restitle.']';
1.44      ng       2221: 		my (@msgnum) = split(/,/,$includemsg);
                   2222: 		foreach (@msgnum) {
1.257     albertel 2223: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2224: 		}
1.80      ng       2225: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2226: 		if ($env{'form.withgrades'.$ctr}) {
                   2227: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
1.386     raeburn  2228: 		    $messagetail = " for <a href=\"".
1.418     albertel 2229: 		                   $feedurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.386     raeburn  2230: 		}
                   2231: 		$msgstatus = 
                   2232:                     &Apache::lonmsg::user_normal_msg($uname,$udom,$subject,
                   2233: 						     $message.$messagetail,
1.418     albertel 2234:                                                      undef,$feedurl,undef,
1.386     raeburn  2235:                                                      undef,undef,$showsymb,
                   2236:                                                      $restitle);
                   2237: 		$request->print('<br />'.&mt('Sending message to [_1]:[_2]',$uname,$udom).': '.
1.296     www      2238: 				$msgstatus);
1.44      ng       2239: 	    }
1.257     albertel 2240: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2241: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2242: 		foreach my $collabstr (@collabstrs) {
                   2243: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2244: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2245: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2246: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2247: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2248: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2249: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2250: 			    next;
1.418     albertel 2251: 			} elsif ($message ne '') {
                   2252: 			    my ($baseurl,$showsymb) = 
                   2253: 				&get_feedurl_and_symb($symb,$collaborator,
                   2254: 						      $udom);
                   2255: 			    if ($env{'form.withgrades'.$ctr}) {
                   2256: 				$messagetail = " for <a href=\"".
1.386     raeburn  2257:                                     $baseurl."?symb=$showsymb\">$env{'form.probTitle'}</a>";
1.150     albertel 2258: 			    }
1.418     albertel 2259: 			    $msgstatus = 
                   2260: 				&Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message.$messagetail,undef,$baseurl,undef,undef,undef,$showsymb,$restitle);
1.104     albertel 2261: 			}
1.44      ng       2262: 		    }
                   2263: 		}
                   2264: 	    }
                   2265: 	    $ctr++;
                   2266: 	}
                   2267:     }
                   2268: 
1.257     albertel 2269:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2270: 	# Keywords sorted in alphabatical order
1.257     albertel 2271: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2272: 	my %keyhash = ();
1.257     albertel 2273: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2274: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2275: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2276: 	$env{'form.keywords'} = join(' ',@keywords);
                   2277: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2278: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2279: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2280: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2281: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2282: 
                   2283: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2284: 	# New messages are saved in env for the next student.
1.119     ng       2285: 	# All messages are saved in nohist_handgrade.db
                   2286: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2287: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2288: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2289: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2290: 		$idx++;
                   2291: 	    }
                   2292: 	    $ctr++;
1.41      ng       2293: 	}
1.119     ng       2294: 	$ctr = 0;
                   2295: 	while ($ctr < $ngrade) {
1.257     albertel 2296: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2297: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2298: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2299: 		$idx++;
                   2300: 	    }
                   2301: 	    $ctr++;
1.41      ng       2302: 	}
1.257     albertel 2303: 	$env{'form.savemsgN'} = --$idx;
                   2304: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2305: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2306: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2307:     }
1.44      ng       2308:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2309:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2310:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2311: 	my ($ctr,$total) = (0,0);
                   2312: 	while ($ctr < $ngrade) {
1.257     albertel 2313: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2314: 	    $ctr++;
                   2315: 	}
1.257     albertel 2316: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2317: 	$ctr = 0;
                   2318: 	while ($ctr < $total) {
1.257     albertel 2319: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2320: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2321: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2322: 	    &submission($request,$ctr,$total-1);
1.41      ng       2323: 	    $ctr++;
                   2324: 	}
                   2325: 	return '';
                   2326:     }
1.36      ng       2327: 
1.121     ng       2328: # Go directly to grade student - from submission or link from chart page
1.120     ng       2329:     if ($button eq 'Grade Student') {
1.324     albertel 2330: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2331: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2332: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2333: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2334: 	&submission($request,0,0);
                   2335: 	return '';
                   2336:     }
                   2337: 
1.44      ng       2338:     # Get the next/previous one or group of students
1.257     albertel 2339:     my $firststu = $env{'form.unamedom0'};
                   2340:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2341:     my $ctr = 2;
1.41      ng       2342:     while ($laststu eq '') {
1.257     albertel 2343: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2344: 	$ctr++;
                   2345: 	$laststu = $firststu if ($ctr > $ngrade);
                   2346:     }
1.44      ng       2347: 
1.41      ng       2348:     my (@parsedlist,@nextlist);
                   2349:     my ($nextflg) = 0;
1.294     albertel 2350:     foreach (sort 
                   2351: 	     {
                   2352: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2353: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2354: 		 }
                   2355: 		 return $a cmp $b;
                   2356: 	     } (keys(%$fullname))) {
1.41      ng       2357: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2358: 	    push @parsedlist,$_;
                   2359: 	}
                   2360: 	$nextflg = 1 if ($_ eq $laststu);
                   2361: 	if ($button eq 'Previous') {
                   2362: 	    last if ($_ eq $firststu);
                   2363: 	    push @parsedlist,$_;
                   2364: 	}
                   2365:     }
                   2366:     $ctr = 0;
                   2367:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2368:     my ($partlist) = &response_type($symb);
1.41      ng       2369:     foreach my $student (@parsedlist) {
1.257     albertel 2370: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2371: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2372: 	
                   2373: 	if ($submitonly eq 'queued') {
                   2374: 	    my %queue_status = 
                   2375: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2376: 							$udom,$uname);
                   2377: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2378: 	}
                   2379: 
1.156     albertel 2380: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2381: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2382: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2383: 	    my $submitted = 0;
1.248     albertel 2384: 	    my $ungraded = 0;
                   2385: 	    my $incorrect = 0;
1.145     albertel 2386: 	    foreach (keys(%status)) {
                   2387: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2388: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2389: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2390: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2391: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2392: 		    $submitted = 0;
                   2393: 		}
1.41      ng       2394: 	    }
1.156     albertel 2395: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2396: 				     $submitonly eq 'incorrect' ||
                   2397: 				     $submitonly eq 'graded'));
1.248     albertel 2398: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2399: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2400: 	}
                   2401: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2402: 	last if ($ctr == $ntstu);
1.41      ng       2403: 	$ctr++;
                   2404:     }
1.36      ng       2405: 
1.41      ng       2406:     $ctr = 0;
                   2407:     my $total = scalar(@nextlist)-1;
1.39      ng       2408: 
1.41      ng       2409:     foreach (sort @nextlist) {
                   2410: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2411: 	$env{'form.student'}  = $uname;
                   2412: 	$env{'form.userdom'}  = $udom;
                   2413: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2414: 	&submission($request,$ctr,$total);
                   2415: 	$ctr++;
                   2416:     }
                   2417:     if ($total < 0) {
1.398     albertel 2418: 	my $the_end = '<h3><span class="LC_info">LON-CAPA User Message</span></h3><br />'."\n";
1.41      ng       2419: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2420: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2421: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2422: 	$request->print($the_end);
                   2423:     }
                   2424:     return '';
1.38      ng       2425: }
1.36      ng       2426: 
1.44      ng       2427: #---- Save the score and award for each student, if changed
1.38      ng       2428: sub saveHandGrade {
1.324     albertel 2429:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2430:     my @version_parts;
1.104     albertel 2431:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2432: 					   $env{'request.course.id'});
1.104     albertel 2433:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2434:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2435:     my @parts_graded;
1.77      ng       2436:     my %newrecord  = ();
                   2437:     my ($pts,$wgt) = ('','');
1.269     raeburn  2438:     my %aggregate = ();
                   2439:     my $aggregateflag = 0;
1.301     albertel 2440:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2441:     foreach my $new_part (@parts) {
1.337     banghart 2442: 	#collaborator ($submi may vary for different parts
1.259     banghart 2443: 	if ($submitter && $new_part ne $part) { next; }
                   2444: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2445: 	if ($dropMenu eq 'excused') {
1.259     banghart 2446: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2447: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2448: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2449: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2450: 		}
1.364     banghart 2451: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2452: 	    }
1.125     ng       2453: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2454: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2455: 	    foreach my $key (keys (%record)) {
1.259     banghart 2456: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2457: 	    }
1.259     banghart 2458: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2459: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2460:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2461: 
                   2462:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2463: 					       [$new_part]);
                   2464:             my $aggtries =$totaltries;
1.269     raeburn  2465:             if ($last_resets{$new_part}) {
1.270     albertel 2466:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2467: 					   $new_part);
1.269     raeburn  2468:             }
1.270     albertel 2469: 
                   2470:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2471:             if ($aggtries > 0) {
1.327     albertel 2472:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2473:                 $aggregateflag = 1;
                   2474:             }
1.125     ng       2475: 	} elsif ($dropMenu eq '') {
1.259     banghart 2476: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2477: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2478: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2479: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2480: 		next;
                   2481: 	    }
1.259     banghart 2482: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2483: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2484: 	    my $partial= $pts/$wgt;
1.259     banghart 2485: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2486: 		#do not update score for part if not changed.
1.346     banghart 2487:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2488: 		next;
1.251     banghart 2489: 	    } else {
1.259     banghart 2490: 	        push @parts_graded, $new_part;
1.153     albertel 2491: 	    }
1.259     banghart 2492: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2493: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2494: 	    }
1.259     banghart 2495: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2496: 	    if ($partial == 0) {
1.153     albertel 2497: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2498: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2499: 		}
1.41      ng       2500: 	    } else {
1.153     albertel 2501: 		if ($record{$reckey} ne 'correct_by_override') {
                   2502: 		    $newrecord{$reckey} = 'correct_by_override';
                   2503: 		}
                   2504: 	    }	    
                   2505: 	    if ($submitter && 
1.259     banghart 2506: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2507: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2508: 	    }
1.259     banghart 2509: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2510: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2511: 	}
1.259     banghart 2512: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2513: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2514: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2515: 	        $dropMenu eq 'reset status')
                   2516: 	   {
1.342     banghart 2517: 	    push (@version_parts,$new_part);
1.259     banghart 2518: 	}
1.41      ng       2519:     }
1.301     albertel 2520:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2521:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2522: 
1.344     albertel 2523:     if (%newrecord) {
                   2524:         if (@version_parts) {
1.364     banghart 2525:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2526:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2527: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2528: 	    foreach my $new_part (@version_parts) {
                   2529: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2530: 				$new_part,\%newrecord);
                   2531: 	    }
1.259     banghart 2532:         }
1.44      ng       2533: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2534: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2535: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2536: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2537:     }
1.269     raeburn  2538:     if ($aggregateflag) {
                   2539:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2540: 			      $cdom,$cnum);
1.269     raeburn  2541:     }
1.301     albertel 2542:     return ('',$pts,$wgt);
1.36      ng       2543: }
1.322     albertel 2544: 
1.380     albertel 2545: sub check_and_remove_from_queue {
                   2546:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2547:     my @ungraded_parts;
                   2548:     foreach my $part (@{$parts}) {
                   2549: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2550: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2551: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2552: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2553: 		) {
                   2554: 	    push(@ungraded_parts, $part);
                   2555: 	}
                   2556:     }
                   2557:     if ( !@ungraded_parts ) {
                   2558: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2559: 					       $cnum,$domain,$stuname);
                   2560:     }
                   2561: }
                   2562: 
1.337     banghart 2563: sub handback_files {
                   2564:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2565:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2566:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2567: 
                   2568:     my @part_response_id = &flatten_responseType($responseType);
                   2569:     foreach my $part_response_id (@part_response_id) {
                   2570:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2571: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2572:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2573:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2574:                 my $file_counter = 1;
1.367     albertel 2575: 		my $file_msg;
1.337     banghart 2576:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2577:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2578:                     my ($directory,$answer_file) = 
                   2579:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2580:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2581: 		        &file_name_version_ext($answer_file);
1.355     banghart 2582: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2583: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2584: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2585:                     # fix file name
                   2586:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2587:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2588:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2589:             	                                $save_file_name);
1.337     banghart 2590:                     if ($result !~ m|^/uploaded/|) {
1.401     albertel 2591:                         $request->print('<span class="LC_error">An error occurred ('.$result.
1.398     albertel 2592:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</span><br />');
1.356     banghart 2593:                     } else {
1.360     banghart 2594:                         # mark the file as read only
                   2595:                         my @files = ($save_file_name);
1.372     albertel 2596:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2597:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2598: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2599: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2600: 			}
                   2601:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2602: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2603: 
1.337     banghart 2604:                     }
                   2605:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2606:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2607:                     $file_counter++;
                   2608:                 }
1.367     albertel 2609: 		my $subject = "File Handed Back by Instructor ";
                   2610: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2611: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2612: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2613: 		$message .= " and can be found in your portfolio space.";
1.418     albertel 2614: 		my ($feedurl,$showsymb) = 
                   2615: 		    &get_feedurl_and_symb($symb,$domain,$stuname);
1.386     raeburn  2616:                 my $restitle = &Apache::lonnet::gettitle($symb);
                   2617: 		my $msgstatus = 
                   2618:                    &Apache::lonmsg::user_normal_msg($stuname,$domain,$subject.
                   2619: 			 ' (File Returned) ['.$restitle.']',$message,undef,
1.418     albertel 2620:                          $feedurl,undef,undef,undef,$showsymb,$restitle);
1.337     banghart 2621:             }
                   2622:         }
1.338     banghart 2623:     return;
1.337     banghart 2624: }
                   2625: 
1.418     albertel 2626: sub get_feedurl_and_symb {
                   2627:     my ($symb,$uname,$udom) = @_;
                   2628:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
                   2629:     $url = &Apache::lonnet::clutter($url);
                   2630:     my $encrypturl=&Apache::lonnet::EXT('resource.0.encrypturl',
                   2631: 					$symb,$udom,$uname);
                   2632:     if ($encrypturl =~ /^yes$/i) {
                   2633: 	&Apache::lonenc::encrypted(\$url,1);
                   2634: 	&Apache::lonenc::encrypted(\$symb,1);
                   2635:     }
                   2636:     return ($url,$symb);
                   2637: }
                   2638: 
1.313     banghart 2639: sub get_submitted_files {
                   2640:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2641:     my @files;
                   2642:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2643:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2644:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2645:     	    push(@files,$file_url.$file);
                   2646:         }
                   2647:     }
                   2648:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2649:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2650:     }
                   2651:     return (\@files);
                   2652: }
1.322     albertel 2653: 
1.269     raeburn  2654: # ----------- Provides number of tries since last reset.
                   2655: sub get_num_tries {
                   2656:     my ($record,$last_reset,$part) = @_;
                   2657:     my $timestamp = '';
                   2658:     my $num_tries = 0;
                   2659:     if ($$record{'version'}) {
                   2660:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2661:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2662:                 $timestamp = $$record{$version.':timestamp'};
                   2663:                 if ($timestamp > $last_reset) {
                   2664:                     $num_tries ++;
                   2665:                 } else {
                   2666:                     last;
                   2667:                 }
                   2668:             }
                   2669:         }
                   2670:     }
                   2671:     return $num_tries;
                   2672: }
                   2673: 
                   2674: # ----------- Determine decrements required in aggregate totals 
                   2675: sub decrement_aggs {
                   2676:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2677:     my %decrement = (
                   2678:                         attempts => 0,
                   2679:                         users => 0,
                   2680:                         correct => 0
                   2681:                     );
                   2682:     $decrement{'attempts'} = $aggtries;
                   2683:     if ($solvedstatus =~ /^correct/) {
                   2684:         $decrement{'correct'} = 1;
                   2685:     }
                   2686:     if ($aggtries == $totaltries) {
                   2687:         $decrement{'users'} = 1;
                   2688:     }
                   2689:     foreach my $type (keys (%decrement)) {
                   2690:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2691:     }
                   2692:     return;
                   2693: }
                   2694: 
                   2695: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2696: sub get_last_resets {
1.270     albertel 2697:     my ($symb,$courseid,$partids) =@_;
                   2698:     my %last_resets;
1.269     raeburn  2699:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2700:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2701:     my @keys;
                   2702:     foreach my $part (@{$partids}) {
                   2703: 	push(@keys,"$symb\0$part\0resettime");
                   2704:     }
                   2705:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2706: 				     $cdom,$cname);
                   2707:     foreach my $part (@{$partids}) {
                   2708: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2709:     }
1.270     albertel 2710:     return %last_resets;
1.269     raeburn  2711: }
                   2712: 
1.251     banghart 2713: # ----------- Handles creating versions for portfolio files as answers
                   2714: sub version_portfiles {
1.343     banghart 2715:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2716:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2717:     my @returned_keys;
1.255     banghart 2718:     my $parts = join('|', @$parts_graded);
1.359     www      2719:     my $portfolio_root = &propath($domain,$stu_name).
                   2720: 	'/userfiles/portfolio';
1.277     albertel 2721:     foreach my $key (keys(%$record)) {
1.259     banghart 2722:         my $new_portfiles;
1.263     banghart 2723:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2724:             my @versioned_portfiles;
1.367     albertel 2725:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2726:             foreach my $file (@portfiles) {
1.306     banghart 2727:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2728:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2729: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2730: 		    &file_name_version_ext($answer_file);
1.306     banghart 2731:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2732:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2733:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2734:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2735:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2736:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2737:                         [$directory.$new_answer],
1.306     banghart 2738:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2739:                 }
1.252     banghart 2740:             }
1.343     banghart 2741:             $$record{$key} = join(',',@versioned_portfiles);
                   2742:             push(@returned_keys,$key);
1.251     banghart 2743:         }
                   2744:     } 
1.343     banghart 2745:     return (@returned_keys);   
1.305     banghart 2746: }
                   2747: 
1.307     banghart 2748: sub get_next_version {
1.341     banghart 2749:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2750:     my $version;
                   2751:     foreach my $row (@$dir_list) {
                   2752:         my ($file) = split(/\&/,$row,2);
                   2753:         my ($file_name,$file_version,$file_ext) =
                   2754: 	    &file_name_version_ext($file);
                   2755:         if (($file_name eq $answer_name) && 
                   2756: 	    ($file_ext eq $answer_ext)) {
                   2757:                 # gets here if filename and extension match, regardless of version
                   2758:                 if ($file_version ne '') {
                   2759:                 # a versioned file is found  so save it for later
                   2760:                 if ($file_version > $version) {
                   2761: 		    $version = $file_version;
                   2762: 	        }
                   2763:             }
                   2764:         }
                   2765:     } 
                   2766:     $version ++;
                   2767:     return($version);
                   2768: }
                   2769: 
1.305     banghart 2770: sub version_selected_portfile {
1.306     banghart 2771:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2772:     my ($answer_name,$answer_ver,$answer_ext) =
                   2773:         &file_name_version_ext($file_name);
                   2774:     my $new_answer;
                   2775:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2776:     if($env{'form.copy'} eq '-1') {
                   2777:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2778:         $new_answer = 'problem getting file';
                   2779:     } else {
                   2780:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2781:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2782:                             $stu_name,$domain,'copy',
                   2783: 		        '/portfolio'.$directory.$new_answer);
                   2784:     }    
                   2785:     return ($new_answer);
1.251     banghart 2786: }
                   2787: 
1.304     albertel 2788: sub file_name_version_ext {
                   2789:     my ($file)=@_;
                   2790:     my @file_parts = split(/\./, $file);
                   2791:     my ($name,$version,$ext);
                   2792:     if (@file_parts > 1) {
                   2793: 	$ext=pop(@file_parts);
                   2794: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2795: 	    $version=pop(@file_parts);
                   2796: 	}
                   2797: 	$name=join('.',@file_parts);
                   2798:     } else {
                   2799: 	$name=join('.',@file_parts);
                   2800:     }
                   2801:     return($name,$version,$ext);
                   2802: }
                   2803: 
1.44      ng       2804: #--------------------------------------------------------------------------------------
                   2805: #
                   2806: #-------------------------- Next few routines handles grading by section or whole class
                   2807: #
                   2808: #--- Javascript to handle grading by section or whole class
1.42      ng       2809: sub viewgrades_js {
                   2810:     my ($request) = shift;
                   2811: 
1.41      ng       2812:     $request->print(<<VIEWJAVASCRIPT);
                   2813: <script type="text/javascript" language="javascript">
1.45      ng       2814:    function writePoint(partid,weight,point) {
1.125     ng       2815: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2816: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2817: 	if (point == "textval") {
1.125     ng       2818: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2819: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2820: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2821: 		var resetbox = false;
                   2822: 		for (var i=0; i<radioButton.length; i++) {
                   2823: 		    if (radioButton[i].checked) {
                   2824: 			textbox.value = i;
                   2825: 			resetbox = true;
                   2826: 		    }
                   2827: 		}
                   2828: 		if (!resetbox) {
                   2829: 		    textbox.value = "";
                   2830: 		}
                   2831: 		return;
                   2832: 	    }
1.109     matthew  2833: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2834: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2835: 				   ") greater than the weight for the part. Accept?");
                   2836: 		if (resp == false) {
                   2837: 		    textbox.value = "";
                   2838: 		    return;
                   2839: 		}
                   2840: 	    }
1.42      ng       2841: 	    for (var i=0; i<radioButton.length; i++) {
                   2842: 		radioButton[i].checked=false;
1.109     matthew  2843: 		if (parseFloat(point) == i) {
1.42      ng       2844: 		    radioButton[i].checked=true;
                   2845: 		}
                   2846: 	    }
1.41      ng       2847: 
1.42      ng       2848: 	} else {
1.125     ng       2849: 	    textbox.value = parseFloat(point);
1.42      ng       2850: 	}
1.41      ng       2851: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2852: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2853: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2854: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2855: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2856: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2857: 	    if (saveval != "correct") {
                   2858: 		scorename.value = point;
1.43      ng       2859: 		if (selname[0].selected != true) {
                   2860: 		    selname[0].selected = true;
                   2861: 		}
1.42      ng       2862: 	    }
                   2863: 	}
1.125     ng       2864: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2865:     }
                   2866: 
                   2867:     function writeRadText(partid,weight) {
1.125     ng       2868: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2869: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2870:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2871: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2872: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2873: 	    for (var i=0; i<radioButton.length; i++) {
                   2874: 		radioButton[i].checked=false;
                   2875: 
                   2876: 	    }
                   2877: 	    textbox.value = "";
                   2878: 
                   2879: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2880: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2881: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2882: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2883: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2884: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2885: 		if ((saveval != "correct") || override) {
1.42      ng       2886: 		    scorename.value = "";
1.125     ng       2887: 		    if (selval[1].selected) {
                   2888: 			selname[1].selected = true;
                   2889: 		    } else {
                   2890: 			selname[2].selected = true;
                   2891: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2892: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2893: 		    }
1.42      ng       2894: 		}
                   2895: 	    }
1.43      ng       2896: 	} else {
                   2897: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2898: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2899: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2900: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2901: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2902: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2903: 		if ((saveval != "correct") || override) {
1.125     ng       2904: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2905: 		    selname[0].selected = true;
                   2906: 		}
                   2907: 	    }
                   2908: 	}	    
1.42      ng       2909:     }
                   2910: 
                   2911:     function changeSelect(partid,user) {
1.125     ng       2912: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2913: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2914: 	var point  = textbox.value;
1.125     ng       2915: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2916: 
1.109     matthew  2917: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2918: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2919: 	    textbox.value = "";
                   2920: 	    return;
                   2921: 	}
1.109     matthew  2922: 	if (parseFloat(point) > parseFloat(weight)) {
                   2923: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2924: 			       ") greater than the weight of the part. Accept?");
                   2925: 	    if (resp == false) {
                   2926: 		textbox.value = "";
                   2927: 		return;
                   2928: 	    }
                   2929: 	}
1.42      ng       2930: 	selval[0].selected = true;
                   2931:     }
                   2932: 
                   2933:     function changeOneScore(partid,user) {
1.125     ng       2934: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2935: 	if (selval[1].selected || selval[2].selected) {
                   2936: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2937: 	    if (selval[2].selected) {
                   2938: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2939: 	    }
1.269     raeburn  2940:         }
1.42      ng       2941:     }
                   2942: 
                   2943:     function resetEntry(numpart) {
                   2944: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2945: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2946: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2947: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2948: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2949: 	    for (var i=0; i<radioButton.length; i++) {
                   2950: 		radioButton[i].checked=false;
                   2951: 
                   2952: 	    }
                   2953: 	    textbox.value = "";
                   2954: 	    selval[0].selected = true;
                   2955: 
                   2956: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2957: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2958: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2959: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2960: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2961: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2962: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2963: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2964: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2965: 		if (saveselval == "excused") {
1.43      ng       2966: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2967: 		} else {
1.43      ng       2968: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2969: 		}
                   2970: 	    }
1.41      ng       2971: 	}
1.42      ng       2972:     }
                   2973: 
1.41      ng       2974: </script>
                   2975: VIEWJAVASCRIPT
1.42      ng       2976: }
                   2977: 
1.44      ng       2978: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2979: sub viewgrades {
                   2980:     my ($request) = shift;
                   2981:     &viewgrades_js($request);
1.41      ng       2982: 
1.324     albertel 2983:     my ($symb) = &get_symb($request);
1.168     albertel 2984:     #need to make sure we have the correct data for later EXT calls, 
                   2985:     #thus invalidate the cache
                   2986:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2987:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2988:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2989:     &Apache::lonnet::clear_EXT_cache_status();
                   2990: 
1.398     albertel 2991:     my $result='<h3><span class="LC_info">'.&mt('Manual Grading').'</span></h3>';
                   2992:     $result.='<h4><b>Current Resource: </b>'.$env{'form.probTitle'}.'</h4>'."\n";
1.41      ng       2993: 
                   2994:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2995:     $result.=&jscriptNform($symb);
1.41      ng       2996: 
1.44      ng       2997:     #beginning of class grading form
1.41      ng       2998:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.418     albertel 2999: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.38      ng       3000: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.432     banghart 3001: 	&build_section_inputs().
1.257     albertel 3002: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   3003: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   3004: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       3005: 
1.126     ng       3006:     my $sectionClass;
1.430     banghart 3007:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
1.257     albertel 3008:     if ($env{'form.section'} eq 'all') {
1.126     ng       3009: 	$sectionClass='Class </h3>';
1.257     albertel 3010:     } elsif ($env{'form.section'} eq 'none') {
1.431     banghart 3011: 	$sectionClass=&mt('Students in no Section').'</h3>';
1.52      albertel 3012:     } else {
1.431     banghart 3013: 	$sectionClass=&mt('Students in Section(s) [_1]',$section_display).'</h3>';
1.52      albertel 3014:     }
1.431     banghart 3015:     $result.='<h3>'.&mt('Assign Common Grade To [_1]',$sectionClass);
1.52      albertel 3016:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   3017: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       3018:     #radio buttons/text box for assigning points for a section or class.
                   3019:     #handles different parts of a problem
1.375     albertel 3020:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       3021:     my %weight = ();
                   3022:     my $ctsparts = 0;
1.41      ng       3023:     $result.='<table border="0">';
1.45      ng       3024:     my %seen = ();
1.375     albertel 3025:     my @part_response_id = &flatten_responseType($responseType);
                   3026:     foreach my $part_response_id (@part_response_id) {
                   3027:     	my ($partid,$respid) = @{ $part_response_id };
                   3028: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       3029: 	next if $seen{$partid};
                   3030: 	$seen{$partid}++;
1.375     albertel 3031: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       3032: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   3033: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   3034: 
1.44      ng       3035: 	$result.='<input type="hidden" name="partid_'.
                   3036: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   3037: 	$result.='<input type="hidden" name="weight_'.
                   3038: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 3039: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 3040: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       3041: 	$result.='<table border="0"><tr>';  
1.41      ng       3042: 	my $ctr = 0;
1.42      ng       3043: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 3044: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 3045: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 3046: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       3047: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   3048: 	    $ctr++;
                   3049: 	}
                   3050: 	$result.='</tr></table>';
1.44      ng       3051: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 3052: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   3053: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       3054: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   3055: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 3056: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 3057: 		$weight{$partid}.')"> '.
1.401     albertel 3058: 	    '<option selected="selected"> </option>'.
1.125     ng       3059: 	    '<option>excused</option>'.
1.265     www      3060: 	    '<option>reset status</option></select></td>'.
1.266     albertel 3061:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       3062: 	$ctsparts++;
1.41      ng       3063:     }
1.52      albertel 3064:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   3065: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.391     banghart 3066:     $result.='<input type="button" value="Revert to Default" '.
1.417     albertel 3067: 	'onClick="javascript:resetEntry('.$ctsparts.');" target="_self" />';
1.41      ng       3068: 
1.44      ng       3069:     #table listing all the students in a section/class
                   3070:     #header of table
1.126     ng       3071:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       3072:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       3073: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       3074: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 3075:     my (@parts) = sort(&getpartlist($symb));
                   3076:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  3077:     my @partids = ();
1.41      ng       3078:     foreach my $part (@parts) {
                   3079: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       3080: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       3081: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 3082: 	my ($partid) = &split_part_type($part);
1.269     raeburn  3083:         push(@partids, $partid);
1.324     albertel 3084: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       3085: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 3086: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   3087: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       3088: 	    next;
1.207     albertel 3089: 	} else {
                   3090: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       3091: 	}
1.53      albertel 3092: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 3093: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       3094:     }
                   3095:     $result.='</tr>';
1.44      ng       3096: 
1.270     albertel 3097:     my %last_resets = 
                   3098: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  3099: 
1.41      ng       3100:     #get info for each student
1.44      ng       3101:     #list all the students - with points and grade status
1.257     albertel 3102:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       3103:     my $ctr = 0;
1.294     albertel 3104:     foreach (sort 
                   3105: 	     {
                   3106: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3107: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3108: 		 }
                   3109: 		 return $a cmp $b;
                   3110: 	     } (keys(%$fullname))) {
1.126     ng       3111: 	$ctr++;
1.324     albertel 3112: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  3113: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       3114:     }
                   3115:     $result.='</table></td></tr></table>';
                   3116:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       3117:     $result.='<input type="button" value="Save" '.
1.417     albertel 3118: 	'onClick="javascript:submit();" target="_self" /></form>'."\n";
1.96      albertel 3119:     if (scalar(%$fullname) eq 0) {
                   3120: 	my $colspan=3+scalar(@parts);
1.433     banghart 3121: 	my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3122: 	$result='<span class="LC_warning">'.
                   3123: 	    &mt('There are no students in section(s) [_1] with enrollment status [_2] to modify or grade',
                   3124: 	        $section_display, $env{'form.Status'}).
                   3125: 	    '</span>';
1.96      albertel 3126:     }
1.324     albertel 3127:     $result.=&show_grading_menu_form($symb);
1.41      ng       3128:     return $result;
                   3129: }
                   3130: 
1.44      ng       3131: #--- call by previous routine to display each student
1.41      ng       3132: sub viewstudentgrade {
1.324     albertel 3133:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3134:     my ($uname,$udom) = split(/:/,$student);
                   3135:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3136:     my %aggregates = (); 
1.233     albertel 3137:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3138: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3139: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3140: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.417     albertel 3141: 	'\');" target="_self">'.$fullname.'</a> '.
1.398     albertel 3142: 	'<span class="LC_internal_info">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</span></td>'."\n";
1.281     albertel 3143:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3144:     foreach my $apart (@$parts) {
                   3145: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3146: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3147:         $result.='<td align="center">';
1.269     raeburn  3148:         my ($aggtries,$totaltries);
                   3149:         unless (exists($aggregates{$part})) {
1.270     albertel 3150: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3151: 
                   3152: 	    $aggtries = $totaltries;
1.269     raeburn  3153:             if ($$last_resets{$part}) {  
1.270     albertel 3154:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3155: 					   $part);
                   3156:             }
1.269     raeburn  3157:             $result.='<input type="hidden" name="'.
                   3158:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3159:             $result.='<input type="hidden" name="'.
                   3160:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3161:             $aggregates{$part} = 1;
                   3162:         }
1.41      ng       3163: 	if ($type eq 'awarded') {
1.320     albertel 3164: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3165: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3166: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3167: 	    $result.='<input type="text" name="'.
1.89      albertel 3168: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3169: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3170: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3171: 	} elsif ($type eq 'solved') {
                   3172: 	    my ($status,$foo)=split(/_/,$score,2);
                   3173: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3174: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3175: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3176: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3177: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3178: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.401     albertel 3179: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="selected">excused</option>' 
                   3180: 		: '<option selected="selected"> </option><option>excused</option>')."\n";
1.125     ng       3181: 	    $result.='<option>reset status</option>';
1.126     ng       3182: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3183: 	} else {
                   3184: 	    $result.='<input type="hidden" name="'.
                   3185: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3186: 		    "\n";
1.233     albertel 3187: 	    $result.='<input type="text" name="'.
1.122     ng       3188: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3189: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3190: 	}
                   3191:     }
                   3192:     $result.='</tr>';
                   3193:     return $result;
1.38      ng       3194: }
                   3195: 
1.44      ng       3196: #--- change scores for all the students in a section/class
                   3197: #    record does not get update if unchanged
1.38      ng       3198: sub editgrades {
1.41      ng       3199:     my ($request) = @_;
                   3200: 
1.324     albertel 3201:     my $symb=&get_symb($request);
1.433     banghart 3202:     my $section_display = join (", ",&Apache::loncommon::get_env_multiple('form.section'));
                   3203:     my $title='<h3><span class="LC_info">'.&mt('Current Grade Status').'</span></h3>';
                   3204:     $title.='<h4>'.&mt('<b>Current Resource: </b>[_1]',$env{'form.probTitle'}).'</h4><br />'."\n";
                   3205:     $title.='<h4>'.&mt('<b>Section: </b>[_1]',$section_display).'</h4>'."\n";
1.126     ng       3206: 
1.44      ng       3207:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3208:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3209: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3210: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3211: 
                   3212:     my %scoreptr = (
                   3213: 		    'correct'  =>'correct_by_override',
                   3214: 		    'incorrect'=>'incorrect_by_override',
                   3215: 		    'excused'  =>'excused',
                   3216: 		    'ungraded' =>'ungraded_attempted',
                   3217: 		    'nothing'  => '',
                   3218: 		    );
1.257     albertel 3219:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3220: 
1.44      ng       3221:     my (@partid);
                   3222:     my %weight = ();
1.54      albertel 3223:     my %columns = ();
1.44      ng       3224:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3225: 
1.324     albertel 3226:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3227:     my $header;
1.257     albertel 3228:     while ($ctr < $env{'form.totalparts'}) {
                   3229: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3230: 	push @partid,$partid;
1.257     albertel 3231: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3232: 	$ctr++;
1.54      albertel 3233:     }
1.324     albertel 3234:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3235:     foreach my $partid (@partid) {
                   3236: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3237: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3238: 	$columns{$partid}=2;
                   3239: 	foreach my $stores (@parts) {
                   3240: 	    my ($part,$type) = &split_part_type($stores);
                   3241: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3242: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3243: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3244: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3245: 	    $display =~ s/Number of Attempts/Tries/;
                   3246: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3247: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3248: 	    $columns{$partid}+=2;
                   3249: 	}
                   3250:     }
                   3251:     foreach my $partid (@partid) {
1.324     albertel 3252: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3253: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3254: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3255: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3256: 
1.44      ng       3257:     }
                   3258:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3259:     $result .= $header;
1.44      ng       3260:     $result .= '</tr>'."\n";
1.93      albertel 3261:     my $noupdate;
1.126     ng       3262:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3263:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3264: 	my $line;
1.257     albertel 3265: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3266: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3267: 	my %newrecord;
                   3268: 	my $updateflag = 0;
1.281     albertel 3269: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3270: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3271: 	if (!&canmodify($usec)) {
1.126     ng       3272: 	    my $numcols=scalar(@partid)*4+2;
1.399     albertel 3273: 	    $noupdate.=$line."<td colspan=\"$numcols\"><span class=\"LC_warning\">Not allowed to modify student</span></td></tr>";
1.105     albertel 3274: 	    next;
                   3275: 	}
1.269     raeburn  3276:         my %aggregate = ();
                   3277:         my $aggregateflag = 0;
1.281     albertel 3278: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3279: 	foreach (@partid) {
1.257     albertel 3280: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3281: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3282: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3283: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3284: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3285: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3286: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3287: 	    my $score;
                   3288: 	    if ($partial eq '') {
1.257     albertel 3289: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3290: 	    } elsif ($partial > 0) {
                   3291: 		$score = 'correct_by_override';
                   3292: 	    } elsif ($partial == 0) {
                   3293: 		$score = 'incorrect_by_override';
                   3294: 	    }
1.257     albertel 3295: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3296: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3297: 
1.292     albertel 3298: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3299: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3300: 	    if ($dropMenu eq 'reset status' &&
                   3301: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3302: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3303: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3304: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3305: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3306: 		$updateflag = 1;
1.269     raeburn  3307:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3308:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3309:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3310:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3311:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3312:                     $aggregateflag = 1;
                   3313:                 }
1.139     albertel 3314: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3315: 		$updateflag = 1;
                   3316: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3317: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3318: 		$rec_update++;
1.125     ng       3319: 	    }
                   3320: 
1.93      albertel 3321: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3322: 		'<td align="center">'.$awarded.
                   3323: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3324: 
1.54      albertel 3325: 
                   3326: 	    my $partid=$_;
                   3327: 	    foreach my $stores (@parts) {
                   3328: 		my ($part,$type) = &split_part_type($stores);
                   3329: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3330: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3331: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3332: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3333: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3334: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3335: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3336: 		    $updateflag=1;
                   3337: 		}
1.93      albertel 3338: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3339: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3340: 	    }
1.44      ng       3341: 	}
1.93      albertel 3342: 	$line.='</tr>'."\n";
1.301     albertel 3343: 
                   3344: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3345: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3346: 
1.44      ng       3347: 	if ($updateflag) {
                   3348: 	    $count++;
1.257     albertel 3349: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3350: 				    $udom,$uname);
1.301     albertel 3351: 
                   3352: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3353: 					      $cnum,$udom,$uname)) {
                   3354: 		# need to figure out if should be in queue.
                   3355: 		my %record =  
                   3356: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3357: 					     $udom,$uname);
                   3358: 		my $all_graded = 1;
                   3359: 		my $none_graded = 1;
                   3360: 		foreach my $part (@parts) {
                   3361: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3362: 			$all_graded = 0;
                   3363: 		    } else {
                   3364: 			$none_graded = 0;
                   3365: 		    }
                   3366: 		}
                   3367: 
                   3368: 		if ($all_graded || $none_graded) {
                   3369: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3370: 							   $symb,$cdom,$cnum,
                   3371: 							   $udom,$uname);
                   3372: 		}
                   3373: 	    }
                   3374: 
1.126     ng       3375: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3376: 	    $updateCtr++;
1.93      albertel 3377: 	} else {
1.126     ng       3378: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3379: 	    $noupdateCtr++;
1.44      ng       3380: 	}
1.269     raeburn  3381:         if ($aggregateflag) {
                   3382:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3383: 				  $cdom,$cnum);
1.269     raeburn  3384:         }
1.93      albertel 3385:     }
                   3386:     if ($noupdate) {
1.126     ng       3387: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3388: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3389: 	$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       3390:     }
1.72      ng       3391:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3392: 	&show_grading_menu_form ($symb);
1.125     ng       3393:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3394: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3395: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3396:     return $title.$msg.$result;
1.5       albertel 3397: }
1.54      albertel 3398: 
                   3399: sub split_part_type {
                   3400:     my ($partstr) = @_;
                   3401:     my ($temp,@allparts)=split(/_/,$partstr);
                   3402:     my $type=pop(@allparts);
1.439   ! albertel 3403:     my $part=join('_',@allparts);
1.54      albertel 3404:     return ($part,$type);
                   3405: }
                   3406: 
1.44      ng       3407: #------------- end of section for handling grading by section/class ---------
                   3408: #
                   3409: #----------------------------------------------------------------------------
                   3410: 
1.5       albertel 3411: 
1.44      ng       3412: #----------------------------------------------------------------------------
                   3413: #
                   3414: #-------------------------- Next few routines handles grading by csv upload
                   3415: #
                   3416: #--- Javascript to handle csv upload
1.27      albertel 3417: sub csvupload_javascript_reverse_associate {
1.246     albertel 3418:     my $error1=&mt('You need to specify the username or ID');
                   3419:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3420:   return(<<ENDPICK);
                   3421:   function verify(vf) {
                   3422:     var foundsomething=0;
                   3423:     var founduname=0;
1.243     albertel 3424:     var foundID=0;
1.27      albertel 3425:     for (i=0;i<=vf.nfields.value;i++) {
                   3426:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3427:       if (i==0 && tw!=0) { foundID=1; }
                   3428:       if (i==1 && tw!=0) { founduname=1; }
                   3429:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3430:     }
1.246     albertel 3431:     if (founduname==0 && foundID==0) {
                   3432: 	alert('$error1');
                   3433: 	return;
1.27      albertel 3434:     }
                   3435:     if (foundsomething==0) {
1.246     albertel 3436: 	alert('$error2');
                   3437: 	return;
1.27      albertel 3438:     }
                   3439:     vf.submit();
                   3440:   }
                   3441:   function flip(vf,tf) {
                   3442:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3443:     var i;
                   3444:     for (i=0;i<=vf.nfields.value;i++) {
                   3445:       //can not pick the same destination field for both name and domain
                   3446:       if (((i ==0)||(i ==1)) && 
                   3447:           ((tf==0)||(tf==1)) && 
                   3448:           (i!=tf) &&
                   3449:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3450:         eval('vf.f'+i+'.selectedIndex=0;')
                   3451:       }
                   3452:     }
                   3453:   }
                   3454: ENDPICK
                   3455: }
                   3456: 
                   3457: sub csvupload_javascript_forward_associate {
1.246     albertel 3458:     my $error1=&mt('You need to specify the username or ID');
                   3459:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3460:   return(<<ENDPICK);
                   3461:   function verify(vf) {
                   3462:     var foundsomething=0;
                   3463:     var founduname=0;
1.243     albertel 3464:     var foundID=0;
1.27      albertel 3465:     for (i=0;i<=vf.nfields.value;i++) {
                   3466:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3467:       if (tw==1) { foundID=1; }
                   3468:       if (tw==2) { founduname=1; }
                   3469:       if (tw>3) { foundsomething=1; }
1.27      albertel 3470:     }
1.246     albertel 3471:     if (founduname==0 && foundID==0) {
                   3472: 	alert('$error1');
                   3473: 	return;
1.27      albertel 3474:     }
                   3475:     if (foundsomething==0) {
1.246     albertel 3476: 	alert('$error2');
                   3477: 	return;
1.27      albertel 3478:     }
                   3479:     vf.submit();
                   3480:   }
                   3481:   function flip(vf,tf) {
                   3482:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3483:     var i;
                   3484:     //can not pick the same destination field twice
                   3485:     for (i=0;i<=vf.nfields.value;i++) {
                   3486:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3487:         eval('vf.f'+i+'.selectedIndex=0;')
                   3488:       }
                   3489:     }
                   3490:   }
                   3491: ENDPICK
                   3492: }
                   3493: 
1.26      albertel 3494: sub csvuploadmap_header {
1.324     albertel 3495:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3496:     my $javascript;
1.257     albertel 3497:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3498: 	$javascript=&csvupload_javascript_reverse_associate();
                   3499:     } else {
                   3500: 	$javascript=&csvupload_javascript_forward_associate();
                   3501:     }
1.45      ng       3502: 
1.324     albertel 3503:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3504:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3505:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3506:     $symb = &Apache::lonenc::check_encrypt($symb);
1.41      ng       3507:     $request->print(<<ENDPICK);
1.26      albertel 3508: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3509: <h3><span class="LC_info">Uploading Class Grades</span></h3>
1.45      ng       3510: $result
1.326     albertel 3511: <hr />
1.26      albertel 3512: <h3>Identify fields</h3>
                   3513: Total number of records found in file: $distotal <hr />
                   3514: Enter as many fields as you can. The system will inform you and bring you back
                   3515: to this page if the data selected is insufficient to run your class.<hr />
                   3516: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3517: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3518: <input type="hidden" name="associate"  value="" />
                   3519: <input type="hidden" name="phase"      value="three" />
                   3520: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3521: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3522: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3523: <input type="hidden" name="upfile_associate" 
1.257     albertel 3524:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3525: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3526: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3527: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3528: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3529: <hr />
                   3530: <script type="text/javascript" language="Javascript">
                   3531: $javascript
                   3532: </script>
                   3533: ENDPICK
1.118     ng       3534:     return '';
1.26      albertel 3535: 
                   3536: }
                   3537: 
                   3538: sub csvupload_fields {
1.324     albertel 3539:     my ($symb) = @_;
                   3540:     my (@parts) = &getpartlist($symb);
1.243     albertel 3541:     my @fields=(['ID','Student ID'],
                   3542: 		['username','Student Username'],
                   3543: 		['domain','Student Domain']);
1.324     albertel 3544:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3545:     foreach my $part (sort(@parts)) {
                   3546: 	my @datum;
                   3547: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3548: 	my $name=$part;
                   3549: 	if  (!$display) { $display = $name; }
                   3550: 	@datum=($name,$display);
1.244     albertel 3551: 	if ($name=~/^stores_(.*)_awarded/) {
                   3552: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3553: 	}
1.41      ng       3554: 	push(@fields,\@datum);
                   3555:     }
                   3556:     return (@fields);
1.26      albertel 3557: }
                   3558: 
                   3559: sub csvuploadmap_footer {
1.41      ng       3560:     my ($request,$i,$keyfields) =@_;
                   3561:     $request->print(<<ENDPICK);
1.26      albertel 3562: </table>
                   3563: <input type="hidden" name="nfields" value="$i" />
                   3564: <input type="hidden" name="keyfields" value="$keyfields" />
                   3565: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3566: </form>
                   3567: ENDPICK
                   3568: }
                   3569: 
1.283     albertel 3570: sub checkforfile_js {
1.86      ng       3571:     my $result =<<CSVFORMJS;
                   3572: <script type="text/javascript" language="javascript">
                   3573:     function checkUpload(formname) {
                   3574: 	if (formname.upfile.value == "") {
                   3575: 	    alert("Please use the browse button to select a file from your local directory.");
                   3576: 	    return false;
                   3577: 	}
                   3578: 	formname.submit();
                   3579:     }
                   3580:     </script>
                   3581: CSVFORMJS
1.283     albertel 3582:     return $result;
                   3583: }
                   3584: 
                   3585: sub upcsvScores_form {
                   3586:     my ($request) = shift;
1.324     albertel 3587:     my ($symb)=&get_symb($request);
1.283     albertel 3588:     if (!$symb) {return '';}
                   3589:     my $result=&checkforfile_js();
1.257     albertel 3590:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3591:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3592:     $result.=$table;
1.326     albertel 3593:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3594:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3595:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3596: 	'.</b></td></tr>'."\n";
                   3597:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3598:     my $upload=&mt("Upload Scores");
1.86      ng       3599:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3600:     my $ignore=&mt('Ignore First Line');
1.418     albertel 3601:     $symb = &Apache::lonenc::check_encrypt($symb);
1.86      ng       3602:     $result.=<<ENDUPFORM;
1.106     albertel 3603: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3604: <input type="hidden" name="symb" value="$symb" />
                   3605: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3606: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3607: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3608: $upfile_select
1.370     www      3609: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3610: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3611: </form>
                   3612: ENDUPFORM
1.370     www      3613:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3614:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3615:     .'</td></tr></table>'."\n";
1.86      ng       3616:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3617:     $result.=&show_grading_menu_form($symb);
1.86      ng       3618:     return $result;
                   3619: }
                   3620: 
                   3621: 
1.26      albertel 3622: sub csvuploadmap {
1.41      ng       3623:     my ($request)= @_;
1.324     albertel 3624:     my ($symb)=&get_symb($request);
1.41      ng       3625:     if (!$symb) {return '';}
1.72      ng       3626: 
1.41      ng       3627:     my $datatoken;
1.257     albertel 3628:     if (!$env{'form.datatoken'}) {
1.41      ng       3629: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3630:     } else {
1.257     albertel 3631: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3632: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3633:     }
1.41      ng       3634:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3635:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3636:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3637:     my ($i,$keyfields);
                   3638:     if (@records) {
1.324     albertel 3639: 	my @fields=&csvupload_fields($symb);
1.45      ng       3640: 
1.257     albertel 3641: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3642: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3643: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3644: 							  \@fields);
                   3645: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3646: 	    chop($keyfields);
                   3647: 	} else {
                   3648: 	    unshift(@fields,['none','']);
                   3649: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3650: 							    \@fields);
1.311     banghart 3651:             foreach my $rec (@records) {
                   3652:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3653:                 if (%temp) {
                   3654:                     $keyfields=join(',',sort(keys(%temp)));
                   3655:                     last;
                   3656:                 }
                   3657:             }
1.41      ng       3658: 	}
                   3659:     }
                   3660:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3661:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3662: 
1.41      ng       3663:     return '';
1.27      albertel 3664: }
                   3665: 
1.246     albertel 3666: sub csvuploadoptions {
1.41      ng       3667:     my ($request)= @_;
1.324     albertel 3668:     my ($symb)=&get_symb($request);
1.257     albertel 3669:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3670:     my $ignore=&mt('Ignore First Line');
                   3671:     $request->print(<<ENDPICK);
                   3672: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.398     albertel 3673: <h3><span class="LC_info">Uploading Class Grade Options</span></h3>
1.246     albertel 3674: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3675: <!--
1.246     albertel 3676: <p>
                   3677: <label>
                   3678:    <input type="checkbox" name="show_full_results" />
                   3679:    Show a table of all changes
                   3680: </label>
                   3681: </p>
1.302     albertel 3682: -->
1.246     albertel 3683: <p>
                   3684: <label>
                   3685:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3686:    Overwrite any existing score
                   3687: </label>
                   3688: </p>
                   3689: ENDPICK
                   3690:     my %fields=&get_fields();
                   3691:     if (!defined($fields{'domain'})) {
1.257     albertel 3692: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3693: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3694:     }
1.257     albertel 3695:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3696: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3697: 	my $cleankey=$1;
                   3698: 	if ($cleankey eq 'command') { next; }
                   3699: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3700: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3701:     }
                   3702:     # FIXME do a check for any duplicated user ids...
                   3703:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3704:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3705: <hr /></form>'."\n");
1.324     albertel 3706:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3707:     return '';
                   3708: }
                   3709: 
                   3710: sub get_fields {
                   3711:     my %fields;
1.257     albertel 3712:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3713:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3714: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3715: 	    if ($env{'form.f'.$i} ne 'none') {
                   3716: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3717: 	    }
                   3718: 	} else {
1.257     albertel 3719: 	    if ($env{'form.f'.$i} ne 'none') {
                   3720: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3721: 	    }
                   3722: 	}
1.27      albertel 3723:     }
1.246     albertel 3724:     return %fields;
                   3725: }
                   3726: 
                   3727: sub csvuploadassign {
                   3728:     my ($request)= @_;
1.324     albertel 3729:     my ($symb)=&get_symb($request);
1.246     albertel 3730:     if (!$symb) {return '';}
1.345     bowersj2 3731:     my $error_msg = '';
1.246     albertel 3732:     &Apache::loncommon::load_tmp_file($request);
                   3733:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3734:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3735:     my %fields=&get_fields();
1.41      ng       3736:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3737:     my $courseid=$env{'request.course.id'};
1.97      albertel 3738:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3739:     my @notallowed;
1.41      ng       3740:     my @skipped;
                   3741:     my $countdone=0;
                   3742:     foreach my $grade (@gradedata) {
                   3743: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3744: 	my $domain;
                   3745: 	if ($entries{$fields{'domain'}}) {
                   3746: 	    $domain=$entries{$fields{'domain'}};
                   3747: 	} else {
1.257     albertel 3748: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3749: 	}
1.243     albertel 3750: 	$domain=~s/\s//g;
1.41      ng       3751: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3752: 	$username=~s/\s//g;
1.243     albertel 3753: 	if (!$username) {
                   3754: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3755: 	    $id=~s/\s//g;
1.243     albertel 3756: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3757: 	    $username=$ids{$id};
                   3758: 	}
1.41      ng       3759: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3760: 	    my $id=$entries{$fields{'ID'}};
                   3761: 	    $id=~s/\s//g;
                   3762: 	    if ($id) {
                   3763: 		push(@skipped,"$id:$domain");
                   3764: 	    } else {
                   3765: 		push(@skipped,"$username:$domain");
                   3766: 	    }
1.41      ng       3767: 	    next;
                   3768: 	}
1.108     albertel 3769: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3770: 	if (!&canmodify($usec)) {
                   3771: 	    push(@notallowed,"$username:$domain");
                   3772: 	    next;
                   3773: 	}
1.244     albertel 3774: 	my %points;
1.41      ng       3775: 	my %grades;
                   3776: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3777: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3778: 		$dest eq 'domain') { next; }
                   3779: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3780: 	    if ($dest=~/stores_(.*)_points/) {
                   3781: 		my $part=$1;
                   3782: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3783: 					      $symb,$domain,$username);
1.345     bowersj2 3784:                 if ($wgt) {
                   3785:                     $entries{$fields{$dest}}=~s/\s//g;
                   3786:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3787:                     my $award='correct_by_override';
                   3788:                     $grades{"resource.$part.awarded"}=$pcr;
                   3789:                     $grades{"resource.$part.solved"}=$award;
                   3790:                     $points{$part}=1;
                   3791:                 } else {
                   3792:                     $error_msg = "<br />" .
                   3793:                         &mt("Some point values were assigned"
                   3794:                             ." for problems with a weight "
                   3795:                             ."of zero. These values were "
                   3796:                             ."ignored.");
                   3797:                 }
1.244     albertel 3798: 	    } else {
                   3799: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3800: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3801: 		my $store_key=$dest;
                   3802: 		$store_key=~s/^stores/resource/;
                   3803: 		$store_key=~s/_/\./g;
                   3804: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3805: 	    }
1.41      ng       3806: 	}
1.398     albertel 3807: 	if (! %grades) { push(@skipped,"$username:$domain no data to save"); }
1.257     albertel 3808: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3809: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3810: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3811: 					   $env{'request.course.id'},
                   3812: 					   $domain,$username);
                   3813: 	if ($result eq 'ok') {
                   3814: 	    $request->print('.');
                   3815: 	} else {
                   3816: 	    $request->print("<p>
1.398     albertel 3817:                               <span class=\"LC_error\">
                   3818:                                  Failed to save student $username:$domain.
                   3819:                                  Message when trying to save was ($result)
                   3820:                               </span>
1.302     albertel 3821:                              </p>" );
                   3822: 	}
1.41      ng       3823: 	$request->rflush();
                   3824: 	$countdone++;
                   3825:     }
1.398     albertel 3826:     $request->print("<br />Saved $countdone students\n");
1.41      ng       3827:     if (@skipped) {
1.398     albertel 3828: 	$request->print('<p><h4><b>Skipped Students</b></h4></p>');
1.106     albertel 3829: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3830:     }
                   3831:     if (@notallowed) {
1.398     albertel 3832: 	$request->print('<p><span class="LC_error">Students Not Allowed to Modify</span></p>');
1.106     albertel 3833: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3834:     }
1.106     albertel 3835:     $request->print("<br />\n");
1.324     albertel 3836:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3837:     return $error_msg;
1.26      albertel 3838: }
1.44      ng       3839: #------------- end of section for handling csv file upload ---------
                   3840: #
                   3841: #-------------------------------------------------------------------
                   3842: #
1.122     ng       3843: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3844: #
                   3845: #--- Select a page/sequence and a student to grade
1.68      ng       3846: sub pickStudentPage {
                   3847:     my ($request) = shift;
                   3848: 
                   3849:     $request->print(<<LISTJAVASCRIPT);
                   3850: <script type="text/javascript" language="javascript">
                   3851: 
                   3852: function checkPickOne(formname) {
1.76      ng       3853:     if (radioSelection(formname.student) == null) {
1.68      ng       3854: 	alert("Please select the student you wish to grade.");
                   3855: 	return;
                   3856:     }
1.125     ng       3857:     ptr = pullDownSelection(formname.selectpage);
                   3858:     formname.page.value = formname["page"+ptr].value;
                   3859:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3860:     formname.submit();
                   3861: }
                   3862: 
                   3863: </script>
                   3864: LISTJAVASCRIPT
1.118     ng       3865:     &commonJSfunctions($request);
1.324     albertel 3866:     my ($symb) = &get_symb($request);
1.257     albertel 3867:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3868:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3869:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3870: 
1.398     albertel 3871:     my $result='<h3><span class="LC_info">&nbsp;'.
                   3872: 	'Manual Grading by Page or Sequence</span></h3>';
1.68      ng       3873: 
1.80      ng       3874:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3875:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.423     albertel 3876:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 3877:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3878: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3879: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3880:     my $ctr=0;
1.68      ng       3881:     foreach (@$titles) {
                   3882: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3883: 	$result.='<option value="'.$ctr.'" '.
1.401     albertel 3884: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.71      ng       3885: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3886: 	$ctr++;
1.68      ng       3887:     }
1.326     albertel 3888:     $result.= '</select>'."<br />\n";
1.70      ng       3889:     $ctr=0;
                   3890:     foreach (@$titles) {
                   3891: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3892: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3893: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3894: 	$ctr++;
                   3895:     }
1.72      ng       3896:     $result.='<input type="hidden" name="page" />'."\n".
                   3897: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3898: 
1.401     albertel 3899:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="checked" /> no </label>'."\n".
1.288     albertel 3900: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3901: 
1.71      ng       3902:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3903: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
1.401     albertel 3904: 	'<label><input type="radio" name="lastSub" value="datesub" checked="checked" /> by dates and submissions</label>'."\n".
1.288     albertel 3905: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.432     banghart 3906:     
                   3907:     $result.=&build_section_inputs();
                   3908:     $result.='<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3909: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.418     albertel 3910: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 3911: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3912: 
1.382     albertel 3913:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
                   3914: 	'<input type="text" name="CODE" value="" /><br />'."\n";
                   3915: 
1.80      ng       3916:     $result.='&nbsp;<input type="button" '.
1.126     ng       3917: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3918: 
1.68      ng       3919:     $request->print($result);
                   3920: 
1.326     albertel 3921:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3922: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3923: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3924: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3925: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3926: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3927: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3928:  
1.76      ng       3929:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3930:     my $ptr = 1;
1.294     albertel 3931:     foreach my $student (sort 
                   3932: 			 {
                   3933: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3934: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3935: 			     }
                   3936: 			     return $a cmp $b;
                   3937: 			 } (keys(%$fullname))) {
1.68      ng       3938: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3939: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3940: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3941: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3942: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3943: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3944: 	$ptr++;
                   3945:     }
1.381     albertel 3946:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3947:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3948:     $studentTable.='<input type="button" '.
                   3949: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3950: 
1.324     albertel 3951:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3952:     $request->print($studentTable);
                   3953: 
                   3954:     return '';
                   3955: }
                   3956: 
                   3957: sub getSymbMap {
1.132     bowersj2 3958:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3959: 
                   3960:     my %symbx = ();
                   3961:     my @titles = ();
1.117     bowersj2 3962:     my $minder = 0;
                   3963: 
                   3964:     # Gather every sequence that has problems.
1.240     albertel 3965:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3966: 					       1,0,1);
1.117     bowersj2 3967:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3968: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3969: 	    my $title = $minder.'.'.
                   3970: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3971: 	    push(@titles, $title); # minder in case two titles are identical
                   3972: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3973: 	    $minder++;
1.241     albertel 3974: 	}
1.68      ng       3975:     }
                   3976:     return \@titles,\%symbx;
                   3977: }
                   3978: 
1.72      ng       3979: #
                   3980: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3981: sub displayPage {
                   3982:     my ($request) = shift;
                   3983: 
1.324     albertel 3984:     my ($symb) = &get_symb($request);
1.257     albertel 3985:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3986:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3987:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3988:     my $pageTitle = $env{'form.page'};
1.103     albertel 3989:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3990:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3991:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3992: 
                   3993:     #need to make sure we have the correct data for later EXT calls, 
                   3994:     #thus invalidate the cache
                   3995:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3996:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3997:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3998:     &Apache::lonnet::clear_EXT_cache_status();
                   3999: 
1.103     albertel 4000:     if (!&canview($usec)) {
1.398     albertel 4001: 	$request->print('<span class="LC_warning">Unable to view requested student.('.$env{'form.student'}.')</span>');
1.324     albertel 4002: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 4003: 	return;
                   4004:     }
1.398     albertel 4005:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4006:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       4007: 	'</h3>'."\n";
1.382     albertel 4008:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4009: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
                   4010:     } else {
                   4011: 	delete($env{'form.CODE'});
                   4012:     }
1.71      ng       4013:     &sub_page_js($request);
                   4014:     $request->print($result);
                   4015: 
1.132     bowersj2 4016:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4017:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       4018:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4019:     if (!$map) {
1.398     albertel 4020: 	$request->print('<span class="LC_warning">Unable to view requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4021: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4022: 	return; 
                   4023:     }
1.68      ng       4024:     my $iterator = $navmap->getIterator($map->map_start(),
                   4025: 					$map->map_finish());
                   4026: 
1.71      ng       4027:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       4028: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 4029: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   4030: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       4031: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 4032: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.418     albertel 4033: 	'<input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.125     ng       4034: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 4035: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       4036: 
1.382     albertel 4037:     if (defined($env{'form.CODE'})) {
                   4038: 	$studentTable.=
                   4039: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
                   4040:     }
1.381     albertel 4041:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   4042: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       4043: 	'/check.gif" height="16" border="0" />';
                   4044: 
1.118     ng       4045:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   4046: 	' symbol.'."\n".
1.71      ng       4047: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   4048: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       4049: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 4050: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       4051: 
1.329     albertel 4052:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 4053:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       4054:     $iterator->next(); # skip the first BEGIN_MAP
                   4055:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 4056:     while ($depth > 0) {
1.68      ng       4057:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4058:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       4059: 
1.385     albertel 4060:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4061: 	    my $parts = $curRes->parts();
1.68      ng       4062:             my $title = $curRes->compTitle();
1.71      ng       4063: 	    my $symbx = $curRes->symb();
1.196     albertel 4064: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4065: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4066: 	    $studentTable.='<td valign="top">';
1.382     albertel 4067: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 4068: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 4069: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
1.383     albertel 4070: 					     undef,'both',\%form);
1.71      ng       4071: 	    } else {
1.382     albertel 4072: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       4073: 		$companswer =~ s|<form(.*?)>||g;
                   4074: 		$companswer =~ s|</form>||g;
1.71      ng       4075: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       4076: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 4077: #		    $request->print('match='.$1."<br />\n");
1.71      ng       4078: #		}
1.116     ng       4079: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 4080: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       4081: 	    }
                   4082: 
1.257     albertel 4083: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       4084: 
1.257     albertel 4085: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       4086: 		if ($record{'version'} eq '') {
1.398     albertel 4087: 		    $studentTable.='<br />&nbsp;<span class="LC_warning">No recorded submission for this problem</span><br />';
1.71      ng       4088: 		} else {
1.116     ng       4089: 		    my %responseType = ();
                   4090: 		    foreach my $partid (@{$parts}) {
1.147     albertel 4091: 			my @responseIds =$curRes->responseIds($partid);
                   4092: 			my @responseType =$curRes->responseType($partid);
                   4093: 			my %responseIds;
                   4094: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   4095: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   4096: 			}
                   4097: 			$responseType{$partid} = \%responseIds;
1.116     ng       4098: 		    }
1.148     albertel 4099: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 4100: 
1.71      ng       4101: 		}
1.257     albertel 4102: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   4103: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       4104: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 4105: 									$env{'request.course.id'},
1.71      ng       4106: 									'','.submission');
                   4107:  
                   4108: 	    }
1.103     albertel 4109: 	    if (&canmodify($usec)) {
                   4110: 		foreach my $partid (@{$parts}) {
                   4111: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   4112: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   4113: 		    $question++;
                   4114: 		}
1.196     albertel 4115: 		$prob++;
1.71      ng       4116: 	    }
                   4117: 	    $studentTable.='</td></tr>';
1.68      ng       4118: 
1.103     albertel 4119: 	}
1.68      ng       4120:         $curRes = $iterator->next();
                   4121:     }
                   4122: 
1.381     albertel 4123:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       4124: 	'<input type="button" value="Save" '.
1.381     albertel 4125: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       4126: 	'</form>'."\n";
1.324     albertel 4127:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4128:     $request->print($studentTable);
                   4129: 
                   4130:     return '';
1.119     ng       4131: }
                   4132: 
                   4133: sub displaySubByDates {
1.148     albertel 4134:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4135:     my $isCODE=0;
1.335     albertel 4136:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4137:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4138:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4139: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4140: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4141: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4142: 	'<td><b>Submission</b></td>'.
                   4143: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4144:     my ($version);
                   4145:     my %mark;
1.148     albertel 4146:     my %orders;
1.119     ng       4147:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4148:     if (!exists($$record{'1:timestamp'})) {
1.398     albertel 4149: 	return '<br />&nbsp;<span class="LC_warning">Nothing submitted - no attempts</span><br />';
1.147     albertel 4150:     }
1.335     albertel 4151: 
                   4152:     my $interaction;
1.119     ng       4153:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4154: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4155: 	if (exists($$record{$version.':resource.0.version'})) {
                   4156: 	    $interaction = $$record{$version.':resource.0.version'};
                   4157: 	}
                   4158: 
                   4159: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4160: 		             : "$version:resource");
                   4161: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4162: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4163: 	if ($isCODE) {
                   4164: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4165: 	}
1.119     ng       4166: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4167: 	my @displaySub = ();
                   4168: 	foreach my $partid (@{$parts}) {
1.335     albertel 4169: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4170: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4171: 	    
                   4172: 
1.122     ng       4173: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4174: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4175: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4176: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4177: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4178: 
                   4179: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4180: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4181: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4182: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.398     albertel 4183: 		    $displaySub[0].='<span class="LC_internal_info">(ID&nbsp;'.
                   4184: 			$responseId.')</span>&nbsp;<b>';
1.335     albertel 4185: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4186: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4187: 		    } else {
                   4188: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4189: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4190: 		    }
1.335     albertel 4191: 		    my $responseType=($isTask ? 'Task'
                   4192:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4193: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4194: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4195: 			$orders{$partid}->{$responseId}=
                   4196: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4197: 		    }
1.147     albertel 4198: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4199: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4200: 		}
                   4201: 	    }
1.335     albertel 4202: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4203: 		$displaySub[1].='Checked in by '.
                   4204: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4205: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4206: 		    '<br />';
                   4207: 	    }
                   4208: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4209: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4210: 		    lc($$record{"$where.$partid.award"}).' '.
                   4211: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4212: 		    '<br />';
                   4213: 	    }
1.335     albertel 4214: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4215: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4216: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4217: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4218: 		$displaySub[2].=
                   4219: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4220: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4221: 	    }
                   4222: 	}
                   4223: 	# needed because old essay regrader has not parts info
                   4224: 	if (exists $$record{"$version:resource.regrader"}) {
                   4225: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4226: 	}
                   4227: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4228: 	if ($displaySub[2]) {
                   4229: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4230: 	}
1.382     albertel 4231: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4232:     
1.119     ng       4233:     }
                   4234:     $studentTable.='</table></td></tr></table>';
                   4235:     return $studentTable;
1.71      ng       4236: }
                   4237: 
                   4238: sub updateGradeByPage {
                   4239:     my ($request) = shift;
                   4240: 
1.257     albertel 4241:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4242:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4243:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4244:     my $pageTitle = $env{'form.page'};
1.103     albertel 4245:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4246:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4247:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4248:     if (!&canmodify($usec)) {
1.398     albertel 4249: 	$request->print('<span class="LC_warning">Unable to modify requested student.('.$env{'form.student'}.'</span>');
1.324     albertel 4250: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4251: 	return;
                   4252:     }
1.398     albertel 4253:     my $result='<h3><span class="LC_info">&nbsp;'.$env{'form.title'}.'</span></h3>';
1.257     albertel 4254:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4255: 	'</h3>'."\n";
1.70      ng       4256: 
1.68      ng       4257:     $request->print($result);
                   4258: 
1.132     bowersj2 4259:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4260:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4261:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4262:     if (!$map) {
1.398     albertel 4263: 	$request->print('<span class="LC_warning">Unable to grade requested sequence. ('.$resUrl.')</span>');
1.324     albertel 4264: 	my ($symb)=&get_symb($request);
                   4265: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4266: 	return; 
                   4267:     }
1.71      ng       4268:     my $iterator = $navmap->getIterator($map->map_start(),
                   4269: 					$map->map_finish());
1.70      ng       4270: 
1.71      ng       4271:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4272: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4273: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4274: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4275: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4276: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4277: 
                   4278:     $iterator->next(); # skip the first BEGIN_MAP
                   4279:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4280:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4281:     while ($depth > 0) {
1.71      ng       4282:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4283:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4284: 
1.385     albertel 4285:         if (ref($curRes) && $curRes->is_problem()) {
1.91      albertel 4286: 	    my $parts = $curRes->parts();
1.71      ng       4287:             my $title = $curRes->compTitle();
                   4288: 	    my $symbx = $curRes->symb();
1.196     albertel 4289: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4290: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4291: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4292: 
                   4293: 	    my %newrecord=();
                   4294: 	    my @displayPts=();
1.269     raeburn  4295:             my %aggregate = ();
                   4296:             my $aggregateflag = 0;
1.71      ng       4297: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4298: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4299: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4300: 
1.257     albertel 4301: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4302: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4303: 		my $partial = $newpts/$wgt;
                   4304: 		my $score;
                   4305: 		if ($partial > 0) {
                   4306: 		    $score = 'correct_by_override';
1.125     ng       4307: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4308: 		    $score = 'incorrect_by_override';
                   4309: 		}
1.257     albertel 4310: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4311: 		if ($dropMenu eq 'excused') {
1.71      ng       4312: 		    $partial = '';
                   4313: 		    $score = 'excused';
1.125     ng       4314: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4315: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4316: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4317: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4318: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4319: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4320: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4321: 		    $changeflag++;
                   4322: 		    $newpts = '';
1.269     raeburn  4323:                     
                   4324:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4325:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4326:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4327:                     if ($aggtries > 0) {
                   4328:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4329:                         $aggregateflag = 1;
                   4330:                     }
1.71      ng       4331: 		}
1.324     albertel 4332: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4333: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4334: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4335: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4336: 		    '&nbsp;<br />';
1.207     albertel 4337: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4338: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4339: 		    '&nbsp;<br />';
1.71      ng       4340: 		$question++;
1.380     albertel 4341: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4342: 
1.71      ng       4343: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4344: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4345: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4346: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4347: 
                   4348: 		$changeflag++;
                   4349: 	    }
                   4350: 	    if (scalar(keys(%newrecord)) > 0) {
1.382     albertel 4351: 		my %record = 
                   4352: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
                   4353: 					     $udom,$uname);
                   4354: 
                   4355: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
                   4356: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
                   4357: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
                   4358: 		    $newrecord{'resource.CODE'} = '';
                   4359: 		}
1.257     albertel 4360: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4361: 					$udom,$uname);
1.382     albertel 4362: 		%record = &Apache::lonnet::restore($symbx,
                   4363: 						   $env{'request.course.id'},
                   4364: 						   $udom,$uname);
1.380     albertel 4365: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4366: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4367: 	    }
1.380     albertel 4368: 	    
1.269     raeburn  4369:             if ($aggregateflag) {
                   4370:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4371:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4372:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4373:             }
1.125     ng       4374: 
1.71      ng       4375: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4376: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4377: 		'</tr>';
1.68      ng       4378: 
1.196     albertel 4379: 	    $prob++;
1.68      ng       4380: 	}
1.71      ng       4381:         $curRes = $iterator->next();
1.68      ng       4382:     }
1.98      albertel 4383: 
1.71      ng       4384:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4385:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4386:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4387: 		  'The scores were changed for '.
                   4388: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4389:     $request->print($grademsg.$studentTable);
1.68      ng       4390: 
1.70      ng       4391:     return '';
                   4392: }
                   4393: 
1.72      ng       4394: #-------- end of section for handling grading by page/sequence ---------
                   4395: #
                   4396: #-------------------------------------------------------------------
                   4397: 
1.75      albertel 4398: #--------------------Scantron Grading-----------------------------------
                   4399: #
                   4400: #------ start of section for handling grading by page/sequence ---------
                   4401: 
1.423     albertel 4402: =pod
                   4403: 
                   4404: =head1 Bubble sheet grading routines
                   4405: 
1.424     albertel 4406:   For this documentation:
                   4407: 
                   4408:    'scanline' refers to the full line of characters
                   4409:    from the file that we are parsing that represents one entire sheet
                   4410: 
                   4411:    'bubble line' refers to the data
                   4412:    representing the line of bubbles that are on the physical bubble sheet
                   4413: 
                   4414: 
                   4415: The overall process is that a scanned in bubble sheet data is uploaded
                   4416: into a course. When a user wants to grade, they select a
                   4417: sequence/folder of resources, a file of bubble sheet info, and pick
                   4418: one of the predefined configurations for what each scanline looks
                   4419: like.
                   4420: 
                   4421: Next each scanline is checked for any errors of either 'missing
1.435     foxr     4422: bubbles' (it's an error because it may have been mis-scanned
1.424     albertel 4423: because too light bubbling), 'double bubble' (each bubble line should
                   4424: have no more that one letter picked), invalid or duplicated CODE,
                   4425: invalid student ID
                   4426: 
                   4427: If the CODE option is used that determines the randomization of the
                   4428: homework problems, either way the student ID is looked up into a
                   4429: username:domain.
                   4430: 
                   4431: During the validation phase the instructor can choose to skip scanlines. 
                   4432: 
1.435     foxr     4433: After the validation phase, there are now 3 bubble sheet files
1.424     albertel 4434: 
                   4435:   scantron_original_filename (unmodified original file)
                   4436:   scantron_corrected_filename (file where the corrected information has replaced the original information)
                   4437:   scantron_skipped_filename (contains the exact text of scanlines that where skipped)
                   4438: 
                   4439: Also there is a separate hash nohist_scantrondata that contains extra
                   4440: correction information that isn't representable in the bubble sheet
                   4441: file (see &scantron_getfile() for more information)
                   4442: 
                   4443: After all scanlines are either valid, marked as valid or skipped, then
                   4444: foreach line foreach problem in the picked sequence, an ssi request is
                   4445: made that simulates a user submitting their selected letter(s) against
                   4446: the homework problem.
1.423     albertel 4447: 
                   4448: =over 4
                   4449: 
                   4450: =cut
                   4451: 
                   4452: 
                   4453: =pod 
                   4454: 
                   4455: =item defaultFormData
                   4456: 
                   4457:   Returns html hidden inputs used to hold context/default values.
                   4458: 
                   4459:  Arguments:
                   4460:   $symb - $symb of the current resource 
                   4461: 
                   4462: =cut
1.422     foxr     4463: 
1.81      albertel 4464: sub defaultFormData {
1.324     albertel 4465:     my ($symb)=@_;
1.81      albertel 4466:     return '
1.418     albertel 4467:       <input type="hidden" name="symb"    value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 4468:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4469:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4470: }
                   4471: 
1.423     albertel 4472: =pod 
                   4473: 
                   4474: =item getSequenceDropDown
                   4475: 
                   4476:    Return html dropdown of possible sequences to grade
                   4477:  
                   4478:  Arguments:
                   4479:    $symb - $symb of the current resource 
                   4480: 
                   4481: =cut
1.422     foxr     4482: 
1.75      albertel 4483: sub getSequenceDropDown {
1.423     albertel 4484:     my ($symb)=@_;
1.75      albertel 4485:     my $result='<select name="selectpage">'."\n";
1.423     albertel 4486:     my ($titles,$symbx) = &getSymbMap();
1.137     albertel 4487:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4488:     my $ctr=0;
                   4489:     foreach (@$titles) {
                   4490: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4491: 	$result.='<option value="'.$$symbx{$_}.'" '.
1.401     albertel 4492: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="selected"' : '').
1.75      albertel 4493: 	    '>'.$showtitle.'</option>'."\n";
                   4494: 	$ctr++;
                   4495:     }
                   4496:     $result.= '</select>';
                   4497:     return $result;
                   4498: }
                   4499: 
1.423     albertel 4500: 
                   4501: =pod 
                   4502: 
                   4503: =item scantron_filenames
                   4504: 
                   4505:    Returns a list of the scantron files in the current course 
                   4506: 
                   4507: =cut
1.422     foxr     4508: 
1.202     albertel 4509: sub scantron_filenames {
1.257     albertel 4510:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4511:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4512:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4513: 				    &propath($cdom,$cname));
1.202     albertel 4514:     my @possiblenames;
1.201     albertel 4515:     foreach my $filename (sort(@files)) {
1.157     albertel 4516: 	($filename)=split(/&/,$filename);
                   4517: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4518: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4519: 	push(@possiblenames,$filename);
                   4520:     }
                   4521:     return @possiblenames;
                   4522: }
                   4523: 
1.423     albertel 4524: =pod 
                   4525: 
                   4526: =item scantron_uploads
                   4527: 
                   4528:    Returns  html drop-down list of scantron files in current course.
                   4529: 
                   4530:  Arguments:
                   4531:    $file2grade - filename to set as selected in the dropdown
                   4532: 
                   4533: =cut
1.422     foxr     4534: 
1.202     albertel 4535: sub scantron_uploads {
1.209     ng       4536:     my ($file2grade) = @_;
1.202     albertel 4537:     my $result=	'<select name="scantron_selectfile">';
                   4538:     $result.="<option></option>";
                   4539:     foreach my $filename (sort(&scantron_filenames())) {
1.401     albertel 4540: 	$result.="<option".($filename eq $file2grade ? ' selected="selected"':'').">$filename</option>\n";
1.81      albertel 4541:     }
                   4542:     $result.="</select>";
                   4543:     return $result;
                   4544: }
                   4545: 
1.423     albertel 4546: =pod 
                   4547: 
                   4548: =item scantron_scantab
                   4549: 
                   4550:   Returns html drop down of the scantron formats in the scantronformat.tab
                   4551:   file.
                   4552: 
                   4553: =cut
1.422     foxr     4554: 
1.82      albertel 4555: sub scantron_scantab {
                   4556:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4557:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4558:     $result.='<option></option>'."\n";
1.82      albertel 4559:     foreach my $line (<$fh>) {
                   4560: 	my ($name,$descrip)=split(/:/,$line);
                   4561: 	if ($name =~ /^\#/) { next; }
                   4562: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4563:     }
                   4564:     $result.='</select>'."\n";
                   4565: 
                   4566:     return $result;
                   4567: }
                   4568: 
1.423     albertel 4569: =pod 
                   4570: 
                   4571: =item scantron_CODElist
                   4572: 
                   4573:   Returns html drop down of the saved CODE lists from current course,
                   4574:   generated from earlier printings.
                   4575: 
                   4576: =cut
1.422     foxr     4577: 
1.186     albertel 4578: sub scantron_CODElist {
1.257     albertel 4579:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4580:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4581:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4582:     my $namechoice='<option></option>';
1.225     albertel 4583:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4584: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4585: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4586: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4587:     }
                   4588:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4589:     return $namechoice;
                   4590: }
                   4591: 
1.423     albertel 4592: =pod 
                   4593: 
                   4594: =item scantron_CODEunique
                   4595: 
                   4596:   Returns the html for "Each CODE to be used once" radio.
                   4597: 
                   4598: =cut
1.422     foxr     4599: 
1.186     albertel 4600: sub scantron_CODEunique {
1.381     albertel 4601:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4602:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4603:                         value="yes" checked="checked" />'.&mt('Yes').' </label>
1.381     albertel 4604:                 </span>
                   4605:                 <span style="white-space: nowrap;">
1.272     albertel 4606:                  <label><input type="radio" name="scantron_CODEunique"
1.423     albertel 4607:                         value="no" />'.&mt('No').' </label>
1.381     albertel 4608:                 </span>';
1.186     albertel 4609:     return $result;
                   4610: }
1.423     albertel 4611: 
                   4612: =pod 
                   4613: 
                   4614: =item scantron_selectphase
                   4615: 
                   4616:   Generates the initial screen to start the bubble sheet process.
                   4617:   Allows for - starting a grading run.
1.424     albertel 4618:              - downloading existing scan data (original, corrected
1.423     albertel 4619:                                                 or skipped info)
                   4620: 
                   4621:              - uploading new scan data
                   4622: 
                   4623:  Arguments:
                   4624:   $r          - The Apache request object
                   4625:   $file2grade - name of the file that contain the scanned data to score
                   4626: 
                   4627: =cut
1.186     albertel 4628: 
1.75      albertel 4629: sub scantron_selectphase {
1.209     ng       4630:     my ($r,$file2grade) = @_;
1.324     albertel 4631:     my ($symb)=&get_symb($r);
1.75      albertel 4632:     if (!$symb) {return '';}
1.423     albertel 4633:     my $sequence_selector=&getSequenceDropDown($symb);
1.324     albertel 4634:     my $default_form_data=&defaultFormData($symb);
                   4635:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4636:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4637:     my $format_selector=&scantron_scantab();
1.186     albertel 4638:     my $CODE_selector=&scantron_CODElist();
                   4639:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4640:     my $result;
1.422     foxr     4641: 
                   4642:     # Chunk of form to prompt for a file to grade and how:
                   4643: 
1.75      albertel 4644:     $result.= <<SCANTRONFORM;
1.162     albertel 4645:     <table width="100%" border="0">
1.75      albertel 4646:     <tr>
1.226     albertel 4647:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4648:       <td bgcolor="#777777">
1.203     albertel 4649:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4650:         $default_form_data
1.75      albertel 4651:         <table width="100%" border="0">
                   4652:           <tr bgcolor="#e6ffff">
1.174     albertel 4653:             <td colspan="2">
                   4654:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4655:             </td>
                   4656:           </tr>
                   4657:           <tr bgcolor="#ffffe6">
1.174     albertel 4658:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4659:           </tr>
                   4660:           <tr bgcolor="#ffffe6">
1.174     albertel 4661:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4662:           </tr>
1.82      albertel 4663:           <tr bgcolor="#ffffe6">
1.174     albertel 4664:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4665:           </tr>
1.157     albertel 4666:           <tr bgcolor="#ffffe6">
1.186     albertel 4667:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4668:           </tr>
                   4669:           <tr bgcolor="#ffffe6">
                   4670:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4671:           </tr>
                   4672:           <tr bgcolor="#ffffe6">
1.187     albertel 4673: 	    <td> Options: </td>
                   4674:             <td>
1.272     albertel 4675: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.424     albertel 4676:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all existing corrections</label> <br />
1.331     albertel 4677:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4678: 	    </td>
                   4679:           </tr>
                   4680:           <tr bgcolor="#ffffe6">
1.174     albertel 4681:             <td colspan="2">
1.265     www      4682:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4683:             </td>
                   4684:           </tr>
                   4685:         </table>
1.226     albertel 4686:        </td>
                   4687:      </form>
1.162     albertel 4688:     </tr>
                   4689: SCANTRONFORM
                   4690:    
                   4691:     $r->print($result);
                   4692: 
1.257     albertel 4693:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4694:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4695: 
1.422     foxr     4696: 	# Chunk of form to prompt for a scantron file upload.
                   4697: 
1.162     albertel 4698:         $r->print(<<SCANTRONFORM);
                   4699:     <tr>
                   4700:       <td bgcolor="#777777">
                   4701:         <table width="100%" border="0">
                   4702:           <tr bgcolor="#e6ffff">
                   4703:             <td>
1.174     albertel 4704:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4705:             </td>
                   4706:           </tr>
                   4707:           <tr bgcolor="#ffffe6">
                   4708:             <td>
                   4709: SCANTRONFORM
1.324     albertel 4710:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4711:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4712:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4713:     $r->print(<<UPLOAD);
                   4714:               <script type="text/javascript" language="javascript">
                   4715:     function checkUpload(formname) {
                   4716: 	if (formname.upfile.value == "") {
                   4717: 	    alert("Please use the browse button to select a file from your local directory.");
                   4718: 	    return false;
                   4719: 	}
                   4720: 	formname.submit();
                   4721:     }
                   4722:               </script>
                   4723: 
                   4724:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4725:                 $default_form_data
                   4726:                 <input name='courseid' type='hidden' value='$cnum' />
                   4727:                 <input name='domainid' type='hidden' value='$cdom' />
                   4728:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4729:                 File to upload:<input type="file" name="upfile" size="50" />
                   4730:                 <br />
                   4731:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4732:               </form>
                   4733: UPLOAD
1.162     albertel 4734: 
                   4735:         $r->print(<<SCANTRONFORM);
                   4736:             </td>
                   4737:           </tr>
1.75      albertel 4738:         </table>
                   4739:       </td>
                   4740:     </tr>
1.162     albertel 4741: SCANTRONFORM
                   4742:     }
1.422     foxr     4743: 
                   4744:     # Chunk of the form that prompts to view a scoring office file,
                   4745:     # corrected file, skipped records in a file.
                   4746: 
1.187     albertel 4747:     $r->print(<<SCANTRONFORM);
                   4748:     <tr>
1.226     albertel 4749:       <form action='/adm/grades' name='scantron_download'>
                   4750:         <td bgcolor="#777777">
1.379     albertel 4751: 	  $default_form_data
1.187     albertel 4752:           <input type="hidden" name="command" value="scantron_download" />
                   4753:           <table width="100%" border="0">
                   4754:             <tr bgcolor="#e6ffff">
                   4755:               <td colspan="2">
                   4756:                 &nbsp;<b>Download a scoring office file</b>
                   4757:               </td>
                   4758:             </tr>
                   4759:             <tr bgcolor="#ffffe6">
                   4760:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4761:             </tr>
                   4762:             <tr bgcolor="#ffffe6">
                   4763:               <td colspan="2">
1.293     www      4764:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4765:               </td>
                   4766:             </tr>
                   4767:           </table>
1.226     albertel 4768:         </td>
                   4769:       </form>
1.187     albertel 4770:     </tr>
                   4771: SCANTRONFORM
1.162     albertel 4772: 
                   4773:     $r->print(<<SCANTRONFORM);
1.75      albertel 4774:   </table>
1.81      albertel 4775: $grading_menu_button
1.75      albertel 4776: SCANTRONFORM
                   4777: 
1.162     albertel 4778:     return
1.75      albertel 4779: }
                   4780: 
1.423     albertel 4781: =pod
                   4782: 
                   4783: =item get_scantron_config
                   4784: 
                   4785:    Parse and return the scantron configuration line selected as a
                   4786:    hash of configuration file fields.
                   4787: 
                   4788:  Arguments:
                   4789:     which - the name of the configuration to parse from the file.
                   4790: 
                   4791: 
                   4792:  Returns:
                   4793:             If the named configuration is not in the file, an empty
                   4794:             hash is returned.
                   4795:     a hash with the fields
                   4796:       name         - internal name for the this configuration setup
                   4797:       description  - text to display to operator that describes this config
                   4798:       CODElocation - if 0 or the string 'none'
                   4799:                           - no CODE exists for this config
                   4800:                      if -1 || the string 'letter'
                   4801:                           - a CODE exists for this config and is
                   4802:                             a string of letters
                   4803:                      Unsupported value (but planned for future support)
                   4804:                           if a positive integer
                   4805:                                - The CODE exists as the first n items from
                   4806:                                  the question section of the form
                   4807:                           if the string 'number'
                   4808:                                - The CODE exists for this config and is
                   4809:                                  a string of numbers
                   4810:       CODEstart   - (only matter if a CODE exists) column in the line where
                   4811:                      the CODE starts
                   4812:       CODElength  - length of the CODE
                   4813:       IDstart     - column where the student ID number starts
                   4814:       IDlength    - length of the student ID info
                   4815:       Qstart      - column where the information from the bubbled
                   4816:                     'questions' start
                   4817:       Qlength     - number of columns comprising a single bubble line from
                   4818:                     the sheet. (usually either 1 or 10)
1.424     albertel 4819:       Qon         - either a single character representing the character used
1.423     albertel 4820:                     to signal a bubble was chosen in the positional setup, or
                   4821:                     the string 'letter' if the letter of the chosen bubble is
                   4822:                     in the final, or 'number' if a number representing the
                   4823:                     chosen bubble is in the file (1->A 0->J)
1.424     albertel 4824:       Qoff        - the character used to represent that a bubble was
                   4825:                     left blank
1.423     albertel 4826:       PaperID     - if the scanning process generates a unique number for each
                   4827:                     sheet scanned the column that this ID number starts in
                   4828:       PaperIDlength - number of columns that comprise the unique ID number
                   4829:                       for the sheet of paper
1.424     albertel 4830:       FirstName   - column that the first name starts in
1.423     albertel 4831:       FirstNameLength - number of columns that the first name spans
                   4832:  
                   4833:       LastName    - column that the last name starts in
                   4834:       LastNameLength - number of columns that the last name spans
                   4835: 
                   4836: =cut
1.422     foxr     4837: 
1.82      albertel 4838: sub get_scantron_config {
                   4839:     my ($which) = @_;
                   4840:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4841:     my %config;
1.157     albertel 4842:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4843:     foreach my $line (<$fh>) {
                   4844: 	my ($name,$descrip)=split(/:/,$line);
                   4845: 	if ($name ne $which ) { next; }
                   4846: 	chomp($line);
                   4847: 	my @config=split(/:/,$line);
                   4848: 	$config{'name'}=$config[0];
                   4849: 	$config{'description'}=$config[1];
                   4850: 	$config{'CODElocation'}=$config[2];
                   4851: 	$config{'CODEstart'}=$config[3];
                   4852: 	$config{'CODElength'}=$config[4];
                   4853: 	$config{'IDstart'}=$config[5];
                   4854: 	$config{'IDlength'}=$config[6];
                   4855: 	$config{'Qstart'}=$config[7];
                   4856: 	$config{'Qlength'}=$config[8];
                   4857: 	$config{'Qoff'}=$config[9];
                   4858: 	$config{'Qon'}=$config[10];
1.157     albertel 4859: 	$config{'PaperID'}=$config[11];
                   4860: 	$config{'PaperIDlength'}=$config[12];
                   4861: 	$config{'FirstName'}=$config[13];
                   4862: 	$config{'FirstNamelength'}=$config[14];
                   4863: 	$config{'LastName'}=$config[15];
                   4864: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4865: 	last;
                   4866:     }
                   4867:     return %config;
                   4868: }
                   4869: 
1.423     albertel 4870: =pod 
                   4871: 
                   4872: =item username_to_idmap
                   4873: 
                   4874:     creates a hash keyed by student id with values of the corresponding
                   4875:     student username:domain.
                   4876: 
                   4877:   Arguments:
                   4878: 
                   4879:     $classlist - reference to the class list hash. This is a hash
                   4880:                  keyed by student name:domain  whose elements are references
1.424     albertel 4881:                  to arrays containing various chunks of information
1.423     albertel 4882:                  about the student. (See loncoursedata for more info).
                   4883: 
                   4884:   Returns
                   4885:     %idmap - the constructed hash
                   4886: 
                   4887: =cut
                   4888: 
1.82      albertel 4889: sub username_to_idmap {
                   4890:     my ($classlist)= @_;
                   4891:     my %idmap;
                   4892:     foreach my $student (keys(%$classlist)) {
                   4893: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4894: 	    $student;
                   4895:     }
                   4896:     return %idmap;
                   4897: }
1.423     albertel 4898: 
                   4899: =pod
                   4900: 
1.424     albertel 4901: =item scantron_fixup_scanline
1.423     albertel 4902: 
                   4903:    Process a requested correction to a scanline.
                   4904: 
                   4905:   Arguments:
                   4906:     $scantron_config   - hash from &get_scantron_config()
                   4907:     $scan_data         - hash of correction information 
                   4908:                           (see &scantron_getfile())
                   4909:     $line              - existing scanline
                   4910:     $whichline         - line number of the passed in scanline
                   4911:     $field             - type of change to process 
                   4912:                          (either 
                   4913:                           'ID'     -> correct the student ID number
                   4914:                           'CODE'   -> correct the CODE
                   4915:                           'answer' -> fixup the submitted answers)
                   4916:     
                   4917:    $args               - hash of additional info,
                   4918:                           - 'ID' 
                   4919:                                'newid' -> studentID to use in replacement
1.424     albertel 4920:                                           of existing one
1.423     albertel 4921:                           - 'CODE' 
                   4922:                                'CODE_ignore_dup' - set to true if duplicates
                   4923:                                                    should be ignored.
                   4924: 	                       'CODE' - is new code or 'use_unfound'
1.424     albertel 4925:                                         if the existing unfound code should
1.423     albertel 4926:                                         be used as is
                   4927:                           - 'answer'
                   4928:                                'response' - new answer or 'none' if blank
                   4929:                                'question' - the bubble line to change
                   4930: 
                   4931:   Returns:
                   4932:     $line - the modified scanline
                   4933: 
                   4934:   Side effects: 
                   4935:     $scan_data - may be updated
                   4936: 
                   4937: =cut
                   4938: 
1.82      albertel 4939: 
1.157     albertel 4940: sub scantron_fixup_scanline {
                   4941:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
1.423     albertel 4942: 
1.157     albertel 4943:     if ($field eq 'ID') {
                   4944: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4945: 	    return ($line,1,'New value too large');
1.157     albertel 4946: 	}
                   4947: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4948: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4949: 				     $args->{'newid'});
                   4950: 	}
                   4951: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4952: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4953: 	if ($args->{'newid'}=~/^\s*$/) {
                   4954: 	    &scan_data($scan_data,"$whichline.user",
                   4955: 		       $args->{'username'}.':'.$args->{'domain'});
                   4956: 	}
1.186     albertel 4957:     } elsif ($field eq 'CODE') {
1.192     albertel 4958: 	if ($args->{'CODE_ignore_dup'}) {
                   4959: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4960: 	}
                   4961: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4962: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4963: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4964: 		return ($line,1,'New CODE value too large');
                   4965: 	    }
                   4966: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4967: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4968: 	    }
                   4969: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4970: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4971: 	}
1.157     albertel 4972:     } elsif ($field eq 'answer') {
                   4973: 	my $length=$scantron_config->{'Qlength'};
                   4974: 	my $off=$scantron_config->{'Qoff'};
                   4975: 	my $on=$scantron_config->{'Qon'};
                   4976: 	my $answer=${off}x$length;
                   4977: 	if ($args->{'response'} eq 'none') {
                   4978: 	    &scan_data($scan_data,
                   4979: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4980: 	} else {
1.274     albertel 4981: 	    if ($on eq 'letter') {
                   4982: 		my @alphabet=('A'..'Z');
                   4983: 		$answer=$alphabet[$args->{'response'}];
                   4984: 	    } elsif ($on eq 'number') {
                   4985: 		$answer=$args->{'response'}+1;
1.389     albertel 4986: 		if ($answer == 10) { $answer = '0'; }
1.274     albertel 4987: 	    } else {
                   4988: 		substr($answer,$args->{'response'},1)=$on;
                   4989: 	    }
1.157     albertel 4990: 	    &scan_data($scan_data,
                   4991: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4992: 	}
                   4993: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4994: 	substr($line,$where-1,$length)=$answer;
                   4995:     }
                   4996:     return $line;
                   4997: }
1.423     albertel 4998: 
                   4999: =pod
                   5000: 
                   5001: =item scan_data
                   5002: 
                   5003:     Edit or look up  an item in the scan_data hash.
                   5004: 
                   5005:   Arguments:
                   5006:     $scan_data  - The hash (see scantron_getfile)
                   5007:     $key        - shorthand of the key to edit (actual key is
1.424     albertel 5008:                   scantronfilename_key).
1.423     albertel 5009:     $data        - New value of the hash entry.
                   5010:     $delete      - If true, the entry is removed from the hash.
                   5011: 
                   5012:   Returns:
                   5013:     The new value of the hash table field (undefined if deleted).
                   5014: 
                   5015: =cut
                   5016: 
                   5017: 
1.157     albertel 5018: sub scan_data {
                   5019:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 5020:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 5021:     if (defined($value)) {
                   5022: 	$scan_data->{$filename.'_'.$key} = $value;
                   5023:     }
                   5024:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   5025:     return $scan_data->{$filename.'_'.$key};
                   5026: }
1.423     albertel 5027: 
                   5028: =pod 
                   5029: 
                   5030: =item scantron_parse_scanline
                   5031: 
                   5032:   Decodes a scanline from the selected scantron file
                   5033: 
                   5034:  Arguments:
                   5035:     line             - The text of the scantron file line to process
                   5036:     whichline        - Line number
                   5037:     scantron_config  - Hash describing the format of the scantron lines.
                   5038:     scan_data        - Hash of extra information about the scanline
                   5039:                        (see scantron_getfile for more information)
                   5040:     just_header      - True if should not process question answers but only
                   5041:                        the stuff to the left of the answers.
                   5042:  Returns:
                   5043:    Hash containing the result of parsing the scanline
                   5044: 
                   5045:    Keys are all proceeded by the string 'scantron.'
                   5046: 
                   5047:        CODE    - the CODE in use for this scanline
                   5048:        useCODE - 1 if the CODE is invalid but it usage has been forced
                   5049:                  by the operator
                   5050:        CODE_ignore_dup - 1 if the CODE is a duplicated use when unique
                   5051:                             CODEs were selected, but the usage has been
                   5052:                             forced by the operator
                   5053:        ID  - student ID
                   5054:        PaperID - if used, the ID number printed on the sheet when the 
                   5055:                  paper was scanned
                   5056:        FirstName - first name from the sheet
                   5057:        LastName  - last name from the sheet
                   5058: 
                   5059:      if just_header was not true these key may also exist
                   5060: 
                   5061:        missingerror - a list of bubbled line numbers that had a blank bubble
                   5062:                       that is considered an error (if the operator had already
                   5063:                       okayed a blank bubble line as really being blank then
                   5064:                       that bubble line number won't appear here.
                   5065:        doubleerror  - a list of bubbled line numbers that had more than one
                   5066:                       bubble filled in and has not been corrected by the
                   5067:                       operator
                   5068:        maxquest     - the number of the last bubble line that was parsed
                   5069: 
                   5070:        (<number> starts at 1)
                   5071:        <number>.answer - zero or more letters representing the selected
                   5072:                          letters from the scanline for the bubble line 
                   5073:                          <number>.
                   5074:                          if blank there was either no bubble or there where
                   5075:                          multiple bubbles, (consult the keys missingerror and
                   5076:                          doubleerror if this is an error condition)
                   5077: 
                   5078: =cut
                   5079: 
1.82      albertel 5080: sub scantron_parse_scanline {
1.423     albertel 5081:     my ($line,$whichline,$scantron_config,$scan_data,$just_header)=@_;
1.82      albertel 5082:     my %record;
1.422     foxr     5083:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);  # Answers
                   5084:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);     # earlier stuff
1.278     albertel 5085:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   5086: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   5087: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   5088: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   5089: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 5090: 	    $record{'scantron.CODE'}=substr($data,
                   5091: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 5092: 					    $$scantron_config{'CODElength'});
1.191     albertel 5093: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   5094: 		$record{'scantron.useCODE'}=1;
                   5095: 	    }
1.192     albertel 5096: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   5097: 		$record{'scantron.CODE_ignore_dup'}=1;
                   5098: 	    }
1.82      albertel 5099: 	} else {
                   5100: 	    #FIXME interpret first N questions
                   5101: 	}
                   5102:     }
1.83      albertel 5103:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   5104: 				  $$scantron_config{'IDlength'});
1.157     albertel 5105:     $record{'scantron.PaperID'}=
                   5106: 	substr($data,$$scantron_config{'PaperID'}-1,
                   5107: 	       $$scantron_config{'PaperIDlength'});
                   5108:     $record{'scantron.FirstName'}=
                   5109: 	substr($data,$$scantron_config{'FirstName'}-1,
                   5110: 	       $$scantron_config{'FirstNamelength'});
                   5111:     $record{'scantron.LastName'}=
                   5112: 	substr($data,$$scantron_config{'LastName'}-1,
                   5113: 	       $$scantron_config{'LastNamelength'});
1.423     albertel 5114:     if ($just_header) { return \%record; }
1.194     albertel 5115: 
1.82      albertel 5116:     my @alphabet=('A'..'Z');
                   5117:     my $questnum=0;
                   5118:     while ($questions) {
                   5119: 	$questnum++;
                   5120: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   5121: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 5122: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 5123: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 5124: 	    if ($currentquest eq '?'
                   5125: 		|| $currentquest eq '*') {
1.274     albertel 5126: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5127: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5128: 	    } elsif (!defined($currentquest)
1.274     albertel 5129: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   5130: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 5131: 		$record{"scantron.$questnum.answer"}='';
                   5132: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5133: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5134: 		}
                   5135: 	    } else {
                   5136: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   5137: 	    }
                   5138: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 5139: 	    if ($currentquest eq '?'
                   5140: 		|| $currentquest eq '*') {
1.274     albertel 5141: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5142: 		$record{"scantron.$questnum.answer"}='';
1.389     albertel 5143: 	    } elsif (!defined($currentquest)
                   5144: 		     || $currentquest eq $$scantron_config{'Qoff'} 
                   5145: 		     || $currentquest !~ /^\d$/) {
1.239     albertel 5146: 		$record{"scantron.$questnum.answer"}='';
                   5147: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5148: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5149: 		}
                   5150: 	    } else {
1.371     albertel 5151: 		# wrap zero back to J
                   5152: 		if ($currentquest eq '0') {
                   5153: 		    $record{"scantron.$questnum.answer"}=
                   5154: 			$alphabet[9];
                   5155: 		} else {
                   5156: 		    $record{"scantron.$questnum.answer"}=
                   5157: 			$alphabet[$currentquest-1];
                   5158: 		}
1.239     albertel 5159: 	    }
1.82      albertel 5160: 	} else {
1.239     albertel 5161: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   5162: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   5163: 		$record{"scantron.$questnum.answer"}='';
                   5164: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   5165: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   5166: 		}
                   5167: 	    } else {
                   5168: 		$record{"scantron.$questnum.answer"}=
                   5169: 		    $alphabet[length($array[0])];
                   5170: 	    }
                   5171: 	    if (scalar(@array) gt 2) {
                   5172: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   5173: 		my @ans=@array;
                   5174: 		my $i=length($ans[0]);shift(@ans);
                   5175: 		while ($#ans) {
                   5176: 		    $i+=length($ans[0])+1;
                   5177: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   5178: 		    shift(@ans);
                   5179: 		}
                   5180: 	    }
1.82      albertel 5181: 	}
                   5182:     }
1.83      albertel 5183:     $record{'scantron.maxquest'}=$questnum;
                   5184:     return \%record;
1.82      albertel 5185: }
                   5186: 
1.423     albertel 5187: =pod
                   5188: 
                   5189: =item scantron_add_delay
                   5190: 
                   5191:    Adds an error message that occurred during the grading phase to a
                   5192:    queue of messages to be shown after grading pass is complete
                   5193: 
                   5194:  Arguments:
1.424     albertel 5195:    $delayqueue  - arrary ref of hash ref of error messages
1.423     albertel 5196:    $scanline    - the scanline that caused the error
                   5197:    $errormesage - the error message
                   5198:    $errorcode   - a numeric code for the error
                   5199: 
                   5200:  Side Effects:
1.424     albertel 5201:    updates the $delayqueue to have a new hash ref of the error
1.423     albertel 5202: 
                   5203: =cut
                   5204: 
1.82      albertel 5205: sub scantron_add_delay {
1.140     albertel 5206:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   5207:     push(@$delayqueue,
                   5208: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   5209: 	  'ecode' => $errorcode }
                   5210: 	 );
1.82      albertel 5211: }
                   5212: 
1.423     albertel 5213: =pod
                   5214: 
                   5215: =item scantron_find_student
                   5216: 
1.424     albertel 5217:    Finds the username for the current scanline
                   5218: 
                   5219:   Arguments:
                   5220:    $scantron_record - hash result from scantron_parse_scanline
                   5221:    $scan_data       - hash of correction information 
                   5222:                       (see &scantron_getfile() form more information)
                   5223:    $idmap           - hash from &username_to_idmap()
                   5224:    $line            - number of current scanline
                   5225:  
                   5226:   Returns:
                   5227:    Either 'username:domain' or undef if unknown
                   5228: 
1.423     albertel 5229: =cut
                   5230: 
1.82      albertel 5231: sub scantron_find_student {
1.157     albertel 5232:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 5233:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 5234:     if ($scanID =~ /^\s*$/) {
                   5235:  	return &scan_data($scan_data,"$line.user");
                   5236:     }
1.83      albertel 5237:     foreach my $id (keys(%$idmap)) {
1.157     albertel 5238:  	if (lc($id) eq lc($scanID)) {
                   5239:  	    return $$idmap{$id};
                   5240:  	}
1.83      albertel 5241:     }
                   5242:     return undef;
                   5243: }
                   5244: 
1.423     albertel 5245: =pod
                   5246: 
                   5247: =item scantron_filter
                   5248: 
1.424     albertel 5249:    Filter sub for lonnavmaps, filters out hidden resources if ignore
                   5250:    hidden resources was selected
                   5251: 
1.423     albertel 5252: =cut
                   5253: 
1.83      albertel 5254: sub scantron_filter {
                   5255:     my ($curres)=@_;
1.331     albertel 5256: 
                   5257:     if (ref($curres) && $curres->is_problem()) {
                   5258: 	# if the user has asked to not have either hidden
                   5259: 	# or 'randomout' controlled resources to be graded
                   5260: 	# don't include them
                   5261: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5262: 	    && $curres->randomout) {
                   5263: 	    return 0;
                   5264: 	}
1.83      albertel 5265: 	return 1;
                   5266:     }
                   5267:     return 0;
1.82      albertel 5268: }
                   5269: 
1.423     albertel 5270: =pod
                   5271: 
                   5272: =item scantron_process_corrections
                   5273: 
1.424     albertel 5274:    Gets correction information out of submitted form data and corrects
                   5275:    the scanline
                   5276: 
1.423     albertel 5277: =cut
                   5278: 
1.157     albertel 5279: sub scantron_process_corrections {
                   5280:     my ($r) = @_;
1.257     albertel 5281:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5282:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5283:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 5284:     my $which=$env{'form.scantron_line'};
1.200     albertel 5285:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 5286:     my ($skip,$err,$errmsg);
1.257     albertel 5287:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 5288: 	$skip=1;
1.257     albertel 5289:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   5290: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   5291: 	    $env{'form.scantron_domain'};
1.157     albertel 5292: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   5293: 	($line,$err,$errmsg)=
                   5294: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   5295: 				     'ID',{'newid'=>$newid,
1.257     albertel 5296: 				    'username'=>$env{'form.scantron_username'},
                   5297: 				    'domain'=>$env{'form.scantron_domain'}});
                   5298:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   5299: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 5300: 	my $newCODE;
1.192     albertel 5301: 	my %args;
1.190     albertel 5302: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 5303: 	    $newCODE='use_unfound';
1.190     albertel 5304: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 5305: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 5306: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 5307: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 5308: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 5309: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 5310: 	}
1.257     albertel 5311: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 5312: 	    $args{'CODE_ignore_dup'}=1;
                   5313: 	}
                   5314: 	$args{'CODE'}=$newCODE;
1.186     albertel 5315: 	($line,$err,$errmsg)=
                   5316: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 5317: 				     'CODE',\%args);
1.257     albertel 5318:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   5319: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 5320: 	    ($line,$err,$errmsg)=
                   5321: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   5322: 					 $which,'answer',
                   5323: 					 { 'question'=>$question,
1.257     albertel 5324: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 5325: 	    if ($err) { last; }
                   5326: 	}
                   5327:     }
                   5328:     if ($err) {
1.398     albertel 5329: 	$r->print("<span class=\"LC_warning\">Unable to accept last correction, an error occurred :$errmsg:</span>");
1.157     albertel 5330:     } else {
1.200     albertel 5331: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 5332: 	&scantron_putfile($scanlines,$scan_data);
                   5333:     }
                   5334: }
                   5335: 
1.423     albertel 5336: =pod
                   5337: 
                   5338: =item reset_skipping_status
                   5339: 
1.424     albertel 5340:    Forgets the current set of remember skipped scanlines (and thus
                   5341:    reverts back to considering all lines in the
                   5342:    scantron_skipped_<filename> file)
                   5343: 
1.423     albertel 5344: =cut
                   5345: 
1.200     albertel 5346: sub reset_skipping_status {
                   5347:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5348:     &scan_data($scan_data,'remember_skipping',undef,1);
                   5349:     &scantron_putfile(undef,$scan_data);
                   5350: }
                   5351: 
1.423     albertel 5352: =pod
                   5353: 
                   5354: =item start_skipping
                   5355: 
1.424     albertel 5356:    Marks a scanline to be skipped. 
                   5357: 
1.423     albertel 5358: =cut
                   5359: 
1.376     albertel 5360: sub start_skipping {
1.200     albertel 5361:     my ($scan_data,$i)=@_;
                   5362:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5363:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   5364: 	$remembered{$i}=2;
                   5365:     } else {
                   5366: 	$remembered{$i}=1;
                   5367:     }
1.200     albertel 5368:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   5369: }
                   5370: 
1.423     albertel 5371: =pod
                   5372: 
                   5373: =item should_be_skipped
                   5374: 
1.424     albertel 5375:    Checks whether a scanline should be skipped.
                   5376: 
1.423     albertel 5377: =cut
                   5378: 
1.200     albertel 5379: sub should_be_skipped {
1.376     albertel 5380:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 5381:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 5382: 	# not redoing old skips
1.376     albertel 5383: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 5384: 	return 0;
                   5385:     }
                   5386:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 5387: 
                   5388:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   5389: 	return 0;
                   5390:     }
1.200     albertel 5391:     return 1;
                   5392: }
                   5393: 
1.423     albertel 5394: =pod
                   5395: 
                   5396: =item remember_current_skipped
                   5397: 
1.424     albertel 5398:    Discovers what scanlines are in the scantron_skipped_<filename>
                   5399:    file and remembers them into scan_data for later use.
                   5400: 
1.423     albertel 5401: =cut
                   5402: 
1.200     albertel 5403: sub remember_current_skipped {
                   5404:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5405:     my %to_remember;
                   5406:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5407: 	if ($scanlines->{'skipped'}[$i]) {
                   5408: 	    $to_remember{$i}=1;
                   5409: 	}
                   5410:     }
1.376     albertel 5411: 
1.200     albertel 5412:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   5413:     &scantron_putfile(undef,$scan_data);
                   5414: }
                   5415: 
1.423     albertel 5416: =pod
                   5417: 
                   5418: =item check_for_error
                   5419: 
1.424     albertel 5420:     Checks if there was an error when attempting to remove a specific
                   5421:     scantron_.. bubble sheet data file. Prints out an error if
                   5422:     something went wrong.
                   5423: 
1.423     albertel 5424: =cut
                   5425: 
1.200     albertel 5426: sub check_for_error {
                   5427:     my ($r,$result)=@_;
                   5428:     if ($result ne 'ok' && $result ne 'not_found' ) {
1.401     albertel 5429: 	$r->print("An error occurred ($result) when trying to Remove the existing corrections.");
1.200     albertel 5430:     }
                   5431: }
1.157     albertel 5432: 
1.423     albertel 5433: =pod
                   5434: 
                   5435: =item scantron_warning_screen
                   5436: 
1.424     albertel 5437:    Interstitial screen to make sure the operator has selected the
                   5438:    correct options before we start the validation phase.
                   5439: 
1.423     albertel 5440: =cut
                   5441: 
1.203     albertel 5442: sub scantron_warning_screen {
                   5443:     my ($button_text)=@_;
1.257     albertel 5444:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 5445:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 5446:     my $CODElist;
1.284     albertel 5447:     if ($scantron_config{'CODElocation'} &&
                   5448: 	$scantron_config{'CODEstart'} &&
                   5449: 	$scantron_config{'CODElength'}) {
                   5450: 	$CODElist=$env{'form.scantron_CODElist'};
1.398     albertel 5451: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<span class="LC_warning">None</span>'; }
1.284     albertel 5452: 	$CODElist=
                   5453: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 5454: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 5455:     }
1.203     albertel 5456:     return (<<STUFF);
                   5457: <p>
1.398     albertel 5458: <span class="LC_warning">Please double check the information
                   5459:                  below before clicking on '$button_text'</span>
1.203     albertel 5460: </p>
                   5461: <table>
1.284     albertel 5462: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 5463: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 5464: $CODElist
1.203     albertel 5465: </table>
                   5466: <br />
                   5467: <p> If this information is correct, please click on '$button_text'.</p>
                   5468: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   5469: 
                   5470: <br />
                   5471: STUFF
                   5472: }
                   5473: 
1.423     albertel 5474: =pod
                   5475: 
                   5476: =item scantron_do_warning
                   5477: 
1.424     albertel 5478:    Check if the operator has picked something for all required
                   5479:    fields. Error out if something is missing.
                   5480: 
1.423     albertel 5481: =cut
                   5482: 
1.203     albertel 5483: sub scantron_do_warning {
                   5484:     my ($r)=@_;
1.324     albertel 5485:     my ($symb)=&get_symb($r);
1.203     albertel 5486:     if (!$symb) {return '';}
1.324     albertel 5487:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 5488:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 5489:     if ( $env{'form.selectpage'} eq '' ||
                   5490: 	 $env{'form.scantron_selectfile'} eq '' ||
                   5491: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 5492: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 5493: 	if ( $env{'form.selectpage'} eq '') {
1.398     albertel 5494: 	    $r->print('<p><span class="LC_error">You have not selected a Sequence to grade</span></p>');
1.237     albertel 5495: 	} 
1.257     albertel 5496: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.398     albertel 5497: 	    $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 5498: 	} 
1.257     albertel 5499: 	if ( $env{'form.scantron_format'} eq '') {
1.398     albertel 5500: 	    $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 5501: 	} 
                   5502:     } else {
1.265     www      5503: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 5504: 	$r->print(<<STUFF);
1.203     albertel 5505: $warning
1.265     www      5506: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 5507: <input type="hidden" name="command" value="scantron_validate" />
                   5508: STUFF
1.237     albertel 5509:     }
1.352     albertel 5510:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 5511:     return '';
                   5512: }
                   5513: 
1.423     albertel 5514: =pod
                   5515: 
                   5516: =item scantron_form_start
                   5517: 
1.424     albertel 5518:     html hidden input for remembering all selected grading options
                   5519: 
1.423     albertel 5520: =cut
                   5521: 
1.203     albertel 5522: sub scantron_form_start {
                   5523:     my ($max_bubble)=@_;
                   5524:     my $result= <<SCANTRONFORM;
                   5525: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 5526:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   5527:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   5528:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 5529:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 5530:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   5531:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   5532:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   5533:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 5534:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 5535: SCANTRONFORM
                   5536:     return $result;
                   5537: }
                   5538: 
1.423     albertel 5539: =pod
                   5540: 
                   5541: =item scantron_validate_file
                   5542: 
1.424     albertel 5543:     Dispatch routine for doing validation of a bubble sheet data file.
                   5544: 
                   5545:     Also processes any necessary information resets that need to
                   5546:     occur before validation begins (ignore previous corrections,
                   5547:     restarting the skipped records processing)
                   5548: 
1.423     albertel 5549: =cut
                   5550: 
1.157     albertel 5551: sub scantron_validate_file {
                   5552:     my ($r) = @_;
1.324     albertel 5553:     my ($symb)=&get_symb($r);
1.157     albertel 5554:     if (!$symb) {return '';}
1.324     albertel 5555:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 5556:     
                   5557:     # do the detection of only doing skipped records first befroe we delete
1.424     albertel 5558:     # them when doing the corrections reset
1.257     albertel 5559:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 5560: 	&reset_skipping_status();
                   5561:     }
1.257     albertel 5562:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 5563: 	&remember_current_skipped();
1.257     albertel 5564: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 5565:     }
                   5566: 
1.257     albertel 5567:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 5568: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   5569: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   5570: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 5571: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 5572:     }
1.200     albertel 5573: 
1.257     albertel 5574:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 5575: 	&scantron_process_corrections($r);
                   5576:     }
1.424     albertel 5577:     $r->print("<p>Gathering necessary info.</p>");$r->rflush();
1.157     albertel 5578:     #get the student pick code ready
                   5579:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 5580:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 5581:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 5582:     $r->print($result);
                   5583:     
1.334     albertel 5584:     my @validate_phases=( 'sequence',
                   5585: 			  'ID',
1.157     albertel 5586: 			  'CODE',
                   5587: 			  'doublebubble',
                   5588: 			  'missingbubbles');
1.257     albertel 5589:     if (!$env{'form.validatepass'}) {
                   5590: 	$env{'form.validatepass'} = 0;
1.157     albertel 5591:     }
1.257     albertel 5592:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 5593: 
                   5594:     my $stop=0;
                   5595:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5596: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5597: 	$r->rflush();
                   5598: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5599: 	{
                   5600: 	    no strict 'refs';
                   5601: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5602: 	}
                   5603:     }
                   5604:     if (!$stop) {
1.203     albertel 5605: 	my $warning=&scantron_warning_screen('Start Grading');
                   5606: 	$r->print(<<STUFF);
                   5607: Validation process complete.<br />
                   5608: $warning
                   5609: <input type="submit" name="submit" value="Start Grading" />
                   5610: <input type="hidden" name="command" value="scantron_process" />
                   5611: STUFF
                   5612: 
1.157     albertel 5613:     } else {
                   5614: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5615: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5616:     }
                   5617:     if ($stop) {
1.334     albertel 5618: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5619: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5620: 	    $r->print(' this error <br />');
                   5621: 
                   5622: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5623: 	} else {
                   5624: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5625: 	    $r->print(' using corrected info <br />');
                   5626: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5627: 	    $r->print(" this scanline saving it for later.");
                   5628: 	}
1.157     albertel 5629:     }
1.352     albertel 5630:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5631:     return '';
                   5632: }
                   5633: 
1.423     albertel 5634: 
                   5635: =pod
                   5636: 
                   5637: =item scantron_remove_file
                   5638: 
1.424     albertel 5639:    Removes the requested bubble sheet data file, makes sure that
                   5640:    scantron_original_<filename> is never removed
                   5641: 
                   5642: 
1.423     albertel 5643: =cut
                   5644: 
1.200     albertel 5645: sub scantron_remove_file {
1.192     albertel 5646:     my ($which)=@_;
1.257     albertel 5647:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5648:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5649:     my $file='scantron_';
1.200     albertel 5650:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5651: 	$file.=$which.'_';
1.192     albertel 5652:     } else {
                   5653: 	return 'refused';
                   5654:     }
1.257     albertel 5655:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5656:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5657: }
                   5658: 
1.423     albertel 5659: 
                   5660: =pod
                   5661: 
                   5662: =item scantron_remove_scan_data
                   5663: 
1.424     albertel 5664:    Removes all scan_data correction for the requested bubble sheet
                   5665:    data file.  (In the case that both the are doing skipped records we need
                   5666:    to remember the old skipped lines for the time being so that element
                   5667:    persists for a while.)
                   5668: 
1.423     albertel 5669: =cut
                   5670: 
1.200     albertel 5671: sub scantron_remove_scan_data {
1.257     albertel 5672:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5673:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5674:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5675:     my @todelete;
1.257     albertel 5676:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5677:     foreach my $key (@keys) {
                   5678: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5679: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5680: 		$key=~/remember_skipping/) {
                   5681: 		next;
                   5682: 	    }
1.192     albertel 5683: 	    push(@todelete,$key);
                   5684: 	}
                   5685:     }
1.200     albertel 5686:     my $result;
1.192     albertel 5687:     if (@todelete) {
1.200     albertel 5688: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5689:     }
                   5690:     return $result;
                   5691: }
                   5692: 
1.423     albertel 5693: 
                   5694: =pod
                   5695: 
                   5696: =item scantron_getfile
                   5697: 
1.424     albertel 5698:     Fetches the requested bubble sheet data file (all 3 versions), and
                   5699:     the scan_data hash
                   5700:   
                   5701:   Arguments:
                   5702:     None
                   5703: 
                   5704:   Returns:
                   5705:     2 hash references
                   5706: 
                   5707:      - first one has 
                   5708:          orig      -
                   5709:          corrected -
                   5710:          skipped   -  each of which points to an array ref of the specified
                   5711:                       file broken up into individual lines
                   5712:          count     - number of scanlines
                   5713:  
                   5714:      - second is the scan_data hash possible keys are
1.425     albertel 5715:        ($number refers to scanline numbered $number and thus the key affects
                   5716:         only that scanline
                   5717:         $bubline refers to the specific bubble line element and the aspects
                   5718:         refers to that specific bubble line element)
                   5719: 
                   5720:        $number.user - username:domain to use
                   5721:        $number.CODE_ignore_dup 
                   5722:                     - ignore the duplicate CODE error 
                   5723:        $number.useCODE
                   5724:                     - use the CODE in the scanline as is
                   5725:        $number.no_bubble.$bubline
                   5726:                     - it is valid that there is no bubbled in bubble
                   5727:                       at $number $bubline
                   5728:        remember_skipping
                   5729:                     - a frozen hash containing keys of $number and values
                   5730:                       of either 
                   5731:                         1 - we are on a 'do skipped records pass' and plan
                   5732:                             on processing this line
                   5733:                         2 - we are on a 'do skipped records pass' and this
                   5734:                             scanline has been marked to skip yet again
1.424     albertel 5735: 
1.423     albertel 5736: =cut
                   5737: 
1.157     albertel 5738: sub scantron_getfile {
1.200     albertel 5739:     #FIXME really would prefer a scantron directory
1.257     albertel 5740:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5741:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5742:     my $lines;
                   5743:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5744: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5745:     my %scanlines;
                   5746:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5747:     my $temp=$scanlines{'orig'};
                   5748:     $scanlines{'count'}=$#$temp;
                   5749: 
                   5750:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5751: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5752:     if ($lines eq '-1') {
                   5753: 	$scanlines{'corrected'}=[];
                   5754:     } else {
                   5755: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5756:     }
                   5757:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5758: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5759:     if ($lines eq '-1') {
                   5760: 	$scanlines{'skipped'}=[];
                   5761:     } else {
                   5762: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5763:     }
1.175     albertel 5764:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5765:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5766:     my %scan_data = @tmp;
                   5767:     return (\%scanlines,\%scan_data);
                   5768: }
                   5769: 
1.423     albertel 5770: =pod
                   5771: 
                   5772: =item lonnet_putfile
                   5773: 
1.424     albertel 5774:    Wrapper routine to call &Apache::lonnet::finishuserfileupload
                   5775: 
                   5776:  Arguments:
                   5777:    $contents - data to store
                   5778:    $filename - filename to store $contents into
                   5779: 
                   5780:  Returns:
                   5781:    result value from &Apache::lonnet::finishuserfileupload
                   5782: 
1.423     albertel 5783: =cut
                   5784: 
1.157     albertel 5785: sub lonnet_putfile {
                   5786:     my ($contents,$filename)=@_;
1.257     albertel 5787:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5788:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5789:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5790:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5791: 
                   5792: }
                   5793: 
1.423     albertel 5794: =pod
                   5795: 
                   5796: =item scantron_putfile
                   5797: 
1.424     albertel 5798:     Stores the current version of the bubble sheet data files, and the
                   5799:     scan_data hash. (Does not modify the original version only the
                   5800:     corrected and skipped versions.
                   5801: 
                   5802:  Arguments:
                   5803:     $scanlines - hash ref that looks like the first return value from
                   5804:                  &scantron_getfile()
                   5805:     $scan_data - hash ref that looks like the second return value from
                   5806:                  &scantron_getfile()
                   5807: 
1.423     albertel 5808: =cut
                   5809: 
1.157     albertel 5810: sub scantron_putfile {
                   5811:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5812:     #FIXME really would prefer a scantron directory
1.257     albertel 5813:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5814:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5815:     if ($scanlines) {
                   5816: 	my $prefix='scantron_';
1.157     albertel 5817: # no need to update orig, shouldn't change
                   5818: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5819: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5820: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5821: 			$prefix.'corrected_'.
1.257     albertel 5822: 			$env{'form.scantron_selectfile'});
1.200     albertel 5823: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5824: 			$prefix.'skipped_'.
1.257     albertel 5825: 			$env{'form.scantron_selectfile'});
1.200     albertel 5826:     }
1.175     albertel 5827:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5828: }
                   5829: 
1.423     albertel 5830: =pod
                   5831: 
                   5832: =item scantron_get_line
                   5833: 
1.424     albertel 5834:    Returns the correct version of the scanline
                   5835: 
                   5836:  Arguments:
                   5837:     $scanlines - hash ref that looks like the first return value from
                   5838:                  &scantron_getfile()
                   5839:     $scan_data - hash ref that looks like the second return value from
                   5840:                  &scantron_getfile()
                   5841:     $i         - number of the requested line (starts at 0)
                   5842: 
                   5843:  Returns:
                   5844:    A scanline, (either the original or the corrected one if it
                   5845:    exists), or undef if the requested scanline should be
                   5846:    skipped. (Either because it's an skipped scanline, or it's an
                   5847:    unskipped scanline and we are not doing a 'do skipped scanlines'
                   5848:    pass.
                   5849: 
1.423     albertel 5850: =cut
                   5851: 
1.157     albertel 5852: sub scantron_get_line {
1.200     albertel 5853:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5854:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5855:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5856:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5857:     return $scanlines->{'orig'}[$i]; 
                   5858: }
                   5859: 
1.423     albertel 5860: =pod
                   5861: 
                   5862: =item scantron_todo_count
                   5863: 
1.424     albertel 5864:     Counts the number of scanlines that need processing.
                   5865: 
                   5866:  Arguments:
                   5867:     $scanlines - hash ref that looks like the first return value from
                   5868:                  &scantron_getfile()
                   5869:     $scan_data - hash ref that looks like the second return value from
                   5870:                  &scantron_getfile()
                   5871: 
                   5872:  Returns:
                   5873:     $count - number of scanlines to process
                   5874: 
1.423     albertel 5875: =cut
                   5876: 
1.200     albertel 5877: sub get_todo_count {
                   5878:     my ($scanlines,$scan_data)=@_;
                   5879:     my $count=0;
                   5880:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5881: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5882: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5883: 	$count++;
                   5884:     }
                   5885:     return $count;
                   5886: }
                   5887: 
1.423     albertel 5888: =pod
                   5889: 
                   5890: =item scantron_put_line
                   5891: 
1.424     albertel 5892:     Updates the 'corrected' or 'skipped' versions of the bubble sheet
                   5893:     data file.
                   5894: 
                   5895:  Arguments:
                   5896:     $scanlines - hash ref that looks like the first return value from
                   5897:                  &scantron_getfile()
                   5898:     $scan_data - hash ref that looks like the second return value from
                   5899:                  &scantron_getfile()
                   5900:     $i         - line number to update
                   5901:     $newline   - contents of the updated scanline
                   5902:     $skip      - if true make the line for skipping and update the
                   5903:                  'skipped' file
                   5904: 
1.423     albertel 5905: =cut
                   5906: 
1.157     albertel 5907: sub scantron_put_line {
1.200     albertel 5908:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5909:     if ($skip) {
                   5910: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5911: 	&start_skipping($scan_data,$i);
1.157     albertel 5912: 	return;
                   5913:     }
                   5914:     $scanlines->{'corrected'}[$i]=$newline;
                   5915: }
                   5916: 
1.423     albertel 5917: =pod
                   5918: 
                   5919: =item scantron_clear_skip
                   5920: 
1.424     albertel 5921:    Remove a line from the 'skipped' file
                   5922: 
                   5923:  Arguments:
                   5924:     $scanlines - hash ref that looks like the first return value from
                   5925:                  &scantron_getfile()
                   5926:     $scan_data - hash ref that looks like the second return value from
                   5927:                  &scantron_getfile()
                   5928:     $i         - line number to update
                   5929: 
1.423     albertel 5930: =cut
                   5931: 
1.376     albertel 5932: sub scantron_clear_skip {
                   5933:     my ($scanlines,$scan_data,$i)=@_;
                   5934:     if (exists($scanlines->{'skipped'}[$i])) {
                   5935: 	undef($scanlines->{'skipped'}[$i]);
                   5936: 	return 1;
                   5937:     }
                   5938:     return 0;
                   5939: }
                   5940: 
1.423     albertel 5941: =pod
                   5942: 
                   5943: =item scantron_filter_not_exam
                   5944: 
1.424     albertel 5945:    Filter routine used by &Apache::lonnavmaps::retrieveResources(), to
                   5946:    filter out resources that are not marked as 'exam' mode
                   5947: 
1.423     albertel 5948: =cut
                   5949: 
1.334     albertel 5950: sub scantron_filter_not_exam {
                   5951:     my ($curres)=@_;
                   5952:     
                   5953:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5954: 	# if the user has asked to not have either hidden
                   5955: 	# or 'randomout' controlled resources to be graded
                   5956: 	# don't include them
                   5957: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5958: 	    && $curres->randomout) {
                   5959: 	    return 0;
                   5960: 	}
                   5961: 	return 1;
                   5962:     }
                   5963:     return 0;
                   5964: }
                   5965: 
1.423     albertel 5966: =pod
                   5967: 
                   5968: =item scantron_validate_sequence
                   5969: 
1.424     albertel 5970:     Validates the selected sequence, checking for resource that are
                   5971:     not set to exam mode.
                   5972: 
1.423     albertel 5973: =cut
                   5974: 
1.334     albertel 5975: sub scantron_validate_sequence {
                   5976:     my ($r,$currentphase) = @_;
                   5977: 
                   5978:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5979:     my (undef,undef,$sequence)=
                   5980: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5981: 
                   5982:     my $map=$navmap->getResourceByUrl($sequence);
                   5983: 
                   5984:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5985:                                     value="ignore" />');
                   5986:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5987: 	my @resources=
                   5988: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5989: 	if (@resources) {
1.357     banghart 5990: 	    $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 5991: 	    return (1,$currentphase);
                   5992: 	}
                   5993:     }
                   5994: 
                   5995:     return (0,$currentphase+1);
                   5996: }
                   5997: 
1.423     albertel 5998: =pod
                   5999: 
                   6000: =item scantron_validate_ID
                   6001: 
1.424     albertel 6002:    Validates all scanlines in the selected file to not have any
                   6003:    invalid or underspecified student IDs
                   6004: 
1.423     albertel 6005: =cut
                   6006: 
1.157     albertel 6007: sub scantron_validate_ID {
                   6008:     my ($r,$currentphase) = @_;
                   6009:     
                   6010:     #get student info
                   6011:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6012:     my %idmap=&username_to_idmap($classlist);
                   6013: 
                   6014:     #get scantron line setup
1.257     albertel 6015:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6016:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6017: 
                   6018:     my %found=('ids'=>{},'usernames'=>{});
                   6019:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6020: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6021: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6022: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6023: 						 $scan_data);
                   6024: 	my $id=$$scan_record{'scantron.ID'};
                   6025: 	my $found;
                   6026: 	foreach my $checkid (keys(%idmap)) {
                   6027: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   6028: 	}
                   6029: 	if ($found) {
                   6030: 	    my $username=$idmap{$found};
                   6031: 	    if ($found{'ids'}{$found}) {
                   6032: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6033: 					 $line,'duplicateID',$found);
1.194     albertel 6034: 		return(1,$currentphase);
1.157     albertel 6035: 	    } elsif ($found{'usernames'}{$username}) {
                   6036: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6037: 					 $line,'duplicateID',$username);
1.194     albertel 6038: 		return(1,$currentphase);
1.157     albertel 6039: 	    }
1.186     albertel 6040: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 6041: 	    $found{'ids'}{$found}++;
                   6042: 	    $found{'usernames'}{$username}++;
                   6043: 	} else {
                   6044: 	    if ($id =~ /^\s*$/) {
1.158     albertel 6045: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 6046: 		if (defined($username) && $found{'usernames'}{$username}) {
                   6047: 		    &scantron_get_correction($r,$i,$scan_record,
                   6048: 					     \%scantron_config,
                   6049: 					     $line,'duplicateID',$username);
1.194     albertel 6050: 		    return(1,$currentphase);
1.157     albertel 6051: 		} elsif (!defined($username)) {
                   6052: 		    &scantron_get_correction($r,$i,$scan_record,
                   6053: 					     \%scantron_config,
                   6054: 					     $line,'incorrectID');
1.194     albertel 6055: 		    return(1,$currentphase);
1.157     albertel 6056: 		}
                   6057: 		$found{'usernames'}{$username}++;
                   6058: 	    } else {
                   6059: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6060: 					 $line,'incorrectID');
1.194     albertel 6061: 		return(1,$currentphase);
1.157     albertel 6062: 	    }
                   6063: 	}
                   6064:     }
                   6065: 
                   6066:     return (0,$currentphase+1);
                   6067: }
                   6068: 
1.423     albertel 6069: =pod
                   6070: 
                   6071: =item scantron_get_correction
                   6072: 
1.424     albertel 6073:    Builds the interface screen to interact with the operator to fix a
                   6074:    specific error condition in a specific scanline
                   6075: 
                   6076:  Arguments:
                   6077:     $r           - Apache request object
                   6078:     $i           - number of the current scanline
                   6079:     $scan_record - hash ref as returned from &scantron_parse_scanline()
                   6080:     $scan_config - hash ref as returned from &get_scantron_config()
                   6081:     $line        - full contents of the current scanline
                   6082:     $error       - error condition, valid values are
                   6083:                    'incorrectCODE', 'duplicateCODE',
                   6084:                    'doublebubble', 'missingbubble',
                   6085:                    'duplicateID', 'incorrectID'
                   6086:     $arg         - extra information needed
                   6087:        For errors:
                   6088:          - duplicateID   - paper number that this studentID was seen before on
                   6089:          - duplicateCODE - array ref of the paper numbers this CODE was
                   6090:                            seen on before
                   6091:          - incorrectCODE - current incorrect CODE 
                   6092:          - doublebubble  - array ref of the bubble lines that have double
                   6093:                            bubble errors
                   6094:          - missingbubble - array ref of the bubble lines that have missing
                   6095:                            bubble errors
                   6096: 
1.423     albertel 6097: =cut
                   6098: 
1.157     albertel 6099: sub scantron_get_correction {
                   6100:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   6101: 
                   6102: #FIXME in the case of a duplicated ID the previous line, probaly need
                   6103: #to show both the current line and the previous one and allow skipping
                   6104: #the previous one or the current one
                   6105: 
1.161     albertel 6106:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 6107:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 6108: 	$r->print(" for PaperID <tt>".
                   6109: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   6110:     } else {
                   6111: 	$r->print(" in scanline $i <pre>".
                   6112: 		  $line."</pre> \n");
                   6113:     }
1.242     albertel 6114:     my $message="<p>The ID on the form is  <tt>".
                   6115: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   6116: 	"The name on the paper is ".
                   6117: 	$$scan_record{'scantron.LastName'}.",".
                   6118: 	$$scan_record{'scantron.FirstName'}."</p>";
                   6119: 
1.157     albertel 6120:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   6121:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   6122:     if ($error =~ /ID$/) {
1.186     albertel 6123: 	if ($error eq 'incorrectID') {
1.157     albertel 6124: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   6125: 	} elsif ($error eq 'duplicateID') {
                   6126: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   6127: 	}
1.242     albertel 6128: 	$r->print($message);
1.157     albertel 6129: 	$r->print("<p>How should I handle this? <br /> \n");
                   6130: 	$r->print("\n<ul><li> ");
                   6131: 	#FIXME it would be nice if this sent back the user ID and
                   6132: 	#could do partial userID matches
                   6133: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   6134: 				       'scantron_username','scantron_domain'));
                   6135: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   6136: 	$r->print("\n@".
1.257     albertel 6137: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 6138: 
                   6139: 	$r->print('</li>');
1.186     albertel 6140:     } elsif ($error =~ /CODE$/) {
                   6141: 	if ($error eq 'incorrectCODE') {
1.187     albertel 6142: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 6143: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 6144: 	    $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 6145: 	}
1.224     albertel 6146: 	$r->print("<p>The CODE on the form is  <tt>'".
                   6147: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 6148: 	$r->print($message);
1.186     albertel 6149: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 6150: 	$r->print("\n<br /> ");
1.194     albertel 6151: 	my $i=0;
1.273     albertel 6152: 	if ($error eq 'incorrectCODE' 
                   6153: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 6154: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 6155: 	    if ($closest > 0) {
                   6156: 		foreach my $testcode (@{$closest}) {
                   6157: 		    my $checked='';
1.401     albertel 6158: 		    if (!$i) { $checked=' checked="checked" '; }
1.278     albertel 6159: 		    $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' />");
                   6160: 		    $r->print("\n<br />");
                   6161: 		    $i++;
                   6162: 		}
1.194     albertel 6163: 	    }
                   6164: 	}
1.273     albertel 6165: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
1.401     albertel 6166: 	    my $checked; if (!$i) { $checked=' checked="checked" '; }
1.273     albertel 6167: 	    $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>");
                   6168: 	    $r->print("\n<br />");
                   6169: 	}
1.194     albertel 6170: 
1.188     albertel 6171: 	$r->print(<<ENDSCRIPT);
                   6172: <script type="text/javascript">
                   6173: function change_radio(field) {
1.190     albertel 6174:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 6175:     var i;
                   6176:     for (i=0;i<slct.length;i++) {
                   6177:         if (slct[i].value==field) { slct[i].checked=true; }
                   6178:     }
                   6179: }
                   6180: </script>
                   6181: ENDSCRIPT
1.187     albertel 6182: 	my $href="/adm/pickcode?".
1.359     www      6183: 	   "form=".&escape("scantronupload").
                   6184: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   6185: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   6186: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   6187: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 6188: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   6189: 	    $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')\" />");
                   6190: 	    $r->print("\n<br />");
                   6191: 	}
1.272     albertel 6192: 	$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 6193: 	$r->print("\n<br /><br />");
1.157     albertel 6194:     } elsif ($error eq 'doublebubble') {
                   6195: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   6196: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6197: 		  join(',',@{$arg}).'" />');
1.242     albertel 6198: 	$r->print($message);
1.157     albertel 6199: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6200: 	foreach my $question (@{$arg}) {
                   6201: 	    my $selected=$$scan_record{"scantron.$question.answer"};
1.422     foxr     6202: 	    &scantron_bubble_selector($r,$scan_config,$question,
                   6203: 				      split('',$selected));
1.157     albertel 6204: 	}
                   6205:     } elsif ($error eq 'missingbubble') {
                   6206: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 6207: 	$r->print($message);
1.157     albertel 6208: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   6209: 	$r->print("Some questions have no scanned bubbles\n");
                   6210: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   6211: 		  join(',',@{$arg}).'" />');
                   6212: 	foreach my $question (@{$arg}) {
                   6213: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   6214: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   6215: 	}
                   6216:     } else {
                   6217: 	$r->print("\n<ul>");
                   6218:     }
                   6219:     $r->print("\n</li></ul>");
                   6220: 
                   6221: }
1.423     albertel 6222: 
                   6223: =pod
                   6224: 
                   6225: =item scantron_bubble_selector
                   6226:   
                   6227:    Generates the html radiobuttons to correct a single bubble line
1.424     albertel 6228:    possibly showing the existing the selected bubbles if known
1.423     albertel 6229: 
                   6230:  Arguments:
                   6231:     $r           - Apache request object
                   6232:     $scan_config - hash from &get_scantron_config()
                   6233:     $quest       - number of the bubble line to make a corrector for
                   6234:     $selected    - array of letters of previously selected bubbles
                   6235:     $lines       - if present, number of bubble lines to show
                   6236: 
                   6237: =cut
                   6238: 
1.157     albertel 6239: sub scantron_bubble_selector {
1.422     foxr     6240:     my ($r,$scan_config,$quest,@selected, $lines)=@_;
1.157     albertel 6241:     my $max=$$scan_config{'Qlength'};
1.274     albertel 6242: 
                   6243:     my $scmode=$$scan_config{'Qon'};
                   6244:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   6245: 
1.422     foxr     6246: 
                   6247:     if (!defined($lines)) {
                   6248: 	$lines = 1;
                   6249:     }
                   6250:     my $total_lines = $lines*2;
1.157     albertel 6251:     my @alphabet=('A'..'Z');
1.422     foxr     6252:     $r->print("<table border='1'><tr><td rowspan='".$total_lines."'>$quest</td>");
                   6253: 
                   6254:     for (my $l = 0; $l < $lines; $l++) {
                   6255: 	if ($l != 0) {
                   6256: 	    $r->print('<tr>');
                   6257: 	}
                   6258: 
                   6259: 	# FIXME:  This loop probably has to be considerably more clever for
                   6260: 	#  multiline bubbles: User can multibubble by having bubbles in
                   6261: 	#  several lines.  User can skip lines legitimately etc. etc.
                   6262: 
                   6263: 	for (my $i=0;$i<$max;$i++) {
                   6264: 	    $r->print("\n".'<td align="center">');
                   6265: 	    if ($selected[0] eq $alphabet[$i]) { 
                   6266: 		$r->print('X'); 
                   6267: 		shift(@selected) ;
                   6268: 	    } else { 
                   6269: 		$r->print('&nbsp;'); 
                   6270: 	    }
                   6271: 	    $r->print('</td>');
                   6272: 	    
                   6273: 	}
                   6274: 
                   6275: 	if ($l == 0) {
                   6276: 	    my $lspan = $total_lines * 2;   #  2 table rows per bubble line.
                   6277: 
                   6278: 	    $r->print('<td rowspan='.$lspan.'><label><input type="radio" name="scantron_correct_Q_'.
                   6279: 	      $quest.'" value="none" /> No bubble </label></td>');
                   6280: 	
                   6281: 	}
                   6282: 
                   6283: 	$r->print('</tr><tr>');
                   6284: 
                   6285: 	# FIXME: This may have to be a bit more clever for
                   6286: 	#        multiline questions (different values e.g..).
                   6287: 
                   6288: 	for (my $i=0;$i<$max;$i++) {
                   6289: 	    $r->print("\n".
                   6290: 		      '<td><label><input type="radio" name="scantron_correct_Q_'.
                   6291: 		      $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
                   6292: 	}
                   6293: 	$r->print('</tr>');
                   6294: 
                   6295: 	    
1.157     albertel 6296:     }
1.422     foxr     6297:     $r->print('</table>');
1.157     albertel 6298: }
                   6299: 
1.423     albertel 6300: =pod
                   6301: 
                   6302: =item num_matches
                   6303: 
1.424     albertel 6304:    Counts the number of characters that are the same between the two arguments.
                   6305: 
                   6306:  Arguments:
                   6307:    $orig - CODE from the scanline
                   6308:    $code - CODE to match against
                   6309: 
                   6310:  Returns:
                   6311:    $count - integer count of the number of same characters between the
                   6312:             two arguments
                   6313: 
1.423     albertel 6314: =cut
                   6315: 
1.194     albertel 6316: sub num_matches {
                   6317:     my ($orig,$code) = @_;
                   6318:     my @code=split(//,$code);
                   6319:     my @orig=split(//,$orig);
                   6320:     my $same=0;
                   6321:     for (my $i=0;$i<scalar(@code);$i++) {
                   6322: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   6323:     }
                   6324:     return $same;
                   6325: }
                   6326: 
1.423     albertel 6327: =pod
                   6328: 
                   6329: =item scantron_get_closely_matching_CODEs
                   6330: 
1.424     albertel 6331:    Cycles through all CODEs and finds the set that has the greatest
                   6332:    number of same characters as the provided CODE
                   6333: 
                   6334:  Arguments:
                   6335:    $allcodes - hash ref returned by &get_codes()
                   6336:    $CODE     - CODE from the current scanline
                   6337: 
                   6338:  Returns:
                   6339:    2 element list
                   6340:     - first elements is number of how closely matching the best fit is 
                   6341:       (5 means best set has 5 matching characters)
                   6342:     - second element is an arrary ref containing the set of valid CODEs
                   6343:       that best fit the passed in CODE
                   6344: 
1.423     albertel 6345: =cut
                   6346: 
1.194     albertel 6347: sub scantron_get_closely_matching_CODEs {
                   6348:     my ($allcodes,$CODE)=@_;
                   6349:     my @CODEs;
                   6350:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   6351: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   6352:     }
                   6353: 
                   6354:     return ($#CODEs,$CODEs[-1]);
                   6355: }
                   6356: 
1.423     albertel 6357: =pod
                   6358: 
                   6359: =item get_codes
                   6360: 
1.424     albertel 6361:    Builds a hash which has keys of all of the valid CODEs from the selected
                   6362:    set of remembered CODEs.
                   6363: 
                   6364:  Arguments:
                   6365:   $old_name - name of the set of remembered CODEs
                   6366:   $cdom     - domain of the course
                   6367:   $cnum     - internal course name
                   6368: 
                   6369:  Returns:
                   6370:   %allcodes - keys are the valid CODEs, values are all 1
                   6371: 
1.423     albertel 6372: =cut
                   6373: 
1.194     albertel 6374: sub get_codes {
1.280     foxr     6375:     my ($old_name, $cdom, $cnum) = @_;
                   6376:     if (!$old_name) {
                   6377: 	$old_name=$env{'form.scantron_CODElist'};
                   6378:     }
                   6379:     if (!$cdom) {
                   6380: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6381:     }
                   6382:     if (!$cnum) {
                   6383: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   6384:     }
1.278     albertel 6385:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   6386: 				    $cdom,$cnum);
                   6387:     my %allcodes;
                   6388:     if ($result{"type\0$old_name"} eq 'number') {
                   6389: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   6390:     } else {
                   6391: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   6392:     }
1.194     albertel 6393:     return %allcodes;
                   6394: }
                   6395: 
1.423     albertel 6396: =pod
                   6397: 
                   6398: =item scantron_validate_CODE
                   6399: 
1.424     albertel 6400:    Validates all scanlines in the selected file to not have any
                   6401:    invalid or underspecified CODEs and that none of the codes are
                   6402:    duplicated if this was requested.
                   6403: 
1.423     albertel 6404: =cut
                   6405: 
1.157     albertel 6406: sub scantron_validate_CODE {
                   6407:     my ($r,$currentphase) = @_;
1.257     albertel 6408:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 6409:     if ($scantron_config{'CODElocation'} &&
                   6410: 	$scantron_config{'CODEstart'} &&
                   6411: 	$scantron_config{'CODElength'}) {
1.257     albertel 6412: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 6413: 	    &FIXME_blow_up()
                   6414: 	}
                   6415:     } else {
                   6416: 	return (0,$currentphase+1);
                   6417:     }
                   6418:     
                   6419:     my %usedCODEs;
                   6420: 
1.194     albertel 6421:     my %allcodes=&get_codes();
1.186     albertel 6422: 
                   6423:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6424:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6425: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 6426: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6427: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6428: 						 $scan_data);
                   6429: 	my $CODE=$$scan_record{'scantron.CODE'};
                   6430: 	my $error=0;
1.224     albertel 6431: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   6432: 	    &scantron_get_correction($r,$i,$scan_record,
                   6433: 				     \%scantron_config,
                   6434: 				     $line,'incorrectCODE',\%allcodes);
                   6435: 	    return(1,$currentphase);
                   6436: 	}
1.221     albertel 6437: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   6438: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 6439: 	    &scantron_get_correction($r,$i,$scan_record,
                   6440: 				     \%scantron_config,
1.194     albertel 6441: 				     $line,'incorrectCODE',\%allcodes);
                   6442: 	    return(1,$currentphase);
1.186     albertel 6443: 	}
1.214     albertel 6444: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 6445: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 6446: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 6447: 	    &scantron_get_correction($r,$i,$scan_record,
                   6448: 				     \%scantron_config,
1.194     albertel 6449: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   6450: 	    return(1,$currentphase);
1.186     albertel 6451: 	}
1.194     albertel 6452: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 6453:     }
1.157     albertel 6454:     return (0,$currentphase+1);
                   6455: }
                   6456: 
1.423     albertel 6457: =pod
                   6458: 
                   6459: =item scantron_validate_doublebubble
                   6460: 
1.424     albertel 6461:    Validates all scanlines in the selected file to not have any
                   6462:    bubble lines with multiple bubbles marked.
                   6463: 
1.423     albertel 6464: =cut
                   6465: 
1.157     albertel 6466: sub scantron_validate_doublebubble {
                   6467:     my ($r,$currentphase) = @_;
                   6468:     #get student info
                   6469:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6470:     my %idmap=&username_to_idmap($classlist);
                   6471: 
                   6472:     #get scantron line setup
1.257     albertel 6473:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6474:     my ($scanlines,$scan_data)=&scantron_getfile();
                   6475:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6476: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6477: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6478: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6479: 						 $scan_data);
                   6480: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   6481: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   6482: 				 'doublebubble',
                   6483: 				 $$scan_record{'scantron.doubleerror'});
                   6484:     	return (1,$currentphase);
                   6485:     }
                   6486:     return (0,$currentphase+1);
                   6487: }
                   6488: 
1.423     albertel 6489: =pod
                   6490: 
                   6491: =item scantron_get_maxbubble
                   6492: 
1.424     albertel 6493:    Returns the maximum number of bubble lines that are expected to
                   6494:    occur. Does this by walking the selected sequence rendering the
                   6495:    resource and then checking &Apache::lonxml::get_problem_counter()
                   6496:    for what the current value of the problem counter is.
                   6497: 
                   6498:    Caches the result to $env{'form.scantron_maxbubble'}
                   6499: 
1.423     albertel 6500: =cut
                   6501: 
1.330     albertel 6502: sub scantron_get_maxbubble {    
1.435     foxr     6503: 
1.257     albertel 6504:     if (defined($env{'form.scantron_maxbubble'}) &&
                   6505: 	$env{'form.scantron_maxbubble'}) {
                   6506: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 6507:     }
1.330     albertel 6508: 
1.191     albertel 6509:     my $navmap=Apache::lonnavmaps::navmap->new();
                   6510:     my (undef,undef,$sequence)=
1.257     albertel 6511: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 6512: 
1.191     albertel 6513:     my $map=$navmap->getResourceByUrl($sequence);
                   6514:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 6515: 
                   6516:     &Apache::lonxml::clear_problem_counter();
                   6517: 
1.435     foxr     6518:     my $uname       = $env{'form.student'};
                   6519:     my $udom        = $env{'form.userdom'};
                   6520:     my $cid         = $env{'request.course.id'};
                   6521:     my $total_lines = 0;
                   6522:     %bubble_lines_per_response = ();
                   6523: 
1.191     albertel 6524:     foreach my $resource (@resources) {
1.435     foxr     6525: 	my $symb = $resource->symb();
1.330     albertel 6526: 	my $result=&Apache::lonnet::ssi($resource->src(),
1.435     foxr     6527: 					('symb' => $resource->symb()),
                   6528: 					('grade_target' => 'analyze'),
                   6529: 					('grade_courseid' => $cid),
                   6530: 					('grade_domain' => $udom),
                   6531: 					('grade_username' => $uname));
1.436     albertel 6532: 	my (undef, $an) =
1.435     foxr     6533: 	    split(/_HASH_REF__/,$result, 2);
                   6534: 
                   6535: 	my %analysis = &Apache::lonnet::str2hash($an);
                   6536: 
                   6537: 
                   6538: 
                   6539: 	foreach my $part_id (@{$analysis{'parts'}}) {
                   6540: 	    my $bubble_lines = $analysis{"$part_id.bubble_lines"}[0];
                   6541: 	    if (!$bubble_lines) {
                   6542: 		$bubble_lines = 1;
                   6543: 	    }
                   6544: 	    $bubble_lines_per_response{"$symb.$part_id"} = $bubble_lines;
                   6545: 	    $total_lines = $total_lines + $bubble_lines;
                   6546: 	}
                   6547: 
1.191     albertel 6548:     }
                   6549:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 6550:     $env{'form.scantron_maxbubble'} =
1.435     foxr     6551: 	$total_lines;
1.257     albertel 6552:     return $env{'form.scantron_maxbubble'};
1.191     albertel 6553: }
                   6554: 
1.423     albertel 6555: =pod
                   6556: 
                   6557: =item scantron_validate_missingbubbles
                   6558: 
1.424     albertel 6559:    Validates all scanlines in the selected file to not have any
                   6560:    bubble lines with missing bubbles that haven't been verified as missing.
                   6561: 
1.423     albertel 6562: =cut
                   6563: 
1.157     albertel 6564: sub scantron_validate_missingbubbles {
                   6565:     my ($r,$currentphase) = @_;
                   6566:     #get student info
                   6567:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6568:     my %idmap=&username_to_idmap($classlist);
                   6569: 
                   6570:     #get scantron line setup
1.257     albertel 6571:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6572:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 6573:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 6574:     if (!$max_bubble) { $max_bubble=2**31; }
                   6575:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 6576: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6577: 	if ($line=~/^[\s\cz]*$/) { next; }
                   6578: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6579: 						 $scan_data);
                   6580: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   6581: 	my @to_correct;
                   6582: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   6583: 	    if ($missing > $max_bubble) { next; }
                   6584: 	    push(@to_correct,$missing);
                   6585: 	}
                   6586: 	if (@to_correct) {
                   6587: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   6588: 				     $line,'missingbubble',\@to_correct);
                   6589: 	    return (1,$currentphase);
                   6590: 	}
                   6591: 
                   6592:     }
                   6593:     return (0,$currentphase+1);
                   6594: }
                   6595: 
1.423     albertel 6596: =pod
                   6597: 
                   6598: =item scantron_process_students
                   6599: 
                   6600:    Routine that does the actual grading of the bubble sheet information.
                   6601: 
                   6602:    The parsed scanline hash is added to %env 
                   6603: 
                   6604:    Then foreach unskipped scanline it does an &Apache::lonnet::ssi()
                   6605:    foreach resource , with the form data of
                   6606: 
                   6607: 	'submitted'     =>'scantron' 
                   6608: 	'grade_target'  =>'grade',
                   6609: 	'grade_username'=> username of student
                   6610: 	'grade_domain'  => domain of student
                   6611: 	'grade_courseid'=> of course
                   6612: 	'grade_symb'    => symb of resource to grade
                   6613: 
                   6614:     This triggers a grading pass. The problem grading code takes care
                   6615:     of converting the bubbled letter information (now in %env) into a
                   6616:     valid submission.
                   6617: 
                   6618: =cut
                   6619: 
1.82      albertel 6620: sub scantron_process_students {
1.75      albertel 6621:     my ($r) = @_;
1.257     albertel 6622:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 6623:     my ($symb)=&get_symb($r);
1.81      albertel 6624:     if (!$symb) {return '';}
1.324     albertel 6625:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 6626: 
1.257     albertel 6627:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 6628:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 6629:     my $classlist=&Apache::loncoursedata::get_classlist();
                   6630:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 6631:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 6632:     my $map=$navmap->getResourceByUrl($sequence);
                   6633:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 6634: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 6635:     my $result= <<SCANTRONFORM;
1.81      albertel 6636: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   6637:   <input type="hidden" name="command" value="scantron_configphase" />
                   6638:   $default_form_data
                   6639: SCANTRONFORM
1.82      albertel 6640:     $r->print($result);
                   6641: 
                   6642:     my @delayqueue;
1.140     albertel 6643:     my %completedstudents;
                   6644:     
1.200     albertel 6645:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 6646:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 6647:  				    'Scantron Progress',$count,
1.195     albertel 6648: 				    'inline',undef,'scantronupload');
1.140     albertel 6649:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   6650: 					  'Processing first student');
                   6651:     my $start=&Time::HiRes::time();
1.158     albertel 6652:     my $i=-1;
1.200     albertel 6653:     my ($uname,$udom,$started);
1.157     albertel 6654:     while ($i<$scanlines->{'count'}) {
                   6655:  	($uname,$udom)=('','');
                   6656:  	$i++;
1.200     albertel 6657:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 6658:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 6659: 	if ($started) {
                   6660: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   6661: 						     'last student');
                   6662: 	}
                   6663: 	$started=1;
1.157     albertel 6664:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   6665:  						 $scan_data);
                   6666:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   6667:  					      \%idmap,$i)) {
                   6668:   	    &scantron_add_delay(\@delayqueue,$line,
                   6669:  				'Unable to find a student that matches',1);
                   6670:  	    next;
                   6671:   	}
                   6672:  	if (exists $completedstudents{$uname}) {
                   6673:  	    &scantron_add_delay(\@delayqueue,$line,
                   6674:  				'Student '.$uname.' has multiple sheets',2);
                   6675:  	    next;
                   6676:  	}
                   6677:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 6678: 
                   6679: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 6680:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 6681: 
                   6682: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   6683: 	    &scantron_putfile($scanlines,$scan_data);
                   6684: 	}
1.161     albertel 6685: 	
                   6686: 	my $i=0;
1.83      albertel 6687: 	foreach my $resource (@resources) {
1.85      albertel 6688: 	    $i++;
1.193     albertel 6689: 	    my %form=('submitted'     =>'scantron',
                   6690: 		      'grade_target'  =>'grade',
                   6691: 		      'grade_username'=>$uname,
                   6692: 		      'grade_domain'  =>$udom,
1.257     albertel 6693: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 6694: 		      'grade_symb'    =>$resource->symb());
1.383     albertel 6695: 	    if (exists($scan_record->{'scantron.CODE'})
                   6696: 		&& 
                   6697: 		&Apache::lonnet::validCODE($scan_record->{'scantron.CODE'})) {
1.193     albertel 6698: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 6699: 	    } else {
                   6700: 		$form{'CODE'}='';
1.193     albertel 6701: 	    }
                   6702: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 6703: 	    if ($result ne '') {
                   6704: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 6705: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 6706: 	    }
1.213     albertel 6707: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 6708: 	}
1.140     albertel 6709: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 6710: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 6711:     } continue {
1.330     albertel 6712: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 6713: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 6714:     }
1.140     albertel 6715:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 6716: #    my $lasttime = &Time::HiRes::time()-$start;
                   6717: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 6718: 
1.200     albertel 6719:     $r->print("</form>");
1.324     albertel 6720:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 6721:     return '';
1.75      albertel 6722: }
1.157     albertel 6723: 
1.423     albertel 6724: =pod
                   6725: 
                   6726: =item scantron_upload_scantron_data
                   6727: 
                   6728:     Creates the screen for adding a new bubble sheet data file to a course.
                   6729: 
                   6730: =cut
                   6731: 
1.157     albertel 6732: sub scantron_upload_scantron_data {
                   6733:     my ($r)=@_;
1.257     albertel 6734:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 6735:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 6736: 							  'domainid',
                   6737: 							  'coursename');
1.257     albertel 6738:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 6739: 						   'domainid');
1.324     albertel 6740:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 6741:     $r->print(<<UPLOAD);
                   6742: <script type="text/javascript" language="javascript">
                   6743:     function checkUpload(formname) {
                   6744: 	if (formname.upfile.value == "") {
                   6745: 	    alert("Please use the browse button to select a file from your local directory.");
                   6746: 	    return false;
                   6747: 	}
                   6748: 	formname.submit();
                   6749:     }
                   6750: </script>
                   6751: 
                   6752: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 6753: $default_form_data
1.181     albertel 6754: <table>
                   6755: <tr><td>$select_link </td></tr>
                   6756: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   6757: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   6758: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   6759: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   6760: </table>
1.157     albertel 6761: <input name='command' value='scantronupload_save' type='hidden' />
                   6762: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   6763: </form>
                   6764: UPLOAD
                   6765:     return '';
                   6766: }
                   6767: 
1.423     albertel 6768: =pod
                   6769: 
                   6770: =item scantron_upload_scantron_data_save
                   6771: 
                   6772:    Adds a provided bubble information data file to the course if user
                   6773:    has the correct privileges to do so.  
                   6774: 
                   6775: =cut
                   6776: 
1.157     albertel 6777: sub scantron_upload_scantron_data_save {
                   6778:     my($r)=@_;
1.324     albertel 6779:     my ($symb)=&get_symb($r,1);
1.182     albertel 6780:     my $doanotherupload=
                   6781: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   6782: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   6783: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   6784: 	'</form>'."\n";
1.257     albertel 6785:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 6786: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 6787: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 6788: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 6789: 	if ($symb) {
1.324     albertel 6790: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 6791: 	} else {
                   6792: 	    $r->print($doanotherupload);
                   6793: 	}
1.162     albertel 6794: 	return '';
                   6795:     }
1.257     albertel 6796:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       6797:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 6798:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 6799:     #FIXME
                   6800:     #copied from lonnet::userfileupload()
                   6801:     #make that function able to target a specified course
                   6802:     # Replace Windows backslashes by forward slashes
                   6803:     $fname=~s/\\/\//g;
                   6804:     # Get rid of everything but the actual filename
                   6805:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   6806:     # Replace spaces by underscores
                   6807:     $fname=~s/\s+/\_/g;
                   6808:     # Replace all other weird characters by nothing
                   6809:     $fname=~s/[^\w\.\-]//g;
                   6810:     # See if there is anything left
                   6811:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       6812:     my $uploadedfile=$fname;
1.157     albertel 6813:     $fname='scantron_orig_'.$fname;
1.257     albertel 6814:     if (length($env{'form.upfile'}) < 2) {
1.398     albertel 6815: 	$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 6816:     } else {
1.275     albertel 6817: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 6818: 	if ($result =~ m|^/uploaded/|) {
1.398     albertel 6819: 	    $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 6820: 	} else {
1.398     albertel 6821: 	    $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 6822: 	}
                   6823:     }
1.174     albertel 6824:     if ($symb) {
1.209     ng       6825: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 6826:     } else {
1.182     albertel 6827: 	$r->print($doanotherupload);
1.174     albertel 6828:     }
1.157     albertel 6829:     return '';
                   6830: }
                   6831: 
1.423     albertel 6832: =pod
                   6833: 
                   6834: =item valid_file
                   6835: 
1.424     albertel 6836:    Validates that the requested bubble data file exists in the course.
1.423     albertel 6837: 
                   6838: =cut
                   6839: 
1.202     albertel 6840: sub valid_file {
                   6841:     my ($requested_file)=@_;
                   6842:     foreach my $filename (sort(&scantron_filenames())) {
                   6843: 	if ($requested_file eq $filename) { return 1; }
                   6844:     }
                   6845:     return 0;
                   6846: }
                   6847: 
1.423     albertel 6848: =pod
                   6849: 
                   6850: =item scantron_download_scantron_data
                   6851: 
                   6852:    Shows a list of the three internal files (original, corrected,
                   6853:    skipped) for a specific bubble sheet data file that exists in the
                   6854:    course.
                   6855: 
                   6856: =cut
                   6857: 
1.202     albertel 6858: sub scantron_download_scantron_data {
                   6859:     my ($r)=@_;
1.324     albertel 6860:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 6861:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6862:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   6863:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 6864:     if (! &valid_file($file)) {
                   6865: 	$r->print(<<ERROR);
                   6866: 	<p>
                   6867: 	    The requested file name was invalid.
                   6868:         </p>
                   6869: ERROR
1.324     albertel 6870: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6871: 	return;
                   6872:     }
                   6873:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   6874:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   6875:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   6876:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   6877:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   6878:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   6879:     $r->print(<<DOWNLOAD);
                   6880:     <p>
                   6881: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   6882:     </p>
                   6883:     <p>
                   6884: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   6885:     </p>
                   6886:     <p>
                   6887: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   6888:     </p>
                   6889: DOWNLOAD
1.324     albertel 6890:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 6891:     return '';
                   6892: }
1.157     albertel 6893: 
1.423     albertel 6894: =pod
                   6895: 
                   6896: =back
                   6897: 
                   6898: =cut
                   6899: 
1.75      albertel 6900: #-------- end of section for handling grading scantron forms -------
                   6901: #
                   6902: #-------------------------------------------------------------------
                   6903: 
1.72      ng       6904: #-------------------------- Menu interface -------------------------
                   6905: #
                   6906: #--- Show a Grading Menu button - Calls the next routine ---
                   6907: sub show_grading_menu_form {
1.324     albertel 6908:     my ($symb)=@_;
1.125     ng       6909:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.418     albertel 6910: 	'<input type="hidden" name="symb" value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.257     albertel 6911: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       6912: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   6913: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   6914: 	'</form>'."\n";
                   6915:     return $result;
                   6916: }
                   6917: 
1.77      ng       6918: # -- Retrieve choices for grading form
                   6919: sub savedState {
                   6920:     my %savedState = ();
1.257     albertel 6921:     if ($env{'form.saveState'}) {
                   6922: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       6923: 	    my ($key,$value) = split(/=/,$_,2);
                   6924: 	    $savedState{$key} = $value;
                   6925: 	}
                   6926:     }
                   6927:     return \%savedState;
                   6928: }
1.76      ng       6929: 
1.72      ng       6930: #--- Displays the main menu page -------
                   6931: sub gradingmenu {
                   6932:     my ($request) = @_;
1.324     albertel 6933:     my ($symb)=&get_symb($request);
1.72      ng       6934:     if (!$symb) {return '';}
1.76      ng       6935:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       6936: 
                   6937:     $request->print(<<GRADINGMENUJS);
                   6938: <script type="text/javascript" language="javascript">
1.116     ng       6939:     function checkChoice(formname,val,cmdx) {
                   6940: 	if (val <= 2) {
                   6941: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       6942: 	    var cmdsave = cmd;
1.116     ng       6943: 	} else {
                   6944: 	    cmd = cmdx;
1.118     ng       6945: 	    cmdsave = 'submission';
1.116     ng       6946: 	}
                   6947: 	formname.command.value = cmd;
1.118     ng       6948: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 6949: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       6950: 	if (val < 5) formname.submit();
                   6951: 	if (val == 5) {
1.72      ng       6952: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   6953: 	    formname.submit();
                   6954: 	}
1.238     albertel 6955: 	if (val < 7) formname.submit();
1.72      ng       6956:     }
                   6957: 
                   6958:     function checkReceiptNo(formname,nospace) {
                   6959: 	var receiptNo = formname.receipt.value;
                   6960: 	var checkOpt = false;
                   6961: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   6962: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   6963: 	if (checkOpt) {
                   6964: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   6965: 	    formname.receipt.value = "";
                   6966: 	    formname.receipt.focus();
                   6967: 	    return false;
                   6968: 	}
                   6969: 	return true;
                   6970:     }
                   6971: </script>
                   6972: GRADINGMENUJS
1.118     ng       6973:     &commonJSfunctions($request);
1.398     albertel 6974:     my $result='<h3>&nbsp;<span class="LC_info">Manual Grading/View Submission</span></h3>';
1.324     albertel 6975:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       6976:     $result.=$table;
1.76      ng       6977:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       6978:     my $savedState = &savedState();
1.118     ng       6979:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       6980:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       6981:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       6982:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       6983: 
                   6984:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
1.418     albertel 6985: 	'<input type="hidden" name="symb"        value="'.&Apache::lonenc::check_encrypt($symb).'" />'."\n".
1.72      ng       6986: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   6987: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       6988: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       6989: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       6990: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       6991: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   6992: 
1.326     albertel 6993:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   6994: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       6995: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       6996: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   6997: 
1.326     albertel 6998:     $result.='<table width="100%" border="0">';
1.116     ng       6999:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.429     banghart 7000: 	'&nbsp;'.&mt('Select Section').': <select name="section" multiple="multiple" size="3">'."\n";
1.116     ng       7001:     if (ref($sections)) {
1.155     albertel 7002: 	foreach (sort (@$sections)) {
                   7003: 	    $result.='<option value="'.$_.'" '.
1.401     albertel 7004: 		($saveSec eq $_ ? 'selected="selected"':'').'>'.$_.'</option>'."\n";
1.155     albertel 7005: 	}
1.116     ng       7006:     }
1.401     albertel 7007:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="selected"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       7008: 
1.401     albertel 7009:     $result.=&mt('Student Status').':'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       7010: 
1.116     ng       7011:     $result.='</td></tr>';
                   7012: 
1.288     albertel 7013:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       7014: 	'<input type="radio" name="radioChoice" value="submission" '.
1.401     albertel 7015: 	($saveCmd eq 'submission' ? 'checked="checked"' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 7016: 	'</label> <select name="submitonly">'.
1.145     albertel 7017: 	'<option value="yes" '.
1.401     albertel 7018: 	($saveSub eq 'yes' ? 'selected="selected"' : '').'>'.&mt('with submissions').'</option>'.
1.301     albertel 7019: 	'<option value="queued" '.
1.401     albertel 7020: 	($saveSub eq 'queued' ? 'selected="selected"' : '').'>'.&mt('in grading queue').'</option>'.
1.145     albertel 7021: 	'<option value="graded" '.
1.401     albertel 7022: 	($saveSub eq 'graded' ? 'selected="selected"' : '').'>'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 7023: 	'<option value="incorrect" '.
1.401     albertel 7024: 	($saveSub eq 'incorrect' ? 'selected="selected"' : '').'>'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 7025: 	'<option value="all" '.
1.401     albertel 7026: 	($saveSub eq 'all' ? 'selected="selected"' : '').'>'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       7027: 
1.116     ng       7028:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 7029: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.401     albertel 7030: 	($saveCmd eq 'viewgrades' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7031: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       7032: 
1.118     ng       7033:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 7034: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.401     albertel 7035: 	($saveCmd eq 'pickStudentPage' ? 'checked="checked"' : '').' /> '.
1.288     albertel 7036: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       7037: 
1.116     ng       7038:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       7039: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       7040: 	'</td></tr></table>'."\n";
                   7041: 
                   7042:     $result.='</td><td valign="top">';
                   7043: 
1.326     albertel 7044:     $result.='<table width="100%" border="0">';
1.116     ng       7045:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      7046: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   7047: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       7048: 
1.404     www      7049:     $result.='<tr bgcolor="#ffffe6"><td>'.
                   7050:         '<input type="button" onClick="javascript:checkChoice(this.form,\'6\',\'processclicker\');" value="'.&mt('Process').'" />'.
                   7051:         ' '.&mt('clicker file').' </td></tr>'."\n";
1.400     www      7052: 
1.75      albertel 7053:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       7054: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      7055: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 7056: 
1.257     albertel 7057:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       7058: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      7059: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   7060: 	    ' '.&mt('receipt').': '.
1.257     albertel 7061: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 7062: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       7063: 	    '</td></tr>'."\n";
                   7064:     } 
1.238     albertel 7065:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7066: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   7067: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 7068:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   7069: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   7070: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       7071: 
1.401     albertel 7072:     $result.='</table>'."\n".
1.72      ng       7073: 	'</td></tr></table>'."\n".
1.401     albertel 7074: 	'</td></tr></table></form>'."\n";
1.44      ng       7075:     return $result;
1.2       albertel 7076: }
                   7077: 
1.285     albertel 7078: sub reset_perm {
                   7079:     undef(%perm);
                   7080: }
                   7081: 
                   7082: sub init_perm {
                   7083:     &reset_perm();
1.300     albertel 7084:     foreach my $test_perm ('vgr','mgr','opa') {
                   7085: 
                   7086: 	my $scope = $env{'request.course.id'};
                   7087: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   7088: 
                   7089: 	    $scope .= '/'.$env{'request.course.sec'};
                   7090: 	    if ( $perm{$test_perm}=
                   7091: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   7092: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   7093: 	    } else {
                   7094: 		delete($perm{$test_perm});
                   7095: 	    }
1.285     albertel 7096: 	}
                   7097:     }
                   7098: }
                   7099: 
1.400     www      7100: sub gather_clicker_ids {
1.408     albertel 7101:     my %clicker_ids;
1.400     www      7102: 
                   7103:     my $classlist = &Apache::loncoursedata::get_classlist();
                   7104: 
                   7105:     # Set up a couple variables.
1.407     albertel 7106:     my $username_idx = &Apache::loncoursedata::CL_SNAME();
                   7107:     my $domain_idx   = &Apache::loncoursedata::CL_SDOM();
1.438     www      7108:     my $status_idx   = &Apache::loncoursedata::CL_STATUS();
1.400     www      7109: 
1.407     albertel 7110:     foreach my $student (keys(%$classlist)) {
1.438     www      7111:         if ($classlist->{$student}->[$status_idx] ne 'Active') { next; }
1.407     albertel 7112:         my $username = $classlist->{$student}->[$username_idx];
                   7113:         my $domain   = $classlist->{$student}->[$domain_idx];
1.400     www      7114:         my $clickers =
1.408     albertel 7115: 	    (&Apache::lonnet::userenvironment($domain,$username,'clickers'))[1];
1.400     www      7116:         foreach my $id (split(/\,/,$clickers)) {
1.414     www      7117:             $id=~s/^[\#0]+//;
1.421     www      7118:             $id=~s/[\-\:]//g;
1.407     albertel 7119:             if (exists($clicker_ids{$id})) {
1.408     albertel 7120: 		$clicker_ids{$id}.=','.$username.':'.$domain;
1.400     www      7121:             } else {
1.408     albertel 7122: 		$clicker_ids{$id}=$username.':'.$domain;
1.400     www      7123:             }
                   7124:         }
                   7125:     }
1.407     albertel 7126:     return %clicker_ids;
1.400     www      7127: }
                   7128: 
1.402     www      7129: sub gather_adv_clicker_ids {
1.408     albertel 7130:     my %clicker_ids;
1.402     www      7131:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   7132:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   7133:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
1.409     albertel 7134:     foreach my $element (sort(keys(%coursepersonnel))) {
1.402     www      7135:         foreach my $person (split(/\,/,$coursepersonnel{$element})) {
                   7136:             my ($puname,$pudom)=split(/\:/,$person);
                   7137:             my $clickers =
1.408     albertel 7138: 		(&Apache::lonnet::userenvironment($pudom,$puname,'clickers'))[1];
1.405     www      7139:             foreach my $id (split(/\,/,$clickers)) {
1.414     www      7140: 		$id=~s/^[\#0]+//;
1.421     www      7141:                 $id=~s/[\-\:]//g;
1.408     albertel 7142: 		if (exists($clicker_ids{$id})) {
                   7143: 		    $clicker_ids{$id}.=','.$puname.':'.$pudom;
                   7144: 		} else {
                   7145: 		    $clicker_ids{$id}=$puname.':'.$pudom;
                   7146: 		}
1.405     www      7147:             }
1.402     www      7148:         }
                   7149:     }
1.407     albertel 7150:     return %clicker_ids;
1.402     www      7151: }
                   7152: 
1.413     www      7153: sub clicker_grading_parameters {
                   7154:     return ('gradingmechanism' => 'scalar',
                   7155:             'upfiletype' => 'scalar',
                   7156:             'specificid' => 'scalar',
                   7157:             'pcorrect' => 'scalar',
                   7158:             'pincorrect' => 'scalar');
                   7159: }
                   7160: 
1.400     www      7161: sub process_clicker {
                   7162:     my ($r)=@_;
                   7163:     my ($symb)=&get_symb($r);
                   7164:     if (!$symb) {return '';}
                   7165:     my $result=&checkforfile_js();
                   7166:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
                   7167:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
                   7168:     $result.=$table;
                   7169:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   7170:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
                   7171:     $result.='&nbsp;<b>'.&mt('Specify a file containing the clicker information for this resource').
                   7172:         '.</b></td></tr>'."\n";
                   7173:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.413     www      7174: # Attempt to restore parameters from last session, set defaults if not present
                   7175:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7176:     &Apache::loncommon::restore_course_settings('grades_clicker',
                   7177:                                                  \%Saveable_Parameters);
                   7178:     if (!$env{'form.pcorrect'}) { $env{'form.pcorrect'}=100; }
                   7179:     if (!$env{'form.pincorrect'}) { $env{'form.pincorrect'}=100; }
                   7180:     if (!$env{'form.gradingmechanism'}) { $env{'form.gradingmechanism'}='attendance'; }
                   7181:     if (!$env{'form.upfiletype'}) { $env{'form.upfiletype'}='iclicker'; }
                   7182: 
                   7183:     my %checked;
                   7184:     foreach my $gradingmechanism ('attendance','personnel','specific') {
                   7185:        if ($env{'form.gradingmechanism'} eq $gradingmechanism) {
                   7186:           $checked{$gradingmechanism}="checked='checked'";
                   7187:        }
                   7188:     }
                   7189: 
1.400     www      7190:     my $upload=&mt("Upload File");
                   7191:     my $type=&mt("Type");
1.402     www      7192:     my $attendance=&mt("Award points just for participation");
                   7193:     my $personnel=&mt("Correctness determined from response by course personnel");
1.414     www      7194:     my $specific=&mt("Correctness determined from response with clicker ID(s)"); 
1.402     www      7195:     my $pcorrect=&mt("Percentage points for correct solution");
                   7196:     my $pincorrect=&mt("Percentage points for incorrect solution");
1.413     www      7197:     my $selectform=&Apache::loncommon::select_form($env{'form.upfiletype'},'upfiletype',
1.419     www      7198: 						   ('iclicker' => 'i>clicker',
                   7199:                                                     'interwrite' => 'interwrite PRS'));
1.418     albertel 7200:     $symb = &Apache::lonenc::check_encrypt($symb);
1.400     www      7201:     $result.=<<ENDUPFORM;
1.402     www      7202: <script type="text/javascript">
                   7203: function sanitycheck() {
                   7204: // Accept only integer percentages
                   7205:    document.forms.gradesupload.pcorrect.value=Math.round(document.forms.gradesupload.pcorrect.value);
                   7206:    document.forms.gradesupload.pincorrect.value=Math.round(document.forms.gradesupload.pincorrect.value);
                   7207: // Find out grading choice
                   7208:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7209:       if (document.forms.gradesupload.gradingmechanism[i].checked) {
                   7210:          gradingchoice=document.forms.gradesupload.gradingmechanism[i].value;
                   7211:       }
                   7212:    }
                   7213: // By default, new choice equals user selection
                   7214:    newgradingchoice=gradingchoice;
                   7215: // Not good to give more points for false answers than correct ones
                   7216:    if (Math.round(document.forms.gradesupload.pcorrect.value)<Math.round(document.forms.gradesupload.pincorrect.value)) {
                   7217:       document.forms.gradesupload.pcorrect.value=document.forms.gradesupload.pincorrect.value;
                   7218:    }
                   7219: // If new choice is attendance only, and old choice was correctness-based, restore defaults
                   7220:    if ((gradingchoice=='attendance') && (document.forms.gradesupload.waschecked.value!='attendance')) {
                   7221:       document.forms.gradesupload.pcorrect.value=100;
                   7222:       document.forms.gradesupload.pincorrect.value=100;
                   7223:    }
                   7224: // If the values are different, cannot be attendance only
                   7225:    if ((Math.round(document.forms.gradesupload.pcorrect.value)!=Math.round(document.forms.gradesupload.pincorrect.value)) &&
                   7226:        (gradingchoice=='attendance')) {
                   7227:        newgradingchoice='personnel';
                   7228:    }
                   7229: // Change grading choice to new one
                   7230:    for (i=0; i<document.forms.gradesupload.gradingmechanism.length; i++) {
                   7231:       if (document.forms.gradesupload.gradingmechanism[i].value==newgradingchoice) {
                   7232:          document.forms.gradesupload.gradingmechanism[i].checked=true;
                   7233:       } else {
                   7234:          document.forms.gradesupload.gradingmechanism[i].checked=false;
                   7235:       }
                   7236:    }
                   7237: // Remember the old state
                   7238:    document.forms.gradesupload.waschecked.value=newgradingchoice;
                   7239: }
                   7240: </script>
1.400     www      7241: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   7242: <input type="hidden" name="symb" value="$symb" />
                   7243: <input type="hidden" name="command" value="processclickerfile" />
                   7244: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7245: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   7246: <input type="file" name="upfile" size="50" />
                   7247: <br /><label>$type: $selectform</label>
1.413     www      7248: <br /><label>$attendance: <input type="radio" name="gradingmechanism" value="attendance" $checked{'attendance'} onClick="sanitycheck()" /></label>
                   7249: <br /><label>$personnel: <input type="radio" name="gradingmechanism" value="personnel" $checked{'personnel'} onClick="sanitycheck()" /></label>
                   7250: <br /><label>$specific: <input type="radio" name="gradingmechanism" value="specific" $checked{'specific'} onClick="sanitycheck()" /></label>
1.414     www      7251: <input type="text" name="specificid" value="$env{'form.specificid'}" size="20" />
1.413     www      7252: <input type="hidden" name="waschecked" value="$env{'form.gradingmechanism'}" />
                   7253: <br /><label>$pcorrect: <input type="text" name="pcorrect" size="4" value="$env{'form.pcorrect'}" onChange="sanitycheck()" /></label>
                   7254: <br /><label>$pincorrect: <input type="text" name="pincorrect" size="4" value="$env{'form.pincorrect'}" onChange="sanitycheck()" /></label>
1.400     www      7255: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
                   7256: </form>
                   7257: ENDUPFORM
                   7258:     $result.='</td></tr></table>'."\n".
                   7259:              '</td></tr></table><br /><br />'."\n";
                   7260:     $result.=&show_grading_menu_form($symb);
                   7261:     return $result;
                   7262: }
                   7263: 
                   7264: sub process_clicker_file {
                   7265:     my ($r)=@_;
                   7266:     my ($symb)=&get_symb($r);
                   7267:     if (!$symb) {return '';}
1.413     www      7268: 
                   7269:     my %Saveable_Parameters=&clicker_grading_parameters();
                   7270:     &Apache::loncommon::store_course_settings('grades_clicker',
                   7271:                                               \%Saveable_Parameters);
                   7272: 
1.400     www      7273:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.404     www      7274:     if (($env{'form.gradingmechanism'} eq 'specific') && ($env{'form.specificid'}!~/\w/)) {
1.408     albertel 7275: 	$result.='<span class="LC_error">'.&mt('You need to specify a clicker ID for the correct answer').'</span>';
                   7276: 	return $result.&show_grading_menu_form($symb);
1.404     www      7277:     }
1.407     albertel 7278:     my %clicker_ids=&gather_clicker_ids();
1.408     albertel 7279:     my %correct_ids;
1.404     www      7280:     if ($env{'form.gradingmechanism'} eq 'personnel') {
1.408     albertel 7281: 	%correct_ids=&gather_adv_clicker_ids();
1.404     www      7282:     }
                   7283:     if ($env{'form.gradingmechanism'} eq 'specific') {
1.414     www      7284: 	foreach my $correct_id (split(/[\s\,]/,$env{'form.specificid'})) {;
                   7285: 	   $correct_id=~tr/a-z/A-Z/;
                   7286: 	   $correct_id=~s/\s//gs;
                   7287: 	   $correct_id=~s/^[\#0]+//;
1.421     www      7288:            $correct_id=~s/[\-\:]//g;
1.414     www      7289:            if ($correct_id) {
                   7290: 	      $correct_ids{$correct_id}='specified';
                   7291:            }
                   7292:         }
1.400     www      7293:     }
1.404     www      7294:     if ($env{'form.gradingmechanism'} eq 'attendance') {
1.408     albertel 7295: 	$result.=&mt('Score based on attendance only');
1.404     www      7296:     } else {
1.408     albertel 7297: 	my $number=0;
1.411     www      7298: 	$result.='<p><b>'.&mt('Correctness determined by the following IDs').'</b>';
1.408     albertel 7299: 	foreach my $id (sort(keys(%correct_ids))) {
1.411     www      7300: 	    $result.='<br /><tt>'.$id.'</tt> - ';
1.408     albertel 7301: 	    if ($correct_ids{$id} eq 'specified') {
                   7302: 		$result.=&mt('specified');
                   7303: 	    } else {
                   7304: 		my ($uname,$udom)=split(/\:/,$correct_ids{$id});
                   7305: 		$result.=&Apache::loncommon::plainname($uname,$udom);
                   7306: 	    }
                   7307: 	    $number++;
                   7308: 	}
1.411     www      7309:         $result.="</p>\n";
1.408     albertel 7310: 	if ($number==0) {
                   7311: 	    $result.='<span class="LC_error">'.&mt('No IDs found to determine correct answer').'</span>';
                   7312: 	    return $result.&show_grading_menu_form($symb);
                   7313: 	}
1.404     www      7314:     }
1.405     www      7315:     if (length($env{'form.upfile'}) < 2) {
1.407     albertel 7316:         $result.=&mt('[_1] Error: [_2] The file you attempted to upload, [_3] contained no information. Please check that you entered the correct filename.',
                   7317: 		     '<span class="LC_error">',
                   7318: 		     '</span>',
                   7319: 		     '<span class="LC_filename">'.&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"').'</span>');
1.405     www      7320:         return $result.&show_grading_menu_form($symb);
                   7321:     }
1.410     www      7322: 
                   7323: # Were able to get all the info needed, now analyze the file
                   7324: 
1.411     www      7325:     $result.=&Apache::loncommon::studentbrowser_javascript();
1.418     albertel 7326:     $symb = &Apache::lonenc::check_encrypt($symb);
1.410     www      7327:     my $heading=&mt('Scanning clicker file');
                   7328:     $result.=(<<ENDHEADER);
                   7329: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7330: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7331: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7332: <form method="post" action="/adm/grades" name="clickeranalysis">
                   7333: <input type="hidden" name="symb" value="$symb" />
                   7334: <input type="hidden" name="command" value="assignclickergrades" />
                   7335: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   7336: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.411     www      7337: <input type="hidden" name="gradingmechanism" value="$env{'form.gradingmechanism'}" />
                   7338: <input type="hidden" name="pcorrect" value="$env{'form.pcorrect'}" />
                   7339: <input type="hidden" name="pincorrect" value="$env{'form.pincorrect'}" />
1.410     www      7340: ENDHEADER
1.408     albertel 7341:     my %responses;
                   7342:     my @questiontitles;
1.405     www      7343:     my $errormsg='';
                   7344:     my $number=0;
                   7345:     if ($env{'form.upfiletype'} eq 'iclicker') {
1.408     albertel 7346: 	($errormsg,$number)=&iclicker_eval(\@questiontitles,\%responses);
1.406     www      7347:     }
1.419     www      7348:     if ($env{'form.upfiletype'} eq 'interwrite') {
                   7349:         ($errormsg,$number)=&interwrite_eval(\@questiontitles,\%responses);
                   7350:     }
1.411     www      7351:     $result.='<br />'.&mt('Found [_1] question(s)',$number).'<br />'.
                   7352:              '<input type="hidden" name="number" value="'.$number.'" />'.
                   7353:              &mt('Awarding [_1] percent for correct and [_2] percent for incorrect responses',
                   7354:                  $env{'form.pcorrect'},$env{'form.pincorrect'}).
                   7355:              '<br />';
1.414     www      7356: # Remember Question Titles
                   7357: # FIXME: Possibly need delimiter other than ":"
                   7358:     for (my $i=0;$i<$number;$i++) {
                   7359:         $result.='<input type="hidden" name="question:'.$i.'" value="'.
                   7360:                  &HTML::Entities::encode($questiontitles[$i],'"&<>').'" />';
                   7361:     }
1.411     www      7362:     my $correct_count=0;
                   7363:     my $student_count=0;
                   7364:     my $unknown_count=0;
1.414     www      7365: # Match answers with usernames
                   7366: # FIXME: Possibly need delimiter other than ":"
1.409     albertel 7367:     foreach my $id (keys(%responses)) {
1.410     www      7368:        if ($correct_ids{$id}) {
1.414     www      7369:           $result.="\n".'<input type="hidden" name="correct:'.$correct_count.':'.$correct_ids{$id}.'" value="'.$responses{$id}.'" />';
1.411     www      7370:           $correct_count++;
1.410     www      7371:        } elsif ($clicker_ids{$id}) {
1.437     www      7372:           if ($clicker_ids{$id}=~/\,/) {
                   7373: # More than one user with the same clicker!
                   7374:              $result.="\n<hr />".&mt('Clicker registered more than once').": <tt>".$id."</tt><br />";
                   7375:              $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7376:                            "<select name='multi".$id."'>";
                   7377:              foreach my $reguser (sort(split(/\,/,$clicker_ids{$id}))) {
                   7378:                  $result.="<option value='".$reguser."'>".&Apache::loncommon::plainname(split(/\:/,$reguser)).' ('.$reguser.')</option>';
                   7379:              }
                   7380:              $result.='</select>';
                   7381:              $unknown_count++;
                   7382:           } else {
                   7383: # Good: found one and only one user with the right clicker
                   7384:              $result.="\n".'<input type="hidden" name="student:'.$clicker_ids{$id}.'" value="'.$responses{$id}.'" />';
                   7385:              $student_count++;
                   7386:           }
1.410     www      7387:        } else {
1.411     www      7388:           $result.="\n<hr />".&mt('Unregistered Clicker')." <tt>".$id."</tt><br />";
                   7389:           $result.="\n".'<input type="hidden" name="unknown:'.$id.'" value="'.$responses{$id}.'" />'.
                   7390:                    "\n".&mt("Username").": <input type='text' name='uname".$id."' />&nbsp;".
                   7391:                    "\n".&mt("Domain").": ".
                   7392:                    &Apache::loncommon::select_dom_form($env{'course.'.$env{'request.course.id'}.'.domain'},'udom'.$id).'&nbsp;'.
                   7393:                    &Apache::loncommon::selectstudent_link('clickeranalysis','uname'.$id,'udom'.$id);
                   7394:           $unknown_count++;
1.410     www      7395:        }
1.405     www      7396:     }
1.412     www      7397:     $result.='<hr />'.
                   7398:              &mt('Found [_1] registered and [_2] unregistered clickers.',$student_count,$unknown_count);
                   7399:     if ($env{'form.gradingmechanism'} ne 'attendance') {
                   7400:        if ($correct_count==0) {
                   7401:           $errormsg.="Found no correct answers answers for grading!";
                   7402:        } elsif ($correct_count>1) {
1.414     www      7403:           $result.='<br /><span class="LC_warning">'.&mt("Found [_1] entries for grading!",$correct_count).'</span>';
1.412     www      7404:        }
                   7405:     }
1.428     www      7406:     if ($number<1) {
                   7407:        $errormsg.="Found no questions.";
                   7408:     }
1.412     www      7409:     if ($errormsg) {
                   7410:        $result.='<br /><span class="LC_error">'.&mt($errormsg).'</span>';
                   7411:     } else {
                   7412:        $result.='<br /><input type="submit" name="finalize" value="'.&mt('Finalize Grading').'" />';
                   7413:     }
                   7414:     $result.='</form></td></tr></table>'."\n".
1.410     www      7415:              '</td></tr></table><br /><br />'."\n";
1.404     www      7416:     return $result.&show_grading_menu_form($symb);
1.400     www      7417: }
                   7418: 
1.405     www      7419: sub iclicker_eval {
1.406     www      7420:     my ($questiontitles,$responses)=@_;
1.405     www      7421:     my $number=0;
                   7422:     my $errormsg='';
                   7423:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
1.410     www      7424:         my %components=&Apache::loncommon::record_sep($line);
                   7425:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.408     albertel 7426: 	if ($entries[0] eq 'Question') {
                   7427: 	    for (my $i=3;$i<$#entries;$i+=6) {
                   7428: 		$$questiontitles[$number]=$entries[$i];
                   7429: 		$number++;
                   7430: 	    }
                   7431: 	}
                   7432: 	if ($entries[0]=~/^\#/) {
                   7433: 	    my $id=$entries[0];
                   7434: 	    my @idresponses;
                   7435: 	    $id=~s/^[\#0]+//;
                   7436: 	    for (my $i=0;$i<$number;$i++) {
                   7437: 		my $idx=3+$i*6;
                   7438: 		push(@idresponses,$entries[$idx]);
                   7439: 	    }
                   7440: 	    $$responses{$id}=join(',',@idresponses);
                   7441: 	}
1.405     www      7442:     }
                   7443:     return ($errormsg,$number);
                   7444: }
                   7445: 
1.419     www      7446: sub interwrite_eval {
                   7447:     my ($questiontitles,$responses)=@_;
                   7448:     my $number=0;
                   7449:     my $errormsg='';
1.420     www      7450:     my $skipline=1;
                   7451:     my $questionnumber=0;
                   7452:     my %idresponses=();
1.419     www      7453:     foreach my $line (split(/[\n\r]/,$env{'form.upfile'})) {
                   7454:         my %components=&Apache::loncommon::record_sep($line);
                   7455:         my @entries=map {$components{$_}} (sort(keys(%components)));
1.420     www      7456:         if ($entries[1] eq 'Time') { $skipline=0; next; }
                   7457:         if ($entries[1] eq 'Response') { $skipline=1; }
                   7458:         next if $skipline;
                   7459:         if ($entries[0]!=$questionnumber) {
                   7460:            $questionnumber=$entries[0];
                   7461:            $$questiontitles[$number]=&mt('Question [_1]',$questionnumber);
                   7462:            $number++;
1.419     www      7463:         }
1.420     www      7464:         my $id=$entries[4];
                   7465:         $id=~s/^[\#0]+//;
1.421     www      7466:         $id=~s/^v\d*\://i;
                   7467:         $id=~s/[\-\:]//g;
1.420     www      7468:         $idresponses{$id}[$number]=$entries[6];
                   7469:     }
                   7470:     foreach my $id (keys %idresponses) {
                   7471:        $$responses{$id}=join(',',@{$idresponses{$id}});
                   7472:        $$responses{$id}=~s/^\s*\,//;
1.419     www      7473:     }
                   7474:     return ($errormsg,$number);
                   7475: }
                   7476: 
1.414     www      7477: sub assign_clicker_grades {
                   7478:     my ($r)=@_;
                   7479:     my ($symb)=&get_symb($r);
                   7480:     if (!$symb) {return '';}
1.416     www      7481: # See which part we are saving to
                   7482:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
                   7483: # FIXME: This should probably look for the first handgradeable part
                   7484:     my $part=$$partlist[0];
                   7485: # Start screen output
1.414     www      7486:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.416     www      7487: 
1.414     www      7488:     my $heading=&mt('Assigning grades based on clicker file');
                   7489:     $result.=(<<ENDHEADER);
                   7490: <br /><table width="100%" border="0"><tr><td bgcolor="#777777">
                   7491: <table width="100%" border="0"><tr bgcolor="#e6ffff"><td>
                   7492: <b>$heading</b></td></tr><tr bgcolor=#ffffe6><td>
                   7493: ENDHEADER
                   7494: # Get correct result
                   7495: # FIXME: Possibly need delimiter other than ":"
                   7496:     my @correct=();
1.415     www      7497:     my $gradingmechanism=$env{'form.gradingmechanism'};
                   7498:     my $number=$env{'form.number'};
                   7499:     if ($gradingmechanism ne 'attendance') {
1.414     www      7500:        foreach my $key (keys(%env)) {
                   7501:           if ($key=~/^form\.correct\:/) {
                   7502:              my @input=split(/\,/,$env{$key});
                   7503:              for (my $i=0;$i<=$#input;$i++) {
                   7504:                  if (($correct[$i]) && ($input[$i]) &&
                   7505:                      ($correct[$i] ne $input[$i])) {
                   7506:                     $result.='<br /><span class="LC_warning">'.
                   7507:                              &mt('More than one correct result given for question "[_1]": [_2] versus [_3].',
                   7508:                                  $env{'form.question:'.$i},$correct[$i],$input[$i]).'</span>';
                   7509:                  } elsif ($input[$i]) {
                   7510:                     $correct[$i]=$input[$i];
                   7511:                  }
                   7512:              }
                   7513:           }
                   7514:        }
1.415     www      7515:        for (my $i=0;$i<$number;$i++) {
1.414     www      7516:           if (!$correct[$i]) {
                   7517:              $result.='<br /><span class="LC_error">'.
                   7518:                       &mt('No correct result given for question "[_1]"!',
                   7519:                           $env{'form.question:'.$i}).'</span>';
                   7520:           }
                   7521:        }
                   7522:        $result.='<br />'.&mt("Correct answer: [_1]",join(', ',map { ($_?$_:'-') } @correct));
                   7523:     }
                   7524: # Start grading
1.415     www      7525:     my $pcorrect=$env{'form.pcorrect'};
                   7526:     my $pincorrect=$env{'form.pincorrect'};
1.416     www      7527:     my $storecount=0;
1.415     www      7528:     foreach my $key (keys(%env)) {
1.420     www      7529:        my $user='';
1.415     www      7530:        if ($key=~/^form\.student\:(.*)$/) {
1.420     www      7531:           $user=$1;
                   7532:        }
                   7533:        if ($key=~/^form\.unknown\:(.*)$/) {
                   7534:           my $id=$1;
                   7535:           if (($env{'form.uname'.$id}) && ($env{'form.udom'.$id})) {
                   7536:              $user=$env{'form.uname'.$id}.':'.$env{'form.udom'.$id};
1.437     www      7537:           } elsif ($env{'form.multi'.$id}) {
                   7538:              $user=$env{'form.multi'.$id};
1.420     www      7539:           }
                   7540:        }
                   7541:        if ($user) { 
1.415     www      7542:           my @answer=split(/\,/,$env{$key});
                   7543:           my $sum=0;
                   7544:           for (my $i=0;$i<$number;$i++) {
                   7545:              if ($answer[$i]) {
                   7546:                 if ($gradingmechanism eq 'attendance') {
                   7547:                    $sum+=$pcorrect;
                   7548:                 } else {
                   7549:                    if ($answer[$i] eq $correct[$i]) {
                   7550:                       $sum+=$pcorrect;
                   7551:                    } else {
                   7552:                       $sum+=$pincorrect;
                   7553:                    }
                   7554:                 }
                   7555:              }
                   7556:           }
1.416     www      7557:           my $ave=$sum/(100*$number);
                   7558: # Store
                   7559:           my ($username,$domain)=split(/\:/,$user);
                   7560:           my %grades=();
                   7561:           $grades{"resource.$part.solved"}='correct_by_override';
                   7562:           $grades{"resource.$part.awarded"}=$ave;
                   7563:           $grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
                   7564:           my $returncode=&Apache::lonnet::cstore(\%grades,$symb,
                   7565:                                                  $env{'request.course.id'},
                   7566:                                                  $domain,$username);
                   7567:           if ($returncode ne 'ok') {
                   7568:              $result.="<br /><span class=\"LC_error\">Failed to save student $username:$domain. Message when trying to save was ($returncode)</span>";
                   7569:           } else {
                   7570:              $storecount++;
                   7571:           }
1.415     www      7572:        }
                   7573:     }
                   7574: # We are done
1.416     www      7575:     $result.='<br />'.&mt('Successfully stored grades for [_1] student(s).',$storecount).
                   7576:              '</td></tr></table>'."\n".
1.414     www      7577:              '</td></tr></table><br /><br />'."\n";
                   7578:     return $result.&show_grading_menu_form($symb);
                   7579: }
                   7580: 
1.1       albertel 7581: sub handler {
1.41      ng       7582:     my $request=$_[0];
1.102     albertel 7583: 
1.434     albertel 7584:     &reset_caches();
1.257     albertel 7585:     if ($env{'browser.mathml'}) {
1.141     www      7586: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       7587:     } else {
1.141     www      7588: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       7589:     }
                   7590:     $request->send_http_header;
1.44      ng       7591:     return '' if $request->header_only;
1.41      ng       7592:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 7593:     my $symb=&get_symb($request,1);
1.160     albertel 7594:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   7595:     my $command=$commands[0];
                   7596:     if ($#commands > 0) {
                   7597: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   7598:     }
1.353     albertel 7599:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 7600:     if ($symb eq '' && $command eq '') {
1.257     albertel 7601: 	if ($env{'user.adv'}) {
                   7602: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   7603: 		($env{'form.codethree'})) {
                   7604: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   7605: 		    $env{'form.codethree'};
1.41      ng       7606: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   7607: 		    &Apache::lonnet::checkin($token);
                   7608: 		if ($tsymb) {
1.137     albertel 7609: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       7610: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 7611: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   7612: 					  ('grade_username' => $tuname,
                   7613: 					   'grade_domain' => $tudom,
                   7614: 					   'grade_courseid' => $tcrsid,
                   7615: 					   'grade_symb' => $tsymb)));
1.41      ng       7616: 		    } else {
1.45      ng       7617: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 7618: 		    }
1.41      ng       7619: 		} else {
1.45      ng       7620: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       7621: 		}
1.14      www      7622: 	    } else {
1.41      ng       7623: 		$request->print(&Apache::lonxml::tokeninputfield());
                   7624: 	    }
                   7625: 	}
                   7626:     } else {
1.285     albertel 7627: 	&init_perm();
1.104     albertel 7628: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 7629: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 7630: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       7631: 	    &pickStudentPage($request);
1.103     albertel 7632: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       7633: 	    &displayPage($request);
1.104     albertel 7634: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       7635: 	    &updateGradeByPage($request);
1.104     albertel 7636: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       7637: 	    &processGroup($request);
1.104     albertel 7638: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       7639: 	    $request->print(&gradingmenu($request));
1.104     albertel 7640: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       7641: 	    $request->print(&viewgrades($request));
1.104     albertel 7642: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       7643: 	    $request->print(&processHandGrade($request));
1.106     albertel 7644: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       7645: 	    $request->print(&editgrades($request));
1.106     albertel 7646: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       7647: 	    $request->print(&verifyreceipt($request));
1.400     www      7648:         } elsif ($command eq 'processclicker' && $perm{'mgr'}) {
                   7649:             $request->print(&process_clicker($request));
                   7650:         } elsif ($command eq 'processclickerfile' && $perm{'mgr'}) {
                   7651:             $request->print(&process_clicker_file($request));
1.414     www      7652:         } elsif ($command eq 'assignclickergrades' && $perm{'mgr'}) {
                   7653:             $request->print(&assign_clicker_grades($request));
1.106     albertel 7654: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       7655: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 7656: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       7657: 	    $request->print(&csvupload($request));
1.106     albertel 7658: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       7659: 	    $request->print(&csvuploadmap($request));
1.246     albertel 7660: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 7661: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 7662: 		$request->print(&csvuploadoptions($request));
1.41      ng       7663: 	    } else {
1.257     albertel 7664: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   7665: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       7666: 		} else {
1.257     albertel 7667: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       7668: 		}
                   7669: 		$request->print(&csvuploadmap($request));
                   7670: 	    }
1.246     albertel 7671: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   7672: 	    $request->print(&csvuploadassign($request));
1.106     albertel 7673: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 7674: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 7675:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   7676:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 7677: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   7678: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 7679: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 7680: 	    $request->print(&scantron_process_students($request));
1.157     albertel 7681:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 7682:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7683: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 7684:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 7685:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 7686:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   7687: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 7688:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 7689:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 7690: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 7691:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 7692: 	} elsif ($command) {
1.157     albertel 7693: 	    $request->print("Access Denied ($command)");
1.26      albertel 7694: 	}
1.2       albertel 7695:     }
1.353     albertel 7696:     $request->print(&Apache::loncommon::end_page());
1.434     albertel 7697:     &reset_caches();
1.44      ng       7698:     return '';
                   7699: }
                   7700: 
1.1       albertel 7701: 1;
                   7702: 
1.13      albertel 7703: __END__;

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