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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.382   ! albertel    4: # $Id: grades.pm,v 1.381 2006/10/23 22:32:09 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.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.170     albertel   42: use String::Similarity;
1.359     www        43: use lib '/home/httpd/lib/perl';
                     44: use LONCAPA;
                     45: 
1.315     bowersj2   46: use POSIX qw(floor);
1.87      www        47: 
                     48: my %oldessays=();
1.103     albertel   49: my %perm=();
1.1       albertel   50: 
1.68      ng         51: # ----- These first few routines are general use routines.----
1.44      ng         52: #
1.146     albertel   53: # --- Retrieve the parts from the metadata file.---
1.44      ng         54: sub getpartlist {
1.324     albertel   55:     my ($symb) = @_;
                     56:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.146     albertel   57:     my $partorder = &Apache::lonnet::metadata($url, 'partorder');
                     58:     my @parts;
                     59:     if ($partorder) {
                     60: 	for my $part (split (/,/,$partorder)) {
                     61: 	    if (!&Apache::loncommon::check_if_partid_hidden($part,$symb)) {
                     62: 		push(@parts, $part);
                     63: 	    }
                     64: 	}	    
                     65:     } else {
                     66: 	my $metadata = &Apache::lonnet::metadata($url, 'packages');
                     67: 	foreach (split(/\,/,$metadata)) {
                     68: 	    if ($_ =~ /^part_(.*)$/) {
                     69: 		if (!&Apache::loncommon::check_if_partid_hidden($1,$symb)) {
                     70: 		    push(@parts, $1);
                     71: 		}
                     72: 	    }
1.41      ng         73: 	}
1.16      albertel   74:     }
1.146     albertel   75:     my @stores;
                     76:     foreach my $part (@parts) {
                     77: 	my (@metakeys) = split(/,/,&Apache::lonnet::metadata($url,'keys'));
                     78: 	foreach my $key (@metakeys) {
                     79: 	    if ($key =~ m/^stores_\Q$part\E_/) { push(@stores,$key); }
                     80: 	}
                     81:     }
                     82:     return @stores;
1.2       albertel   83: }
                     84: 
1.44      ng         85: # --- Get the symbolic name of a problem and the url
1.324     albertel   86: sub get_symb {
1.173     albertel   87:     my ($request,$silent) = @_;
1.257     albertel   88:     (my $url=$env{'form.url'}) =~ s-^http://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
                     89:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
1.173     albertel   90:     if ($symb eq '') { 
                     91: 	if (!$silent) {
                     92: 	    $request->print("Unable to handle ambiguous references:$url:.");
                     93: 	    return ();
                     94: 	}
                     95:     }
1.324     albertel   96:     return ($symb);
1.32      ng         97: }
                     98: 
1.129     ng         99: #--- Format fullname, username:domain if different for display
                    100: #--- Use anywhere where the student names are listed
                    101: sub nameUserString {
                    102:     my ($type,$fullname,$uname,$udom) = @_;
                    103:     if ($type eq 'header') {
1.250     albertel  104: 	return '<b>&nbsp;Fullname&nbsp;</b><font color="#999999">(Username)</font>';
1.129     ng        105:     } else {
                    106: 	return '&nbsp;'.$fullname.'<font color="#999999">&nbsp;('.$uname.
1.257     albertel  107: 	    ($env{'user.domain'} eq $udom ? '' : ' ('.$udom.')').')</font>';
1.129     ng        108:     }
                    109: }
                    110: 
1.44      ng        111: #--- Get the partlist and the response type for a given problem. ---
                    112: #--- Indicate if a response type is coded handgraded or not. ---
1.39      ng        113: sub response_type {
1.324     albertel  114:     my ($symb) = shift;
1.377     albertel  115: 
                    116:     my $navmap = Apache::lonnavmaps::navmap->new();
                    117:     my $res = $navmap->getBySymb($symb);
                    118:     my $partlist = $res->parts();
                    119:     my (%response_types,%handgrade);
                    120:     foreach my $part (@{ $partlist }) {
                    121: 	my @types = $res->responseType($part);
                    122: 	my @ids = $res->responseIds($part);
                    123: 	for (my $i=0; $i < scalar(@ids); $i++) {
                    124: 	    $response_types{$part}{$ids[$i]} = $types[$i];
                    125: 	    $handgrade{$part.'_'.$ids[$i]} = 
                    126: 		&Apache::lonnet::EXT('resource.'.$part.'_'.$ids[$i].
                    127: 				     '.handgrade',$symb);
1.41      ng        128: 	}
                    129:     }
1.377     albertel  130:     return ($partlist,\%handgrade,\%response_types);
1.39      ng        131: }
                    132: 
1.375     albertel  133: sub flatten_responseType {
                    134:     my ($responseType) = @_;
                    135:     my @part_response_id =
                    136: 	map { 
                    137: 	    my $part = $_;
                    138: 	    map {
                    139: 		[$part,$_]
                    140: 		} sort(keys(%{ $responseType->{$part} }));
                    141: 	} sort(keys(%$responseType));
                    142:     return @part_response_id;
                    143: }
                    144: 
1.207     albertel  145: sub get_display_part {
1.324     albertel  146:     my ($partID,$symb)=@_;
1.207     albertel  147:     my $display=&Apache::lonnet::EXT('resource.'.$partID.'.display',$symb);
                    148:     if (defined($display) and $display ne '') {
                    149: 	$display.= " (<font color=\"#999900\">id $partID</font>)";
                    150:     } else {
                    151: 	$display=$partID;
                    152:     }
                    153:     return $display;
                    154: }
1.269     raeburn   155: 
1.118     ng        156: #--- Show resource title
                    157: #--- and parts and response type
                    158: sub showResourceInfo {
1.324     albertel  159:     my ($symb,$probTitle,$checkboxes) = @_;
1.154     albertel  160:     my $col=3;
                    161:     if ($checkboxes) { $col=4; }
1.118     ng        162:     my $result ='<table border="0">'.
1.167     sakharuk  163: 	'<tr><td colspan="'.$col.'"><font size="+1"><b>'.&mt('Current Resource').': </b>'.
1.154     albertel  164: 	$probTitle.'</font></td></tr>'."\n";
1.324     albertel  165:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.126     ng        166:     my %resptype = ();
1.122     ng        167:     my $hdgrade='no';
1.154     albertel  168:     my %partsseen;
1.375     albertel  169:     foreach my $partID (sort keys(%$responseType)) {
                    170: 	foreach my $resID (sort keys(%{ $responseType->{$partID} })) {
                    171: 	    my $handgrade=$$handgrade{$partID.'_'.$resID};
                    172: 	    my $responsetype = $responseType->{$partID}->{$resID};
                    173: 	    $hdgrade = $handgrade if ($handgrade eq 'yes');
                    174: 	    $result.='<tr>';
                    175: 	    if ($checkboxes) {
                    176: 		if (exists($partsseen{$partID})) {
                    177: 		    $result.="<td>&nbsp;</td>";
                    178: 		} else {
                    179: 		    $result.="<td><input type='checkbox' name='vPart' value='$partID' checked='on' /></td>";
                    180: 		}
                    181: 		$partsseen{$partID}=1;
1.154     albertel  182: 	    }
1.375     albertel  183: 	    my $display_part=&get_display_part($partID,$symb);
                    184: 	    $result.='<td><b>Part: </b>'.$display_part.' <font color="#999999">'.
                    185: 		$resID.'</font></td>'.
                    186: 		'<td><b>Type: </b>'.$responsetype.'</td></tr>';
                    187: #	    '<td><b>Handgrade: </b>'.$handgrade.'</td></tr>';
1.154     albertel  188: 	}
1.118     ng        189:     }
                    190:     $result.='</table>'."\n";
1.147     albertel  191:     return $result,$responseType,$hdgrade,$partlist,$handgrade;
1.118     ng        192: }
                    193: 
1.148     albertel  194: 
                    195: sub get_order {
                    196:     my ($partid,$respid,$symb,$uname,$udom)=@_;
                    197:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
                    198:     $url=&Apache::lonnet::clutter($url);
                    199:     my $subresult=&Apache::lonnet::ssi($url,
                    200: 				       ('grade_target' => 'analyze'),
                    201: 				       ('grade_domain' => $udom),
                    202: 				       ('grade_symb' => $symb),
                    203: 				       ('grade_courseid' => 
1.257     albertel  204: 					        $env{'request.course.id'}),
1.148     albertel  205: 				       ('grade_username' => $uname));
1.149     albertel  206:     (undef,$subresult)=split(/_HASH_REF__/,$subresult,2);
1.148     albertel  207:     my %analyze=&Apache::lonnet::str2hash($subresult);
                    208:     return ($analyze{"$partid.$respid.shown"});
                    209: }
1.118     ng        210: #--- Clean response type for display
1.335     albertel  211: #--- Currently filters option/rank/radiobutton/match/essay/Task
                    212: #        response types only.
1.118     ng        213: sub cleanRecord {
1.336     albertel  214:     my ($answer,$response,$symb,$partid,$respid,$record,$order,$version,
                    215: 	$uname,$udom) = @_;
1.148     albertel  216:     my $grayFont = '<font color="#999999">';
                    217:     if ($response =~ /^(option|rank)$/) {
                    218: 	my %answer=&Apache::lonnet::str2hash($answer);
                    219: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    220: 	my ($toprow,$bottomrow);
                    221: 	foreach my $foil (@$order) {
                    222: 	    if ($grading{$foil} == 1) {
                    223: 		$toprow.='<td><b>'.$answer{$foil}.'&nbsp;</b></td>';
                    224: 	    } else {
                    225: 		$toprow.='<td><i>'.$answer{$foil}.'&nbsp;</i></td>';
                    226: 	    }
                    227: 	    $bottomrow.='<td>'.$grayFont.$foil.'</font>&nbsp;</td>';
                    228: 	}
                    229: 	return '<blockquote><table border="1">'.
                    230: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
                    231: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</font></td>'.
                    232: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    233:     } elsif ($response eq 'match') {
                    234: 	my %answer=&Apache::lonnet::str2hash($answer);
                    235: 	my %grading=&Apache::lonnet::str2hash($record->{$version."resource.$partid.$respid.submissiongrading"});
                    236: 	my @items=&Apache::lonnet::str2array($record->{$version."resource.$partid.$respid.submissionitems"});
                    237: 	my ($toprow,$middlerow,$bottomrow);
                    238: 	foreach my $foil (@$order) {
                    239: 	    my $item=shift(@items);
                    240: 	    if ($grading{$foil} == 1) {
                    241: 		$toprow.='<td><b>'.$item.'&nbsp;</b></td>';
                    242: 		$middlerow.='<td><b>'.$grayFont.$answer{$foil}.'&nbsp;</font></b></td>';
                    243: 	    } else {
                    244: 		$toprow.='<td><i>'.$item.'&nbsp;</i></td>';
                    245: 		$middlerow.='<td><i>'.$grayFont.$answer{$foil}.'&nbsp;</font></i></td>';
                    246: 	    }
                    247: 	    $bottomrow.='<td>'.$grayFont.$foil.'</font>&nbsp;</td>';
1.118     ng        248: 	}
1.126     ng        249: 	return '<blockquote><table border="1">'.
1.148     albertel  250: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
                    251: 	    '<tr valign="top"><td>'.$grayFont.'Item ID</font></td>'.
                    252: 	    $middlerow.'</tr>'.
                    253: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</font></td>'.
                    254: 	    $bottomrow.'</tr>'.'</table></blockquote>';
                    255:     } elsif ($response eq 'radiobutton') {
                    256: 	my %answer=&Apache::lonnet::str2hash($answer);
                    257: 	my ($toprow,$bottomrow);
                    258: 	my $correct=($order->[0])+1;
                    259: 	for (my $i=1;$i<=$#$order;$i++) {
                    260: 	    my $foil=$order->[$i];
                    261: 	    if (exists($answer{$foil})) {
                    262: 		if ($i == $correct) {
                    263: 		    $toprow.='<td><b>true</b></td>';
                    264: 		} else {
                    265: 		    $toprow.='<td><i>true</i></td>';
                    266: 		}
                    267: 	    } else {
                    268: 		$toprow.='<td>false</td>';
                    269: 	    }
                    270: 	    $bottomrow.='<td>'.$grayFont.$foil.'</font>&nbsp;</td>';
                    271: 	}
                    272: 	return '<blockquote><table border="1">'.
                    273: 	    '<tr valign="top"><td>Answer</td>'.$toprow.'</tr>'.
                    274: 	    '<tr valign="top"><td>'.$grayFont.'Option ID</font></td>'.
                    275: 	    $grayFont.$bottomrow.'</tr>'.'</table></blockquote>';
                    276:     } elsif ($response eq 'essay') {
1.257     albertel  277: 	if (! exists ($env{'form.'.$symb})) {
1.122     ng        278: 	    my (%keyhash) = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel  279: 						  $env{'course.'.$env{'request.course.id'}.'.domain'},
                    280: 						  $env{'course.'.$env{'request.course.id'}.'.num'});
1.122     ng        281: 
1.257     albertel  282: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                    283: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                    284: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                    285: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                    286: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                    287: 	    $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        288: 	}
1.166     albertel  289: 	$answer =~ s-\n-<br />-g;
                    290: 	return '<br /><br /><blockquote><tt>'.&keywords_highlight($answer).'</tt></blockquote>';
1.268     albertel  291:     } elsif ( $response eq 'organic') {
                    292: 	my $result='Smile representation: "<tt>'.$answer.'</tt>"';
                    293: 	my $jme=$record->{$version."resource.$partid.$respid.molecule"};
                    294: 	$result.=&Apache::chemresponse::jme_img($jme,$answer,400);
                    295: 	return $result;
1.335     albertel  296:     } elsif ( $response eq 'Task') {
                    297: 	if ( $answer eq 'SUBMITTED') {
                    298: 	    my $files = $record->{$version."resource.$respid.$partid.bridgetask.portfiles"};
1.336     albertel  299: 	    my $result = &Apache::bridgetask::file_list($files,$uname,$udom);
1.335     albertel  300: 	    return $result;
                    301: 	} elsif ( grep(/^\Q$version\E.*?\.instance$/, keys(%{$record})) ) {
                    302: 	    my @matches = grep(/^\Q$version\E.*?\.instance$/,
                    303: 			       keys(%{$record}));
                    304: 	    return join('<br />',($version,@matches));
                    305: 			       
                    306: 			       
                    307: 	} else {
                    308: 	    my $result =
                    309: 		'<p>'
                    310: 		.&mt('Overall result: [_1]',
                    311: 		     $record->{$version."resource.$respid.$partid.status"})
                    312: 		.'</p>';
                    313: 	    
                    314: 	    $result .= '<ul>';
                    315: 	    my @grade = grep(/^\Q${version}resource.$respid.$partid.\E[^.]*[.]status$/,
                    316: 			     keys(%{$record}));
                    317: 	    foreach my $grade (sort(@grade)) {
                    318: 		my ($dim) = ($grade =~/[.]([^.]+)[.]status$/);
                    319: 		$result.= '<li>'.&mt("Dimension: [_1], status [_2] ",
                    320: 				     $dim, $record->{$grade}).
                    321: 			  '</li>';
                    322: 	    }
                    323: 	    $result.='</ul>';
                    324: 	    return $result;
                    325: 	}
                    326:        
1.122     ng        327:     }
1.118     ng        328:     return $answer;
                    329: }
                    330: 
                    331: #-- A couple of common js functions
                    332: sub commonJSfunctions {
                    333:     my $request = shift;
                    334:     $request->print(<<COMMONJSFUNCTIONS);
                    335: <script type="text/javascript" language="javascript">
                    336:     function radioSelection(radioButton) {
                    337: 	var selection=null;
                    338: 	if (radioButton.length > 1) {
                    339: 	    for (var i=0; i<radioButton.length; i++) {
                    340: 		if (radioButton[i].checked) {
                    341: 		    return radioButton[i].value;
                    342: 		}
                    343: 	    }
                    344: 	} else {
                    345: 	    if (radioButton.checked) return radioButton.value;
                    346: 	}
                    347: 	return selection;
                    348:     }
                    349: 
                    350:     function pullDownSelection(selectOne) {
                    351: 	var selection="";
                    352: 	if (selectOne.length > 1) {
                    353: 	    for (var i=0; i<selectOne.length; i++) {
                    354: 		if (selectOne[i].selected) {
                    355: 		    return selectOne[i].value;
                    356: 		}
                    357: 	    }
                    358: 	} else {
1.138     albertel  359:             // only one value it must be the selected one
                    360: 	    return selectOne.value;
1.118     ng        361: 	}
                    362:     }
                    363: </script>
                    364: COMMONJSFUNCTIONS
                    365: }
                    366: 
1.44      ng        367: #--- Dumps the class list with usernames,list of sections,
                    368: #--- section, ids and fullnames for each user.
                    369: sub getclasslist {
1.76      ng        370:     my ($getsec,$filterlist) = @_;
1.291     albertel  371:     my @getsec;
                    372:     if (!ref($getsec)) {
                    373: 	if ($getsec ne '' && $getsec ne 'all') {
                    374: 	    @getsec=($getsec);
                    375: 	}
                    376:     } else {
                    377: 	@getsec=@{$getsec};
                    378:     }
                    379:     if (grep(/^all$/,@getsec)) { undef(@getsec); }
                    380: 
1.56      matthew   381:     my $classlist=&Apache::loncoursedata::get_classlist();
1.49      albertel  382:     # Bail out if we were unable to get the classlist
1.56      matthew   383:     return if (! defined($classlist));
                    384:     #
                    385:     my %sections;
                    386:     my %fullnames;
1.205     matthew   387:     foreach my $student (keys(%$classlist)) {
                    388:         my $end      = 
                    389:             $classlist->{$student}->[&Apache::loncoursedata::CL_END()];
                    390:         my $start    = 
                    391:             $classlist->{$student}->[&Apache::loncoursedata::CL_START()];
                    392:         my $id       = 
                    393:             $classlist->{$student}->[&Apache::loncoursedata::CL_ID()];
                    394:         my $section  = 
                    395:             $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    396:         my $fullname = 
                    397:             $classlist->{$student}->[&Apache::loncoursedata::CL_FULLNAME()];
                    398:         my $status   = 
                    399:             $classlist->{$student}->[&Apache::loncoursedata::CL_STATUS()];
1.76      ng        400: 	# filter students according to status selected
1.257     albertel  401: 	if ($filterlist && $env{'form.Status'} ne 'Any') {
                    402: 	    if ($env{'form.Status'} ne $status) {
1.205     matthew   403: 		delete ($classlist->{$student});
1.76      ng        404: 		next;
                    405: 	    }
                    406: 	}
1.205     matthew   407: 	$section = ($section ne '' ? $section : 'none');
1.106     albertel  408: 	if (&canview($section)) {
1.291     albertel  409: 	    if (!@getsec || grep(/^\Q$section\E$/,@getsec)) {
1.103     albertel  410: 		$sections{$section}++;
1.205     matthew   411: 		$fullnames{$student}=$fullname;
1.103     albertel  412: 	    } else {
1.205     matthew   413: 		delete($classlist->{$student});
1.103     albertel  414: 	    }
                    415: 	} else {
1.205     matthew   416: 	    delete($classlist->{$student});
1.103     albertel  417: 	}
1.44      ng        418:     }
                    419:     my %seen = ();
1.56      matthew   420:     my @sections = sort(keys(%sections));
                    421:     return ($classlist,\@sections,\%fullnames);
1.44      ng        422: }
                    423: 
1.103     albertel  424: sub canmodify {
                    425:     my ($sec)=@_;
                    426:     if ($perm{'mgr'}) {
                    427: 	if (!defined($perm{'mgr_section'})) {
                    428: 	    # can modify whole class
                    429: 	    return 1;
                    430: 	} else {
                    431: 	    if ($sec eq $perm{'mgr_section'}) {
                    432: 		#can modify the requested section
                    433: 		return 1;
                    434: 	    } else {
                    435: 		# can't modify the request section
                    436: 		return 0;
                    437: 	    }
                    438: 	}
                    439:     }
                    440:     #can't modify
                    441:     return 0;
                    442: }
                    443: 
                    444: sub canview {
                    445:     my ($sec)=@_;
                    446:     if ($perm{'vgr'}) {
                    447: 	if (!defined($perm{'vgr_section'})) {
                    448: 	    # can modify whole class
                    449: 	    return 1;
                    450: 	} else {
                    451: 	    if ($sec eq $perm{'vgr_section'}) {
                    452: 		#can modify the requested section
                    453: 		return 1;
                    454: 	    } else {
                    455: 		# can't modify the request section
                    456: 		return 0;
                    457: 	    }
                    458: 	}
                    459:     }
                    460:     #can't modify
                    461:     return 0;
                    462: }
                    463: 
1.44      ng        464: #--- Retrieve the grade status of a student for all the parts
                    465: sub student_gradeStatus {
1.324     albertel  466:     my ($symb,$udom,$uname,$partlist) = @_;
1.257     albertel  467:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.44      ng        468:     my %partstatus = ();
                    469:     foreach (@$partlist) {
1.128     ng        470: 	my ($status,undef)   = split(/_/,$record{"resource.$_.solved"},2);
1.44      ng        471: 	$status              = 'nothing' if ($status eq '');
                    472: 	$partstatus{$_}      = $status;
                    473: 	my $subkey           = "resource.$_.submitted_by";
                    474: 	$partstatus{$subkey} = $record{$subkey} if ($record{$subkey} ne '');
                    475:     }
                    476:     return %partstatus;
                    477: }
                    478: 
1.45      ng        479: # hidden form and javascript that calls the form
                    480: # Use by verifyscript and viewgrades
                    481: # Shows a student's view of problem and submission
                    482: sub jscriptNform {
1.324     albertel  483:     my ($symb) = @_;
1.45      ng        484:     my $jscript='<script type="text/javascript" language="javascript">'."\n".
                    485: 	'    function viewOneStudent(user,domain) {'."\n".
                    486: 	'	document.onestudent.student.value = user;'."\n".
                    487: 	'	document.onestudent.userdom.value = domain;'."\n".
                    488: 	'	document.onestudent.submit();'."\n".
                    489: 	'    }'."\n".
                    490: 	'</script>'."\n";
                    491:     $jscript.= '<form action="/adm/grades" method="post" name="onestudent">'."\n".
                    492: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel  493: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                    494: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n".
                    495: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.45      ng        496: 	'<input type="hidden" name="command" value="submission" />'."\n".
                    497: 	'<input type="hidden" name="student" value="" />'."\n".
                    498: 	'<input type="hidden" name="userdom" value="" />'."\n".
                    499: 	'</form>'."\n";
                    500:     return $jscript;
                    501: }
1.39      ng        502: 
1.315     bowersj2  503: # Given the score (as a number [0-1] and the weight) what is the final
                    504: # point value? This function will round to the nearest tenth, third,
                    505: # or quarter if one of those is within the tolerance of .00001.
1.316     albertel  506: sub compute_points {
1.315     bowersj2  507:     my ($score, $weight) = @_;
                    508:     
                    509:     my $tolerance = .00001;
                    510:     my $points = $score * $weight;
                    511: 
                    512:     # Check for nearness to 1/x.
                    513:     my $check_for_nearness = sub {
                    514:         my ($factor) = @_;
                    515:         my $num = ($points * $factor) + $tolerance;
                    516:         my $floored_num = floor($num);
1.316     albertel  517:         if ($num - $floored_num < 2 * $tolerance * $factor) {
1.315     bowersj2  518:             return $floored_num / $factor;
                    519:         }
                    520:         return $points;
                    521:     };
                    522: 
                    523:     $points = $check_for_nearness->(10);
                    524:     $points = $check_for_nearness->(3);
                    525:     $points = $check_for_nearness->(4);
                    526:     
                    527:     return $points;
                    528: }
                    529: 
1.44      ng        530: #------------------ End of general use routines --------------------
1.87      www       531: 
                    532: #
                    533: # Find most similar essay
                    534: #
                    535: 
                    536: sub most_similar {
                    537:     my ($uname,$udom,$uessay)=@_;
                    538: 
                    539: # ignore spaces and punctuation
                    540: 
                    541:     $uessay=~s/\W+/ /gs;
                    542: 
1.282     www       543: # ignore empty submissions (occuring when only files are sent)
                    544: 
                    545:     unless ($uessay=~/\w+/) { return ''; }
                    546: 
1.87      www       547: # these will be returned. Do not care if not at least 50 percent similar
1.88      www       548:     my $limit=0.6;
1.87      www       549:     my $sname='';
                    550:     my $sdom='';
                    551:     my $scrsid='';
                    552:     my $sessay='';
                    553: # go through all essays ...
                    554:     foreach my $tkey (keys %oldessays) {
                    555: 	my ($tname,$tdom,$tcrsid)=split(/\./,$tkey);
                    556: # ... except the same student
1.88      www       557:         if (($tname ne $uname) || ($tdom ne $udom)) {
1.87      www       558: 	    my $tessay=$oldessays{$tkey};
                    559:             $tessay=~s/\W+/ /gs;
                    560: # String similarity gives up if not even limit
1.88      www       561:             my $tsimilar=&String::Similarity::similarity($uessay,$tessay,$limit);
1.87      www       562: # Found one
                    563:             if ($tsimilar>$limit) {
                    564: 		$limit=$tsimilar;
                    565:                 $sname=$tname;
1.88      www       566:                 $sdom=$tdom;
1.87      www       567:                 $scrsid=$tcrsid;
                    568:                 $sessay=$oldessays{$tkey};
                    569:             }
                    570:         } 
                    571:     }
1.88      www       572:     if ($limit>0.6) {
1.87      www       573:        return ($sname,$sdom,$scrsid,$sessay,$limit);
                    574:     } else {
                    575:        return ('','','','',0);
                    576:     }
                    577: }
                    578: 
1.44      ng        579: #-------------------------------------------------------------------
                    580: 
                    581: #------------------------------------ Receipt Verification Routines
1.45      ng        582: #
1.44      ng        583: #--- Check whether a receipt number is valid.---
                    584: sub verifyreceipt {
                    585:     my $request  = shift;
                    586: 
1.257     albertel  587:     my $courseid = $env{'request.course.id'};
1.184     www       588:     my $receipt  = &Apache::lonnet::recprefix($courseid).'-'.
1.257     albertel  589: 	$env{'form.receipt'};
1.44      ng        590:     $receipt     =~ s/[^\-\d]//g;
1.378     albertel  591:     my ($symb)   = &get_symb($request);
1.44      ng        592: 
1.45      ng        593:     my $title.='<h3><font color="#339933">Verifying Submission Receipt '.
                    594: 	$receipt.'</h3></font>'."\n".
1.326     albertel  595: 	'<font size=+1><b>Resource: </b>'.$env{'form.probTitle'}.'</font><br /><br />'."\n";
1.44      ng        596: 
                    597:     my ($string,$contents,$matches) = ('','',0);
1.56      matthew   598:     my (undef,undef,$fullname) = &getclasslist('all','0');
1.177     albertel  599:     
                    600:     my $receiptparts=0;
1.257     albertel  601:     if ($env{"course.$courseid.receiptalg"} eq 'receipt2') { $receiptparts=1; }
1.177     albertel  602:     my $parts=['0'];
1.324     albertel  603:     if ($receiptparts) { ($parts)=&response_type($symb); }
1.294     albertel  604:     foreach (sort 
                    605: 	     {
                    606: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    607: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    608: 		 }
                    609: 		 return $a cmp $b;
                    610: 	     } (keys(%$fullname))) {
1.44      ng        611: 	my ($uname,$udom)=split(/\:/);
1.177     albertel  612: 	foreach my $part (@$parts) {
                    613: 	    if ($receipt eq &Apache::lonnet::ireceipt($uname,$udom,$courseid,$symb,$part)) {
                    614: 		$contents.='<tr bgcolor="#ffffe6"><td>&nbsp;'."\n".
                    615: 		    '<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
                    616: 		    '\')"; TARGET=_self>'.$$fullname{$_}.'</a>&nbsp;</td>'."\n".
                    617: 		    '<td>&nbsp;'.$uname.'&nbsp;</td>'.
                    618: 		    '<td>&nbsp;'.$udom.'&nbsp;</td>';
                    619: 		if ($receiptparts) {
                    620: 		    $contents.='<td>&nbsp;'.$part.'&nbsp;</td>';
                    621: 		}
                    622: 		$contents.='</tr>'."\n";
                    623: 		
                    624: 		$matches++;
                    625: 	    }
1.44      ng        626: 	}
                    627:     }
                    628:     if ($matches == 0) {
                    629: 	$string = $title.'No match found for the above receipt.';
                    630:     } else {
1.324     albertel  631: 	$string = &jscriptNform($symb).$title.
1.44      ng        632: 	    'The above receipt matches the following student'.
                    633: 	    ($matches <= 1 ? '.' : 's.')."\n".
                    634: 	    '<table border="0"><tr><td bgcolor="#777777">'."\n".
                    635: 	    '<table border="0"><tr bgcolor="#e6ffff">'."\n".
                    636: 	    '<td><b>&nbsp;Fullname&nbsp;</b></td>'."\n".
                    637: 	    '<td><b>&nbsp;Username&nbsp;</b></td>'."\n".
1.177     albertel  638: 	    '<td><b>&nbsp;Domain&nbsp;</b></td>';
                    639: 	if ($receiptparts) {
                    640: 	    $string.='<td>&nbsp;Problem Part&nbsp;</td>';
                    641: 	}
                    642: 	$string.='</tr>'."\n".$contents.
1.44      ng        643: 	    '</table></td></tr></table>'."\n";
                    644:     }
1.324     albertel  645:     return $string.&show_grading_menu_form($symb);
1.44      ng        646: }
                    647: 
                    648: #--- This is called by a number of programs.
                    649: #--- Called from the Grading Menu - View/Grade an individual student
                    650: #--- Also called directly when one clicks on the subm button 
                    651: #    on the problem page.
1.30      ng        652: sub listStudents {
1.41      ng        653:     my ($request) = shift;
1.49      albertel  654: 
1.324     albertel  655:     my ($symb) = &get_symb($request);
1.257     albertel  656:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                    657:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                    658:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                    659:     my $submitonly= $env{'form.submitonly'} eq '' ? 'all' : $env{'form.submitonly'};
                    660: 
                    661:     my $viewgrade = $env{'form.showgrading'} eq 'yes' ? 'View/Grade/Regrade' : 'View';
                    662:     $env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                    663: 	&Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.49      albertel  664: 
1.118     ng        665:     my $result='<h3><font color="#339933">&nbsp;'.$viewgrade.
                    666: 	' Submissions for a Student or a Group of Students</font></h3>';
                    667: 
1.324     albertel  668:     my ($table,undef,$hdgrade,$partlist,$handgrade) = &showResourceInfo($symb,$env{'form.probTitle'},($env{'form.showgrading'} eq 'yes'));
1.49      albertel  669: 
1.45      ng        670:     $request->print(<<LISTJAVASCRIPT);
                    671: <script type="text/javascript" language="javascript">
1.110     ng        672:     function checkSelect(checkBox) {
                    673: 	var ctr=0;
                    674: 	var sense="";
                    675: 	if (checkBox.length > 1) {
                    676: 	    for (var i=0; i<checkBox.length; i++) {
                    677: 		if (checkBox[i].checked) {
                    678: 		    ctr++;
                    679: 		}
                    680: 	    }
                    681: 	    sense = "a student or group of students";
                    682: 	} else {
                    683: 	    if (checkBox.checked) {
                    684: 		ctr = 1;
                    685: 	    }
                    686: 	    sense = "the student";
                    687: 	}
                    688: 	if (ctr == 0) {
1.126     ng        689: 	    alert("Please select "+sense+" before clicking on the Next button.");
1.110     ng        690: 	    return false;
                    691: 	}
                    692: 	document.gradesub.submit();
                    693:     }
                    694: 
                    695:     function reLoadList(formname) {
1.112     ng        696: 	if (formname.saveStatusOld.value == pullDownSelection(formname.Status)) {return;}
1.110     ng        697: 	formname.command.value = 'submission';
                    698: 	formname.submit();
                    699:     }
1.45      ng        700: </script>
                    701: LISTJAVASCRIPT
                    702: 
1.118     ng        703:     &commonJSfunctions($request);
1.41      ng        704:     $request->print($result);
1.39      ng        705: 
1.257     albertel  706:     my $checkhdgrade = ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1 ) ? 'checked' : '';
1.119     ng        707:     my $checklastsub = $checkhdgrade eq '' ? 'checked' : '';
1.154     albertel  708:     my $gradeTable='<form action="/adm/grades" method="post" name="gradesub">'.
                    709: 	"\n".$table.
1.267     albertel  710: 	'&nbsp;<b>View Problem Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                    711: 	'<label><input type="radio" name="vProb" value="yes" /> one student </label>'."\n".
                    712: 	'<label><input type="radio" name="vProb" value="all" /> all students </label><br />'."\n".
                    713: 	'&nbsp;<b>View Answer: </b><label><input type="radio" name="vAns" value="no"  /> no </label>'."\n".
                    714: 	'<label><input type="radio" name="vAns" value="yes" /> one student </label>'."\n".
                    715: 	'<label><input type="radio" name="vAns" value="all" checked="on" /> all students </label><br />'."\n".
1.49      albertel  716: 	'&nbsp;<b>Submissions: </b>'."\n";
1.257     albertel  717:     if ($env{'form.handgrade'} eq 'yes' && scalar(@$partlist) > 1) {
1.267     albertel  718: 	$gradeTable.='<label><input type="radio" name="lastSub" value="hdgrade" '.$checkhdgrade.' /> essay part only </label>'."\n";
1.49      albertel  719:     }
1.110     ng        720: 
1.257     albertel  721:     my $saveStatus = $env{'form.Status'} eq '' ? 'Active' : $env{'form.Status'};
                    722:     $env{'form.Status'} = $saveStatus;
1.110     ng        723: 
1.267     albertel  724:     $gradeTable.='<label><input type="radio" name="lastSub" value="lastonly" '.$checklastsub.' /> last submission only </label>'."\n".
                    725: 	'<label><input type="radio" name="lastSub" value="last" /> last submission & parts info </label>'."\n".
                    726: 	'<label><input type="radio" name="lastSub" value="datesub" /> by dates and submissions </label>'."\n".
1.348     bowersj2  727: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label><br />'."\n".
                    728:         '&nbsp;<b>Grading Increments:</b> <select name="increment">'.
                    729:         '<option value="1">Whole Points</option>'.
                    730:         '<option value=".5">Half Points</option>'.
1.349     albertel  731:         '<option value=".25">Quarter Points</option>'.
                    732:         '<option value=".1">Tenths of a Point</option>'.
1.348     bowersj2  733:         '</select>'.
                    734: 
1.45      ng        735: 	'<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
                    736: 	'<input type="hidden" name="submitonly"  value="'.$submitonly.'" />'."\n".
1.257     albertel  737: 	'<input type="hidden" name="handgrade"   value="'.$env{'form.handgrade'}.'" /><br />'."\n".
                    738: 	'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" /><br />'."\n".
                    739: 	'<input type="hidden" name="saveState"   value="'.$env{'form.saveState'}.'" />'."\n".
                    740: 	'<input type="hidden" name="probTitle"   value="'.$env{'form.probTitle'}.'" />'."\n".
1.48      albertel  741: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.110     ng        742: 	'<input type="hidden" name="saveStatusOld" value="'.$saveStatus.'" />'."\n";
                    743: 
1.257     albertel  744:     if (exists($env{'form.gradingMenu'}) && exists($env{'form.Status'})) {
                    745: 	$gradeTable.='<input type="hidden" name="Status"   value="'.$env{'form.Status'}.'" />'."\n";
1.124     ng        746:     } else {
                    747: 	$gradeTable.='<b>Student Status:</b> '.
                    748: 	    &Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,'javascript:reLoadList(this.form);').'<br />';
                    749:     }
1.112     ng        750: 
1.126     ng        751:     $gradeTable.='To '.lc($viewgrade).' a submission or a group of submissions, click on the check box(es) '.
                    752: 	'next to the student\'s name(s). Then click on the Next button.<br />'."\n".
1.110     ng        753: 	'<input type="hidden" name="command" value="processGroup" />'."\n";
1.249     albertel  754: 
                    755: # checkall buttons
                    756:     $gradeTable.=&check_script('gradesub', 'stuinfo');
1.110     ng        757:     $gradeTable.='<input type="button" '."\n".
1.45      ng        758: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '."\n".
1.249     albertel  759: 	'value="Next->" /> <br />'."\n";
                    760:     $gradeTable.=&check_buttons();
1.267     albertel  761:     $gradeTable.='<label><input type="checkbox" name="checkPlag" checked="on" />Check For Plagiarism</label>';
1.249     albertel  762:     my ($classlist, undef, $fullname) = &getclasslist($getsec,'1');
1.45      ng        763:     $gradeTable.='<table border="0"><tr><td bgcolor="#777777">'.
1.110     ng        764: 	'<table border="0"><tr bgcolor="#e6ffff">';
                    765:     my $loop = 0;
                    766:     while ($loop < 2) {
1.126     ng        767: 	$gradeTable.='<td><b>&nbsp;No.</b>&nbsp;</td><td><b>&nbsp;Select&nbsp;</b></td>'.
1.250     albertel  768: 	    '<td>'.&nameUserString('header').'&nbsp;Section/Group</td>';
1.301     albertel  769: 	if ($env{'form.showgrading'} eq 'yes' 
                    770: 	    && $submitonly ne 'queued'
                    771: 	    && $submitonly ne 'all') {
1.110     ng        772: 	    foreach (sort(@$partlist)) {
1.324     albertel  773: 		my $display_part=&get_display_part((split(/_/))[0],$symb);
1.207     albertel  774: 		$gradeTable.='<td><b>&nbsp;Part: '.$display_part.
                    775: 		    ' Status&nbsp;</b></td>';
1.110     ng        776: 	    }
1.301     albertel  777: 	} elsif ($submitonly eq 'queued') {
                    778: 	    $gradeTable.='<td><b>&nbsp;'.&mt('Queue Status').'&nbsp;</b></td>';
1.110     ng        779: 	}
                    780: 	$loop++;
1.126     ng        781: #	$gradeTable.='<td></td>' if ($loop%2 ==1);
1.41      ng        782:     }
1.45      ng        783:     $gradeTable.='</tr>'."\n";
1.41      ng        784: 
1.45      ng        785:     my $ctr = 0;
1.294     albertel  786:     foreach my $student (sort 
                    787: 			 {
                    788: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                    789: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                    790: 			     }
                    791: 			     return $a cmp $b;
                    792: 			 }
                    793: 			 (keys(%$fullname))) {
1.41      ng        794: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel  795: 
1.110     ng        796: 	my %status = ();
1.301     albertel  797: 
                    798: 	if ($submitonly eq 'queued') {
                    799: 	    my %queue_status = 
                    800: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                    801: 							$udom,$uname);
                    802: 	    next if (!defined($queue_status{'gradingqueue'}));
                    803: 	    $status{'gradingqueue'} = $queue_status{'gradingqueue'};
                    804: 	}
                    805: 
                    806: 	if ($env{'form.showgrading'} eq 'yes' 
                    807: 	    && $submitonly ne 'queued'
                    808: 	    && $submitonly ne 'all') {
1.324     albertel  809: 	    (%status) =&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel  810: 	    my $submitted = 0;
1.164     albertel  811: 	    my $graded = 0;
1.248     albertel  812: 	    my $incorrect = 0;
1.110     ng        813: 	    foreach (keys(%status)) {
1.145     albertel  814: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel  815: 		$graded = 1 if ($status{$_} =~ /^ungraded/);
                    816: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
                    817: 		
1.110     ng        818: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                    819: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
1.145     albertel  820: 		    $submitted = 0;
1.150     albertel  821: 		    my ($part)=split(/\./,$partid);
1.110     ng        822: 		    $gradeTable.='<input type="hidden" name="'.
1.150     albertel  823: 			$student.':'.$part.':submitted_by" value="'.
1.110     ng        824: 			$status{'resource.'.$partid.'.submitted_by'}.'" />';
                    825: 		}
1.41      ng        826: 	    }
1.248     albertel  827: 	    
1.156     albertel  828: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                    829: 				     $submitonly eq 'incorrect' ||
                    830: 				     $submitonly eq 'graded'));
1.248     albertel  831: 	    next if (!$graded && ($submitonly eq 'graded'));
                    832: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng        833: 	}
1.34      ng        834: 
1.45      ng        835: 	$ctr++;
1.249     albertel  836: 	my $section = $classlist->{$student}->[&Apache::loncoursedata::CL_SECTION()];
                    837: 
1.104     albertel  838: 	if ( $perm{'vgr'} eq 'F' ) {
1.110     ng        839: 	    $gradeTable.='<tr bgcolor="#ffffe6">' if ($ctr%2 ==1);
1.126     ng        840: 	    $gradeTable.='<td align="right">'.$ctr.'&nbsp;</td>'.
1.249     albertel  841:                '<td align="center"><label><input type=checkbox name="stuinfo" value="'.
                    842:                $student.':'.$$fullname{$student}.':::SECTION'.$section.
                    843: 	       ')&nbsp;" />&nbsp;&nbsp;</label></td>'."\n".'<td>'.
                    844: 	       &nameUserString(undef,$$fullname{$student},$uname,$udom).
                    845: 	       '&nbsp;'.$section.'</td>'."\n";
1.110     ng        846: 
1.257     albertel  847: 	    if ($env{'form.showgrading'} eq 'yes' && $submitonly ne 'all') {
1.110     ng        848: 		foreach (sort keys(%status)) {
                    849: 		    next if (/^resource.*?submitted_by$/);
1.276     albertel  850: 		    $gradeTable.='<td align="center">&nbsp;'.$status{$_}.'&nbsp;</td>'."\n";
1.110     ng        851: 		}
1.41      ng        852: 	    }
1.126     ng        853: #	    $gradeTable.='<td></td>' if ($ctr%2 ==1);
1.110     ng        854: 	    $gradeTable.='</tr>'."\n" if ($ctr%2 ==0);
1.41      ng        855: 	}
                    856:     }
1.110     ng        857:     if ($ctr%2 ==1) {
1.126     ng        858: 	$gradeTable.='<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>';
1.301     albertel  859: 	    if ($env{'form.showgrading'} eq 'yes' 
                    860: 		&& $submitonly ne 'queued'
                    861: 		&& $submitonly ne 'all') {
1.110     ng        862: 		foreach (@$partlist) {
                    863: 		    $gradeTable.='<td>&nbsp;</td>';
                    864: 		}
1.301     albertel  865: 	    } elsif ($submitonly eq 'queued') {
                    866: 		$gradeTable.='<td>&nbsp;</td>';
1.110     ng        867: 	    }
                    868: 	$gradeTable.='</tr>';
                    869:     }
                    870: 
1.249     albertel  871:     $gradeTable.='</table></td></tr></table>'."\n".
1.45      ng        872: 	'<input type="button" '.
                    873: 	'onClick="javascript:checkSelect(this.form.stuinfo);" '.
1.126     ng        874: 	'value="Next->" /></form>'."\n";
1.45      ng        875:     if ($ctr == 0) {
1.96      albertel  876: 	my $num_students=(scalar(keys(%$fullname)));
                    877: 	if ($num_students eq 0) {
                    878: 	    $gradeTable='<br />&nbsp;<font color="red">There are no students currently enrolled.</font>';
                    879: 	} else {
1.171     albertel  880: 	    my $submissions='submissions';
                    881: 	    if ($submitonly eq 'incorrect') { $submissions = 'incorrect submissions'; }
                    882: 	    if ($submitonly eq 'graded'   ) { $submissions = 'ungraded submissions'; }
1.301     albertel  883: 	    if ($submitonly eq 'queued'   ) { $submissions = 'queued submissions'; }
1.96      albertel  884: 	    $gradeTable='<br />&nbsp;<font color="red">'.
1.171     albertel  885: 		'No '.$submissions.' found for this resource for any students. ('.$num_students.
                    886: 		' students checked for '.$submissions.')</font><br />';
1.96      albertel  887: 	}
1.46      ng        888:     } elsif ($ctr == 1) {
                    889: 	$gradeTable =~ s/type=checkbox/type=checkbox checked/;
1.45      ng        890:     }
1.324     albertel  891:     $gradeTable.=&show_grading_menu_form($symb);
1.45      ng        892:     $request->print($gradeTable);
1.44      ng        893:     return '';
1.10      ng        894: }
                    895: 
1.44      ng        896: #---- Called from the listStudents routine
1.249     albertel  897: 
                    898: sub check_script {
                    899:     my ($form, $type)=@_;
                    900:     my $chkallscript='<script type="text/javascript">
                    901:     function checkall() {
                    902:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    903:             ele = document.forms.'.$form.'.elements[i];
                    904:             if (ele.name == "'.$type.'") {
                    905:             document.forms.'.$form.'.elements[i].checked=true;
                    906:                                        }
                    907:         }
                    908:     }
                    909: 
                    910:     function checksec() {
                    911:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    912:             ele = document.forms.'.$form.'.elements[i];
                    913:            string = document.forms.'.$form.'.chksec.value;
                    914:            if
                    915:           (ele.value.indexOf(":::SECTION"+string)>0) {
                    916:               document.forms.'.$form.'.elements[i].checked=true;
                    917:             }
                    918:         }
                    919:     }
                    920: 
                    921: 
                    922:     function uncheckall() {
                    923:         for (i=0; i<document.forms.'.$form.'.elements.length; i++) {
                    924:             ele = document.forms.'.$form.'.elements[i];
                    925:             if (ele.name == "'.$type.'") {
                    926:             document.forms.'.$form.'.elements[i].checked=false;
                    927:                                        }
                    928:         }
                    929:     }
                    930: 
                    931: </script>'."\n";
                    932:     return $chkallscript;
                    933: }
                    934: 
                    935: sub check_buttons {
                    936:     my $buttons.='<input type="button" onclick="checkall()" value="Check All" />';
                    937:     $buttons.='<input type="button" onclick="uncheckall()" value="Uncheck All" />&nbsp;';
                    938:     $buttons.='<input type="button" onclick="checksec()" value="Check Section/Group" />';
                    939:     $buttons.='<input type="text" size="5" name="chksec" />&nbsp;';
                    940:     return $buttons;
                    941: }
                    942: 
1.44      ng        943: #     Displays the submissions for one student or a group of students
1.34      ng        944: sub processGroup {
1.41      ng        945:     my ($request)  = shift;
                    946:     my $ctr        = 0;
1.155     albertel  947:     my @stuchecked = &Apache::loncommon::get_env_multiple('form.stuinfo');
1.41      ng        948:     my $total      = scalar(@stuchecked)-1;
1.45      ng        949: 
1.41      ng        950:     foreach (@stuchecked) {
                    951: 	my ($uname,$udom,$fullname) = split(/:/);
1.257     albertel  952: 	$env{'form.student'}        = $uname;
                    953: 	$env{'form.userdom'}        = $udom;
                    954: 	$env{'form.fullname'}       = $fullname;
1.41      ng        955: 	&submission($request,$ctr,$total);
                    956: 	$ctr++;
                    957:     }
                    958:     return '';
1.35      ng        959: }
1.34      ng        960: 
1.44      ng        961: #------------------------------------------------------------------------------------
                    962: #
                    963: #-------------------------- Next few routines handles grading by student, essentially
                    964: #                           handles essay response type problem/part
                    965: #
                    966: #--- Javascript to handle the submission page functionality ---
                    967: sub sub_page_js {
                    968:     my $request = shift;
                    969:     $request->print(<<SUBJAVASCRIPT);
                    970: <script type="text/javascript" language="javascript">
1.71      ng        971:     function updateRadio(formname,id,weight) {
1.125     ng        972: 	var gradeBox = formname["GD_BOX"+id];
                    973: 	var radioButton = formname["RADVAL"+id];
                    974: 	var oldpts = formname["oldpts"+id].value;
1.72      ng        975: 	var pts = checkSolved(formname,id) == 'update' ? gradeBox.value : oldpts;
1.71      ng        976: 	gradeBox.value = pts;
                    977: 	var resetbox = false;
                    978: 	if (isNaN(pts) || pts < 0) {
                    979: 	    alert("A number equal or greater than 0 is expected. Entered value = "+pts);
                    980: 	    for (var i=0; i<radioButton.length; i++) {
                    981: 		if (radioButton[i].checked) {
                    982: 		    gradeBox.value = i;
                    983: 		    resetbox = true;
                    984: 		}
                    985: 	    }
                    986: 	    if (!resetbox) {
                    987: 		formtextbox.value = "";
                    988: 	    }
                    989: 	    return;
1.44      ng        990: 	}
1.71      ng        991: 
                    992: 	if (pts > weight) {
                    993: 	    var resp = confirm("You entered a value ("+pts+
                    994: 			       ") greater than the weight for the part. Accept?");
                    995: 	    if (resp == false) {
1.125     ng        996: 		gradeBox.value = oldpts;
1.71      ng        997: 		return;
                    998: 	    }
1.44      ng        999: 	}
1.13      albertel 1000: 
1.71      ng       1001: 	for (var i=0; i<radioButton.length; i++) {
                   1002: 	    radioButton[i].checked=false;
                   1003: 	    if (pts == i && pts != "") {
                   1004: 		radioButton[i].checked=true;
                   1005: 	    }
                   1006: 	}
                   1007: 	updateSelect(formname,id);
1.125     ng       1008: 	formname["stores"+id].value = "0";
1.41      ng       1009:     }
1.5       albertel 1010: 
1.72      ng       1011:     function writeBox(formname,id,pts) {
1.125     ng       1012: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1013: 	if (checkSolved(formname,id) == 'update') {
                   1014: 	    gradeBox.value = pts;
                   1015: 	} else {
1.125     ng       1016: 	    var oldpts = formname["oldpts"+id].value;
1.72      ng       1017: 	    gradeBox.value = oldpts;
1.125     ng       1018: 	    var radioButton = formname["RADVAL"+id];
1.71      ng       1019: 	    for (var i=0; i<radioButton.length; i++) {
                   1020: 		radioButton[i].checked=false;
1.72      ng       1021: 		if (i == oldpts) {
1.71      ng       1022: 		    radioButton[i].checked=true;
                   1023: 		}
                   1024: 	    }
1.41      ng       1025: 	}
1.125     ng       1026: 	formname["stores"+id].value = "0";
1.71      ng       1027: 	updateSelect(formname,id);
                   1028: 	return;
1.41      ng       1029:     }
1.44      ng       1030: 
1.71      ng       1031:     function clearRadBox(formname,id) {
                   1032: 	if (checkSolved(formname,id) == 'noupdate') {
                   1033: 	    updateSelect(formname,id);
                   1034: 	    return;
                   1035: 	}
1.125     ng       1036: 	gradeSelect = formname["GD_SEL"+id];
1.71      ng       1037: 	for (var i=0; i<gradeSelect.length; i++) {
                   1038: 	    if (gradeSelect[i].selected) {
                   1039: 		var selectx=i;
                   1040: 	    }
                   1041: 	}
1.125     ng       1042: 	var stores = formname["stores"+id];
1.71      ng       1043: 	if (selectx == stores.value) { return };
1.125     ng       1044: 	var gradeBox = formname["GD_BOX"+id];
1.71      ng       1045: 	gradeBox.value = "";
1.125     ng       1046: 	var radioButton = formname["RADVAL"+id];
1.71      ng       1047: 	for (var i=0; i<radioButton.length; i++) {
                   1048: 	    radioButton[i].checked=false;
                   1049: 	}
                   1050: 	stores.value = selectx;
                   1051:     }
1.5       albertel 1052: 
1.71      ng       1053:     function checkSolved(formname,id) {
1.125     ng       1054: 	if (formname["solved"+id].value == "correct_by_student" && formname.overRideScore.value == 'no') {
1.118     ng       1055: 	    var reply = confirm("This problem has been graded correct by the computer. Do you want to change the score?");
                   1056: 	    if (!reply) {return "noupdate";}
1.120     ng       1057: 	    formname.overRideScore.value = 'yes';
1.41      ng       1058: 	}
1.71      ng       1059: 	return "update";
1.13      albertel 1060:     }
1.71      ng       1061: 
                   1062:     function updateSelect(formname,id) {
1.125     ng       1063: 	formname["GD_SEL"+id][0].selected = true;
1.71      ng       1064: 	return;
1.41      ng       1065:     }
1.33      ng       1066: 
1.121     ng       1067: //=========== Check that a point is assigned for all the parts  ============
1.71      ng       1068:     function checksubmit(formname,val,total,parttot) {
1.121     ng       1069: 	formname.gradeOpt.value = val;
1.71      ng       1070: 	if (val == "Save & Next") {
                   1071: 	    for (i=0;i<=total;i++) {
                   1072: 		for (j=0;j<parttot;j++) {
1.125     ng       1073: 		    var partid = formname["partid"+i+"_"+j].value;
1.127     ng       1074: 		    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1075: 			var points = formname["GD_BOX"+i+"_"+partid].value;
1.71      ng       1076: 			if (points == "") {
1.125     ng       1077: 			    var name = formname["name"+i].value;
1.129     ng       1078: 			    var studentID = (name != '' ? name : formname["unamedom"+i].value);
                   1079: 			    var resp = confirm("You did not assign a score for "+studentID+
                   1080: 					       ", part "+partid+". Continue?");
1.71      ng       1081: 			    if (resp == false) {
1.125     ng       1082: 				formname["GD_BOX"+i+"_"+partid].focus();
1.71      ng       1083: 				return false;
                   1084: 			    }
                   1085: 			}
                   1086: 		    }
                   1087: 		    
                   1088: 		}
                   1089: 	    }
                   1090: 	    
                   1091: 	}
1.121     ng       1092: 	if (val == "Grade Student") {
                   1093: 	    formname.showgrading.value = "yes";
                   1094: 	    if (formname.Status.value == "") {
                   1095: 		formname.Status.value = "Active";
                   1096: 	    }
                   1097: 	    formname.studentNo.value = total;
                   1098: 	}
1.120     ng       1099: 	formname.submit();
                   1100:     }
                   1101: 
1.71      ng       1102: //======= Check that a score is assigned for all the problems (page/sequence grading only) =========
                   1103:     function checkSubmitPage(formname,total) {
                   1104: 	noscore = new Array(100);
                   1105: 	var ptr = 0;
                   1106: 	for (i=1;i<total;i++) {
1.125     ng       1107: 	    var partid = formname["q_"+i].value;
1.127     ng       1108: 	    if (formname["GD_SEL"+i+"_"+partid][0].selected) {
1.125     ng       1109: 		var points = formname["GD_BOX"+i+"_"+partid].value;
                   1110: 		var status = formname["solved"+i+"_"+partid].value;
1.71      ng       1111: 		if (points == "" && status != "correct_by_student") {
                   1112: 		    noscore[ptr] = i;
                   1113: 		    ptr++;
                   1114: 		}
                   1115: 	    }
                   1116: 	}
                   1117: 	if (ptr != 0) {
                   1118: 	    var sense = ptr == 1 ? ": " : "s: ";
                   1119: 	    var prolist = "";
                   1120: 	    if (ptr == 1) {
                   1121: 		prolist = noscore[0];
                   1122: 	    } else {
                   1123: 		var i = 0;
                   1124: 		while (i < ptr-1) {
                   1125: 		    prolist += noscore[i]+", ";
                   1126: 		    i++;
                   1127: 		}
                   1128: 		prolist += "and "+noscore[i];
                   1129: 	    }
                   1130: 	    var resp = confirm("You did not assign any score for the following problem"+sense+prolist+". Continue?");
                   1131: 	    if (resp == false) {
                   1132: 		return false;
                   1133: 	    }
                   1134: 	}
1.45      ng       1135: 
1.71      ng       1136: 	formname.submit();
                   1137:     }
                   1138: </script>
                   1139: SUBJAVASCRIPT
                   1140: }
1.45      ng       1141: 
1.71      ng       1142: #--- javascript for essay type problem --
                   1143: sub sub_page_kw_js {
                   1144:     my $request = shift;
1.80      ng       1145:     my $iconpath = $request->dir_config('lonIconsURL');
1.118     ng       1146:     &commonJSfunctions($request);
1.350     albertel 1147: 
1.351     albertel 1148:     my $inner_js_msg_central=<<INNERJS;
1.350     albertel 1149:     <script text="text/javascript">
                   1150:     function checkInput() {
                   1151:       opener.document.SCORE.msgsub.value = opener.checkEntities(document.msgcenter.msgsub.value);
                   1152:       var nmsg   = opener.document.SCORE.savemsgN.value;
                   1153:       var usrctr = document.msgcenter.usrctr.value;
                   1154:       var newval = opener.document.SCORE["newmsg"+usrctr];
                   1155:       newval.value = opener.checkEntities(document.msgcenter.newmsg.value);
                   1156: 
                   1157:       var msgchk = "";
                   1158:       if (document.msgcenter.subchk.checked) {
                   1159:          msgchk = "msgsub,";
                   1160:       }
                   1161:       var includemsg = 0;
                   1162:       for (var i=1; i<=nmsg; i++) {
                   1163:           var opnmsg = opener.document.SCORE["savemsg"+i];
                   1164:           var frmmsg = document.msgcenter["msg"+i];
                   1165:           opnmsg.value = opener.checkEntities(frmmsg.value);
                   1166:           var showflg = opener.document.SCORE["shownOnce"+i];
                   1167:           showflg.value = "1";
                   1168:           var chkbox = document.msgcenter["msgn"+i];
                   1169:           if (chkbox.checked) {
                   1170:              msgchk += "savemsg"+i+",";
                   1171:              includemsg = 1;
                   1172:           }
                   1173:       }
                   1174:       if (document.msgcenter.newmsgchk.checked) {
                   1175:          msgchk += "newmsg"+usrctr;
                   1176:          includemsg = 1;
                   1177:       }
                   1178:       imgformname = opener.document.SCORE["mailicon"+usrctr];
                   1179:       imgformname.src = "$iconpath/"+((includemsg) ? "mailto.gif" : "mailbkgrd.gif");
                   1180:       var includemsg = opener.document.SCORE["includemsg"+usrctr];
                   1181:       includemsg.value = msgchk;
                   1182: 
                   1183:       self.close()
                   1184: 
                   1185:     }
                   1186:     </script>
                   1187: INNERJS
                   1188: 
1.351     albertel 1189:     my $inner_js_highlight_central=<<INNERJS;
                   1190:  <script type="text/javascript">
                   1191:     function updateChoice(flag) {
                   1192:       opener.document.SCORE.kwclr.value = opener.radioSelection(document.hlCenter.kwdclr);
                   1193:       opener.document.SCORE.kwsize.value = opener.radioSelection(document.hlCenter.kwdsize);
                   1194:       opener.document.SCORE.kwstyle.value = opener.radioSelection(document.hlCenter.kwdstyle);
                   1195:       opener.document.SCORE.refresh.value = "on";
                   1196:       if (opener.document.SCORE.keywords.value!=""){
                   1197:          opener.document.SCORE.submit();
                   1198:       }
                   1199:       self.close()
                   1200:     }
                   1201: </script>
                   1202: INNERJS
                   1203: 
                   1204:     my $start_page_msg_central = 
                   1205:         &Apache::loncommon::start_page('Message Central',$inner_js_msg_central,
                   1206: 				       {'js_ready'  => 1,
                   1207: 					'only_body' => 1,
                   1208: 					'bgcolor'   =>'#FFFFFF',});
                   1209:     my $end_page_msg_central = 
                   1210: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1211: 
                   1212: 
                   1213:     my $start_page_highlight_central = 
                   1214:         &Apache::loncommon::start_page('Highlight Central',
                   1215: 				       $inner_js_highlight_central,
1.350     albertel 1216: 				       {'js_ready'  => 1,
                   1217: 					'only_body' => 1,
                   1218: 					'bgcolor'   =>'#FFFFFF',});
1.351     albertel 1219:     my $end_page_highlight_central = 
1.350     albertel 1220: 	&Apache::loncommon::end_page({'js_ready' => 1});
                   1221: 
1.219     www      1222:     my $docopen=&Apache::lonhtmlcommon::javascript_docopen();
1.236     albertel 1223:     $docopen=~s/^document\.//;
1.71      ng       1224:     $request->print(<<SUBJAVASCRIPT);
                   1225: <script type="text/javascript" language="javascript">
1.45      ng       1226: 
1.44      ng       1227: //===================== Show list of keywords ====================
1.122     ng       1228:   function keywords(formname) {
                   1229:     var nret = prompt("Keywords list, separated by a space. Add/delete to list if desired.",formname.keywords.value);
1.44      ng       1230:     if (nret==null) return;
1.122     ng       1231:     formname.keywords.value = nret;
1.44      ng       1232: 
1.122     ng       1233:     if (formname.keywords.value != "") {
1.128     ng       1234: 	formname.refresh.value = "on";
1.122     ng       1235: 	formname.submit();
1.44      ng       1236:     }
                   1237:     return;
                   1238:   }
                   1239: 
                   1240: //===================== Script to view submitted by ==================
                   1241:   function viewSubmitter(submitter) {
                   1242:     document.SCORE.refresh.value = "on";
                   1243:     document.SCORE.NCT.value = "1";
                   1244:     document.SCORE.unamedom0.value = submitter;
                   1245:     document.SCORE.submit();
                   1246:     return;
                   1247:   }
                   1248: 
                   1249: //===================== Script to add keyword(s) ==================
                   1250:   function getSel() {
                   1251:     if (document.getSelection) txt = document.getSelection();
                   1252:     else if (document.selection) txt = document.selection.createRange().text;
                   1253:     else return;
                   1254:     var cleantxt = txt.replace(new RegExp('([\\f\\n\\r\\t\\v ])+', 'g')," ");
                   1255:     if (cleantxt=="") {
1.46      ng       1256: 	alert("Please select a word or group of words from document and then click this link.");
1.44      ng       1257: 	return;
                   1258:     }
                   1259:     var nret = prompt("Add selection to keyword list? Edit if desired.",cleantxt);
                   1260:     if (nret==null) return;
1.127     ng       1261:     document.SCORE.keywords.value = document.SCORE.keywords.value+" "+nret;
1.44      ng       1262:     if (document.SCORE.keywords.value != "") {
1.127     ng       1263: 	document.SCORE.refresh.value = "on";
1.44      ng       1264: 	document.SCORE.submit();
                   1265:     }
                   1266:     return;
                   1267:   }
                   1268: 
                   1269: //====================== Script for composing message ==============
1.80      ng       1270:    // preload images
                   1271:    img1 = new Image();
                   1272:    img1.src = "$iconpath/mailbkgrd.gif";
                   1273:    img2 = new Image();
                   1274:    img2.src = "$iconpath/mailto.gif";
                   1275: 
1.44      ng       1276:   function msgCenter(msgform,usrctr,fullname) {
                   1277:     var Nmsg  = msgform.savemsgN.value;
                   1278:     savedMsgHeader(Nmsg,usrctr,fullname);
                   1279:     var subject = msgform.msgsub.value;
1.127     ng       1280:     var msgchk = document.SCORE["includemsg"+usrctr].value;
1.44      ng       1281:     re = /msgsub/;
                   1282:     var shwsel = "";
                   1283:     if (re.test(msgchk)) { shwsel = "checked" }
1.123     ng       1284:     subject = (document.SCORE.shownSub.value == 0 ? checkEntities(subject) : subject);
                   1285:     displaySubject(checkEntities(subject),shwsel);
1.44      ng       1286:     for (var i=1; i<=Nmsg; i++) {
1.123     ng       1287: 	var testmsg = "savemsg"+i+",";
                   1288: 	re = new RegExp(testmsg,"g");
1.44      ng       1289: 	shwsel = "";
                   1290: 	if (re.test(msgchk)) { shwsel = "checked" }
1.125     ng       1291: 	var message = document.SCORE["savemsg"+i].value;
1.126     ng       1292: 	message = (document.SCORE["shownOnce"+i].value == 0 ? checkEntities(message) : message);
1.123     ng       1293: 	displaySavedMsg(i,message,shwsel); //I do not get it. w/o checkEntities on saved messages,
                   1294: 	                                   //any &lt; is already converted to <, etc. However, only once!!
1.44      ng       1295:     }
1.125     ng       1296:     newmsg = document.SCORE["newmsg"+usrctr].value;
1.44      ng       1297:     shwsel = "";
                   1298:     re = /newmsg/;
                   1299:     if (re.test(msgchk)) { shwsel = "checked" }
                   1300:     newMsg(newmsg,shwsel);
                   1301:     msgTail(); 
                   1302:     return;
                   1303:   }
                   1304: 
1.123     ng       1305:   function checkEntities(strx) {
                   1306:     if (strx.length == 0) return strx;
                   1307:     var orgStr = ["&", "<", ">", '"']; 
                   1308:     var newStr = ["&amp;", "&lt;", "&gt;", "&quot;"];
                   1309:     var counter = 0;
                   1310:     while (counter < 4) {
                   1311: 	strx = strReplace(strx,orgStr[counter],newStr[counter]);
                   1312: 	counter++;
                   1313:     }
                   1314:     return strx;
                   1315:   }
                   1316: 
                   1317:   function strReplace(strx, orgStr, newStr) {
                   1318:     return strx.split(orgStr).join(newStr);
                   1319:   }
                   1320: 
1.44      ng       1321:   function savedMsgHeader(Nmsg,usrctr,fullname) {
1.76      ng       1322:     var height = 70*Nmsg+250;
1.44      ng       1323:     var scrollbar = "no";
                   1324:     if (height > 600) {
                   1325: 	height = 600;
                   1326: 	scrollbar = "yes";
                   1327:     }
1.118     ng       1328:     var xpos = (screen.width-600)/2;
                   1329:     xpos = (xpos < 0) ? '0' : xpos;
                   1330:     var ypos = (screen.height-height)/2-30;
                   1331:     ypos = (ypos < 0) ? '0' : ypos;
                   1332: 
1.206     albertel 1333:     pWin = window.open('', 'MessageCenter', 'resizable=yes,toolbar=no,location=no,scrollbars='+scrollbar+',screenx='+xpos+',screeny='+ypos+',width=600,height='+height);
1.76      ng       1334:     pWin.focus();
                   1335:     pDoc = pWin.document;
1.219     www      1336:     pDoc.$docopen;
1.351     albertel 1337:     pDoc.write('$start_page_msg_central');
1.76      ng       1338: 
                   1339:     pDoc.write("<form action=\\"inactive\\" name=\\"msgcenter\\">");
                   1340:     pDoc.write("<input value=\\""+usrctr+"\\" name=\\"usrctr\\" type=\\"hidden\\">");
1.326     albertel 1341:     pDoc.write("<font color=\\"green\\" size=+1>&nbsp;Compose Message for \"+fullname+\"</font><br /><br />");
1.76      ng       1342: 
                   1343:     pDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1344:     pDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1345:     pDoc.write("<td><b>Type</b></td><td><b>Include</b></td><td><b>Message</td></tr>");
1.44      ng       1346: }
                   1347:     function displaySubject(msg,shwsel) {
1.76      ng       1348:     pDoc = pWin.document;
                   1349:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1350:     pDoc.write("<td>Subject</td>");
                   1351:     pDoc.write("<td align=\\"center\\"><input name=\\"subchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1352:     pDoc.write("<td><input name=\\"msgsub\\" type=\\"text\\" value=\\""+msg+"\\"size=\\"60\\" maxlength=\\"80\\"></td></tr>");
1.44      ng       1353: }
                   1354: 
1.72      ng       1355:   function displaySavedMsg(ctr,msg,shwsel) {
1.76      ng       1356:     pDoc = pWin.document;
                   1357:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1358:     pDoc.write("<td align=\\"center\\">"+ctr+"</td>");
                   1359:     pDoc.write("<td align=\\"center\\"><input name=\\"msgn"+ctr+"\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1360:     pDoc.write("<td><textarea name=\\"msg"+ctr+"\\" cols=\\"60\\" rows=\\"3\\">"+msg+"</textarea></td></tr>");
1.44      ng       1361: }
                   1362: 
                   1363:   function newMsg(newmsg,shwsel) {
1.76      ng       1364:     pDoc = pWin.document;
                   1365:     pDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1366:     pDoc.write("<td align=\\"center\\">New</td>");
                   1367:     pDoc.write("<td align=\\"center\\"><input name=\\"newmsgchk\\" type=\\"checkbox\\"" +shwsel+"></td>");
                   1368:     pDoc.write("<td><textarea name=\\"newmsg\\" cols=\\"60\\" rows=\\"3\\" onchange=\\"javascript:this.form.newmsgchk.checked=true\\" >"+newmsg+"</textarea></td></tr>");
1.44      ng       1369: }
                   1370: 
                   1371:   function msgTail() {
1.76      ng       1372:     pDoc = pWin.document;
                   1373:     pDoc.write("</table>");
                   1374:     pDoc.write("</td></tr></table>&nbsp;");
                   1375:     pDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:checkInput()\\">&nbsp;&nbsp;");
1.326     albertel 1376:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1377:     pDoc.write("</form>");
1.351     albertel 1378:     pDoc.write('$end_page_msg_central');
1.128     ng       1379:     pDoc.close();
1.44      ng       1380: }
                   1381: 
                   1382: //====================== Script for keyword highlight options ==============
                   1383:   function kwhighlight() {
                   1384:     var kwclr    = document.SCORE.kwclr.value;
                   1385:     var kwsize   = document.SCORE.kwsize.value;
                   1386:     var kwstyle  = document.SCORE.kwstyle.value;
                   1387:     var redsel = "";
                   1388:     var grnsel = "";
                   1389:     var blusel = "";
                   1390:     if (kwclr=="red")   {var redsel="checked"};
                   1391:     if (kwclr=="green") {var grnsel="checked"};
                   1392:     if (kwclr=="blue")  {var blusel="checked"};
                   1393:     var sznsel = "";
                   1394:     var sz1sel = "";
                   1395:     var sz2sel = "";
                   1396:     if (kwsize=="0")  {var sznsel="checked"};
                   1397:     if (kwsize=="+1") {var sz1sel="checked"};
                   1398:     if (kwsize=="+2") {var sz2sel="checked"};
                   1399:     var synsel = "";
                   1400:     var syisel = "";
                   1401:     var sybsel = "";
                   1402:     if (kwstyle=="")    {var synsel="checked"};
                   1403:     if (kwstyle=="<i>") {var syisel="checked"};
                   1404:     if (kwstyle=="<b>") {var sybsel="checked"};
                   1405:     highlightCentral();
                   1406:     highlightbody('red','red',redsel,'0','normal',sznsel,'','normal',synsel);
                   1407:     highlightbody('green','green',grnsel,'+1','+1',sz1sel,'<i>','italic',syisel);
                   1408:     highlightbody('blue','blue',blusel,'+2','+2',sz2sel,'<b>','bold',sybsel);
                   1409:     highlightend();
                   1410:     return;
                   1411:   }
                   1412: 
                   1413:   function highlightCentral() {
1.76      ng       1414: //    if (window.hwdWin) window.hwdWin.close();
1.118     ng       1415:     var xpos = (screen.width-400)/2;
                   1416:     xpos = (xpos < 0) ? '0' : xpos;
                   1417:     var ypos = (screen.height-330)/2-30;
                   1418:     ypos = (ypos < 0) ? '0' : ypos;
                   1419: 
1.206     albertel 1420:     hwdWin = window.open('', 'KeywordHighlightCentral', 'resizeable=yes,toolbar=no,location=no,scrollbars=no,width=400,height=300,screenx='+xpos+',screeny='+ypos);
1.76      ng       1421:     hwdWin.focus();
                   1422:     var hDoc = hwdWin.document;
1.219     www      1423:     hDoc.$docopen;
1.351     albertel 1424:     hDoc.write('$start_page_highlight_central');
1.76      ng       1425:     hDoc.write("<form action=\\"inactive\\" name=\\"hlCenter\\">");
1.326     albertel 1426:     hDoc.write("<font color=\\"green\\" size=+1>&nbsp;Keyword Highlight Options</font><br /><br />");
1.76      ng       1427: 
                   1428:     hDoc.write("<table border=0 width=100%><tr><td bgcolor=\\"#777777\\">");
                   1429:     hDoc.write("<table border=0 width=100%><tr bgcolor=\\"#ddffff\\">");
                   1430:     hDoc.write("<td><b>Text Color</b></td><td><b>Font Size</b></td><td><b>Font Style</td></tr>");
1.44      ng       1431:   }
                   1432: 
                   1433:   function highlightbody(clrval,clrtxt,clrsel,szval,sztxt,szsel,syval,sytxt,sysel) { 
1.76      ng       1434:     var hDoc = hwdWin.document;
                   1435:     hDoc.write("<tr bgcolor=\\"#ffffdd\\">");
                   1436:     hDoc.write("<td align=\\"left\\">");
                   1437:     hDoc.write("<input name=\\"kwdclr\\" type=\\"radio\\" value=\\""+clrval+"\\" "+clrsel+">&nbsp;"+clrtxt+"</td>");
                   1438:     hDoc.write("<td align=\\"left\\">");
                   1439:     hDoc.write("<input name=\\"kwdsize\\" type=\\"radio\\" value=\\""+szval+"\\" "+szsel+">&nbsp;"+sztxt+"</td>");
                   1440:     hDoc.write("<td align=\\"left\\">");
                   1441:     hDoc.write("<input name=\\"kwdstyle\\" type=\\"radio\\" value=\\""+syval+"\\" "+sysel+">&nbsp;"+sytxt+"</td>");
                   1442:     hDoc.write("</tr>");
1.44      ng       1443:   }
                   1444: 
                   1445:   function highlightend() { 
1.76      ng       1446:     var hDoc = hwdWin.document;
                   1447:     hDoc.write("</table>");
                   1448:     hDoc.write("</td></tr></table>&nbsp;");
                   1449:     hDoc.write("<input type=\\"button\\" value=\\"Save\\" onClick=\\"javascript:updateChoice(1)\\">&nbsp;&nbsp;");
1.326     albertel 1450:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       1451:     hDoc.write("</form>");
1.351     albertel 1452:     hDoc.write('$end_page_highlight_central');
1.128     ng       1453:     hDoc.close();
1.44      ng       1454:   }
                   1455: 
                   1456: </script>
                   1457: SUBJAVASCRIPT
                   1458: }
                   1459: 
1.349     albertel 1460: sub get_increment {
1.348     bowersj2 1461:     my $increment = $env{'form.increment'};
                   1462:     if ($increment != 1 && $increment != .5 && $increment != .25 &&
                   1463:         $increment != .1) {
                   1464:         $increment = 1;
                   1465:     }
                   1466:     return $increment;
                   1467: }
                   1468: 
1.71      ng       1469: #--- displays the grading box, used in essay type problem and grading by page/sequence
                   1470: sub gradeBox {
1.322     albertel 1471:     my ($request,$symb,$uname,$udom,$counter,$partid,$record) = @_;
1.381     albertel 1472:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1473: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       1474: 	'/check.gif" height="16" border="0" />';
                   1475:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1476:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
                   1477: 		  '<font color="red">problem weight assigned by computer</font>');
                   1478:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1479:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1480: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1481:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1482:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1483:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1484: 				       [$partid]);
                   1485:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1486:     if ($last_resets{$partid}) {
                   1487:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1488:     }
1.71      ng       1489:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1490: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1491:     my $ctr = 0;
1.348     bowersj2 1492:     my $thisweight = 0;
1.349     albertel 1493:     my $increment = &get_increment();
1.71      ng       1494:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1495:     while ($thisweight<=$wgt) {
1.381     albertel 1496: 	$result.= '<td><span style="white-space: nowrap;"><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1497: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1498: 	    $thisweight.')" value="'.$thisweight.'" '.
1.381     albertel 1499: 	    ($score eq $thisweight ? 'checked':'').' /> '.$thisweight."</label></span></td>\n";
1.71      ng       1500: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1501:         $thisweight += $increment;
1.71      ng       1502: 	$ctr++;
                   1503:     }
                   1504:     $result.='</tr></table>';
                   1505:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1506:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1507: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1508: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1509: 	$wgt.')" /></td>'."\n";
                   1510:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1511: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1512: 	' </td><td>'."\n";
                   1513:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1514: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1515:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
1.381     albertel 1516: 	$result.='<option>&nbsp;</option>'.
1.125     ng       1517: 	    '<option selected="on">excused</option>';
1.71      ng       1518:     } else {
1.381     albertel 1519: 	$result.='<option selected="on">&nbsp;</option>'.
1.125     ng       1520: 	    '<option>excused</option>';
1.71      ng       1521:     }
1.125     ng       1522:     $result.='<option>reset status</option></select>'."\n";
1.381     albertel 1523:     $result.="&nbsp;&nbsp;\n";
1.71      ng       1524:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1525: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1526: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1527: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1528:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1529:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1530:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1531:         $aggtries.'" />'."\n";
1.71      ng       1532:     $result.='</td></tr></table>'."\n";
1.323     banghart 1533:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1534:     return $result;
                   1535: }
1.322     albertel 1536: 
                   1537: sub handback_box {
1.323     banghart 1538:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1539:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1540:     my (@respids);
1.375     albertel 1541:      my @part_response_id = &flatten_responseType($responseType);
                   1542:     foreach my $part_response_id (@part_response_id) {
                   1543:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1544:         if ($part eq $partid) {
1.375     albertel 1545:             push(@respids,$resp);
1.323     banghart 1546:         }
                   1547:     }
1.318     banghart 1548:     my $result;
1.323     banghart 1549:     foreach my $respid (@respids) {
1.322     albertel 1550: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1551: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1552: 	next if (!@$files);
                   1553: 	my $file_counter = 1;
1.313     banghart 1554: 	foreach my $file (@$files) {
1.368     banghart 1555: 	    if ($file =~ /\/portfolio\//) {
                   1556:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1557:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1558:     	        $file_disp = "$name.$ext";
                   1559:     	        $file = $file_path.$file_disp;
                   1560:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1561:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1562:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1563:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1564:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1565:     	        $file_counter++;
                   1566: 	    }
1.322     albertel 1567: 	}
1.313     banghart 1568:     }
1.318     banghart 1569:     return $result;    
1.71      ng       1570: }
1.44      ng       1571: 
1.58      albertel 1572: sub show_problem {
1.382   ! albertel 1573:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode,$form) = @_;
1.144     albertel 1574:     my $rendered;
1.382   ! albertel 1575:     my %form = ((ref($form) eq 'HASH')? %{$form} : ());
1.329     albertel 1576:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1577:     if ($mode eq 'both' or $mode eq 'text') {
                   1578: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.382   ! albertel 1579: 						       $env{'request.course.id'},
        !          1580: 						       undef,\%form);
1.144     albertel 1581:     }
1.58      albertel 1582:     if ($removeform) {
                   1583: 	$rendered=~s|<form(.*?)>||g;
                   1584: 	$rendered=~s|</form>||g;
1.374     albertel 1585: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1586:     }
1.144     albertel 1587:     my $companswer;
                   1588:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1589: 	&Apache::lonxml::restore_problem_counter();
1.382   ! albertel 1590: 	$companswer=
        !          1591: 	    &Apache::loncommon::get_student_answers($symb,$uname,$udom,
        !          1592: 						    $env{'request.course.id'},
        !          1593: 						    %form);
1.144     albertel 1594:     }
1.58      albertel 1595:     if ($removeform) {
                   1596: 	$companswer=~s|<form(.*?)>||g;
                   1597: 	$companswer=~s|</form>||g;
1.144     albertel 1598: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1599:     }
                   1600:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1601:     $result.='<table border="0" width="100%">';
1.144     albertel 1602:     if ($viewon) {
                   1603: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1604: 	if ($mode eq 'both' or $mode eq 'text') {
                   1605: 	    $result.='View of the problem - ';
                   1606: 	} else {
                   1607: 	    $result.='Correct answer: ';
                   1608: 	}
1.257     albertel 1609: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1610:     }
                   1611:     if ($mode eq 'both') {
                   1612: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1613: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1614:     } elsif ($mode eq 'text') {
                   1615: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1616:     } elsif ($mode eq 'answer') {
                   1617: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1618:     }
1.58      albertel 1619:     $result.='</td></tr></table>';
                   1620:     $result.='</td></tr></table><br />';
1.71      ng       1621:     return $result;
1.58      albertel 1622: }
                   1623: 
1.44      ng       1624: # --------------------------- show submissions of a student, option to grade 
                   1625: sub submission {
                   1626:     my ($request,$counter,$total) = @_;
                   1627: 
1.257     albertel 1628:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1629:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1630:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1631:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1632: 
1.324     albertel 1633:     my $symb = &get_symb($request); 
                   1634:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1635: 
                   1636:     if (!&canview($usec)) {
1.116     ng       1637: 	$request->print('<font color="red">Unable to view requested student.('.
1.222     albertel 1638: 			$uname.'@'.$udom.' in section '.$usec.' in course id '.
1.257     albertel 1639: 			$env{'request.course.id'}.')</font>');
1.324     albertel 1640: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1641: 	return;
                   1642:     }
                   1643: 
1.257     albertel 1644:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1645:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1646:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1647:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.381     albertel 1648:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   1649: 	'" src="'.$request->dir_config('lonIconsURL').
1.122     ng       1650: 	'/check.gif" height="16" border="0" />';
1.41      ng       1651: 
                   1652:     # header info
                   1653:     if ($counter == 0) {
                   1654: 	&sub_page_js($request);
1.257     albertel 1655: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1656: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1657: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.76      ng       1658: 
1.45      ng       1659: 	$request->print('<h3>&nbsp;<font color="#339933">Submission Record</font></h3>'."\n".
1.257     albertel 1660: 			'<font size=+1>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n");
1.118     ng       1661: 
1.257     albertel 1662: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1663: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1664: 		$checkIcon.' symbol.'."\n";
                   1665: 	    $request->print($checkMark);
                   1666: 	}
1.41      ng       1667: 
1.44      ng       1668: 	# option to display problem, only once else it cause problems 
                   1669:         # with the form later since the problem has a form.
1.257     albertel 1670: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1671: 	    my $mode;
1.257     albertel 1672: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1673: 		$mode='both';
1.257     albertel 1674: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1675: 		$mode='text';
1.257     albertel 1676: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1677: 		$mode='answer';
                   1678: 	    }
1.329     albertel 1679: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1680: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1681: 	}
                   1682: 	
1.44      ng       1683: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1684:         # if this subroutine has been called once.
1.41      ng       1685: 	my %keyhash = ();
1.257     albertel 1686: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1687: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1688: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1689: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1690: 
1.257     albertel 1691: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1692: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1693: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1694: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1695: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1696: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1697: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1698: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1699: 	}
1.257     albertel 1700: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1701: 
1.303     banghart 1702: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1703: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1704: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1705: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1706: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1707: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1708: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1709: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1710: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.41      ng       1711: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
1.257     albertel 1712: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1713: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1714: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1715: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1716: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1717: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1718: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1719: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1720: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1721: 	if ($env{'form.handgrade'} eq 'yes') {
                   1722: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1723: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1724: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1725: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1726: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1727: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1728: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1729: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1730: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1731: 	    }
1.123     ng       1732: 	}
1.41      ng       1733: 	
                   1734: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1735: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1736: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1737: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1738: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1739: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1740: 		'" />'."\n".
                   1741: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1742: 	    $cts++;
                   1743: 	}
                   1744: 	$request->print($prnmsg);
1.32      ng       1745: 
1.257     albertel 1746: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1747: #
                   1748: # Print out the keyword options line
                   1749: #
1.41      ng       1750: 	    $request->print(<<KEYWORDS);
1.38      ng       1751: &nbsp;<b>Keyword Options:</b>&nbsp;
1.122     ng       1752: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
1.38      ng       1753: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1754:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
                   1755: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
                   1756: KEYWORDS
1.88      www      1757: #
                   1758: # Load the other essays for similarity check
                   1759: #
1.324     albertel 1760:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.88      www      1761: 	    my ($adom,$aname,$apath)=($essayurl=~/^(\w+)\/(\w+)\/(.*)$/);
1.359     www      1762: 	    $apath=&escape($apath);
1.88      www      1763: 	    $apath=~s/\W/\_/gs;
                   1764: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1765:         }
                   1766:     }
1.44      ng       1767: 
1.257     albertel 1768:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1769: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1770: 	my $mode;
1.257     albertel 1771: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1772: 	    $mode='both';
1.257     albertel 1773: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1774: 	    $mode='text';
1.257     albertel 1775: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1776: 	    $mode='answer';
                   1777: 	}
1.329     albertel 1778: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1779: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1780:     }
1.144     albertel 1781: 
1.257     albertel 1782:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1783:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1784: 
1.44      ng       1785:     # Display student info
1.41      ng       1786:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1787:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1788: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1789: 
1.257     albertel 1790:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1791:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1792: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1793: 
1.118     ng       1794:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1795:     my @col_fullnames;
1.56      matthew  1796:     my ($classlist,$fullname);
1.257     albertel 1797:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1798: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1799: 	for (keys (%$handgrade)) {
1.44      ng       1800: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1801: 					    '.maxcollaborators',
                   1802:                                             $symb,$udom,$uname);
                   1803: 	    next if ($ncol <= 0);
                   1804:             s/\_/\./g;
                   1805:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1806:             my @goodcollaborators = ();
                   1807:             my @badcollaborators  = ();
                   1808: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1809: 		$_ =~ s/[\$\^\(\)]//g;
                   1810: 		next if ($_ eq '');
1.80      ng       1811: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1812: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1813: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1814: 		# Doing this grep allows 'fuzzy' specification
                   1815: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1816: 		if (! scalar(@Matches)) {
                   1817: 		    push @badcollaborators,$_;
                   1818: 		} else {
                   1819: 		    push @goodcollaborators, @Matches;
                   1820: 		}
1.80      ng       1821: 	    }
1.86      ng       1822:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1823:                 $result.='<b>Collaborators: </b>';
1.86      ng       1824:                 foreach (@goodcollaborators) {
                   1825: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1826: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1827: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1828: 		}
1.57      matthew  1829:                 $result.='<br />'."\n";
1.150     albertel 1830: 		my ($part)=split(/\./,$_);
1.86      ng       1831: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1832: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1833: 		    "\n";
1.86      ng       1834: 	    }
                   1835: 	    if (scalar(@badcollaborators) > 0) {
                   1836: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1837: 		$result.='This student has submitted ';
                   1838: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1839: 		$result .= ': '.join(', ',@badcollaborators);
                   1840: 		$result .= '</td></tr></table>';
                   1841: 	    }         
                   1842: 	    if (scalar(@badcollaborators > $ncol)) {
                   1843: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1844: 		$result .= 'This student has submitted too many '.
                   1845: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1846: 		$result .= '</td></tr></table>';
                   1847: 	    }
1.41      ng       1848: 	}
                   1849:     }
1.44      ng       1850:     $request->print($result."\n");
1.33      ng       1851: 
1.44      ng       1852:     # print student answer/submission
                   1853:     # Options are (1) Handgaded submission only
                   1854:     #             (2) Last submission, includes submission that is not handgraded 
                   1855:     #                  (for multi-response type part)
                   1856:     #             (3) Last submission plus the parts info
                   1857:     #             (4) The whole record for this student
1.257     albertel 1858:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1859: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1860: 	my $lastsubonly=''.
                   1861: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1862: 	     $$timestamp)."</td></tr>\n";
                   1863: 	if ($$timestamp eq '') {
                   1864: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1865: 	} else {
                   1866: 	    my %seenparts;
1.375     albertel 1867: 	    my @part_response_id = &flatten_responseType($responseType);
                   1868: 	    foreach my $part (@part_response_id) {
                   1869: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1870: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1871: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1872: 		    if (exists($seenparts{$partid})) { next; }
                   1873: 		    $seenparts{$partid}=1;
1.207     albertel 1874: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1875: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1876: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1877: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.151     albertel 1878: 			'\')"; TARGET=_self>'.
1.257     albertel 1879: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1880: 		    $request->print($submitby);
                   1881: 		    next;
                   1882: 		}
                   1883: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1884: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1885: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1886: 			$display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1887: 			' )</font>&nbsp; &nbsp;'.
                   1888: 			'<font color="red">Nothing submitted - no attempts</font><br /><br />';
                   1889: 		    next;
                   1890: 		}
                   1891: 		foreach (@$string) {
                   1892: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1893: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1894: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1895: 		    # Similarity check
                   1896: 		    my $similar='';
1.257     albertel 1897: 		    if($env{'form.checkPlag'}){
1.151     albertel 1898: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   1899: 			    &most_similar($uname,$udom,$subval);
                   1900: 			if ($osim) {
                   1901: 			    $osim=int($osim*100.0);
                   1902: 			    $similar="<hr /><h3><font color=\"#FF0000\">Essay".
                   1903: 				" is $osim% similar to an essay by ".
                   1904: 				&Apache::loncommon::plainname($oname,$odom).
                   1905: 				'</font></h3><blockquote><i>'.
                   1906: 				&keywords_highlight($oessay).
                   1907: 				'</i></blockquote><hr />';
                   1908: 			}
1.150     albertel 1909: 		    }
1.151     albertel 1910: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1911: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1912: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377     albertel 1913: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1914: 			my $display_part=&get_display_part($partid,$symb);
1.207     albertel 1915: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1916: 			    $display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1917: 			    ' )</font>&nbsp; &nbsp;';
1.313     banghart 1918: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1919: 			if (@$files) {
1.232     albertel 1920: 			    $lastsubonly.='<br /><font color="red" size="1">Like all files provided by users, this file may contain virusses</font><br />';
1.303     banghart 1921: 			    my $file_counter = 0;
1.313     banghart 1922: 			    foreach my $file (@$files) {
1.303     banghart 1923: 			        $file_counter ++;
1.232     albertel 1924: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1925: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1926: 			    }
1.236     albertel 1927: 			    $lastsubonly.='<br />';
1.41      ng       1928: 			}
1.151     albertel 1929: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1930: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1931: 					 $respid,\%record,$order);
                   1932: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1933: 		    }
                   1934: 		}
                   1935: 	    }
1.151     albertel 1936: 	}
                   1937: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1938: 	$request->print($lastsubonly);
1.257     albertel 1939:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1940: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1941: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1942:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1943: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1944: 								 $env{'request.course.id'},
1.44      ng       1945: 								 $last,'.submission',
                   1946: 								 'Apache::grades::keywords_highlight'));
1.41      ng       1947:     }
1.120     ng       1948: 
1.121     ng       1949:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   1950: 	.$udom.'" />'."\n");
1.41      ng       1951:     
1.44      ng       1952:     # return if view submission with no grading option
1.257     albertel 1953:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       1954: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       1955: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
                   1956: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 1957: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 1958: 	if (($env{'form.command'} eq 'submission') || 
                   1959: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 1960: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 1961: 	}
1.180     albertel 1962: 	$request->print($toGrade);
1.41      ng       1963: 	return;
1.180     albertel 1964:     } else {
                   1965: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       1966:     }
1.33      ng       1967: 
1.121     ng       1968:     # essay grading message center
1.257     albertel 1969:     if ($env{'form.handgrade'} eq 'yes') {
                   1970: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       1971: 	my $msgfor = $givenn.' '.$lastname;
                   1972: 	if (scalar(@col_fullnames) > 0) {
                   1973: 	    my $lastone = pop @col_fullnames;
                   1974: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   1975: 	}
                   1976: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       1977: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   1978: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   1979: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.118     ng       1980: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
1.350     albertel 1981: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   1982: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       1983: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   1984: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      1985: 	    '<br />&nbsp;('.
                   1986: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       1987: 	$request->print($result);
1.118     ng       1988:     }
1.300     albertel 1989:     if ($perm{'vgr'}) {
1.297     www      1990: 	$request->print('<br />'.
1.300     albertel 1991: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   1992: 						   $uname,$udom,'check'));
1.297     www      1993:     }
1.300     albertel 1994:     if ($perm{'opa'}) {
1.297     www      1995: 	$request->print('<br />'.
1.300     albertel 1996: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   1997: 					 $uname,$udom,$symb,'check'));
1.297     www      1998:     }
1.41      ng       1999: 
                   2000:     my %seen = ();
                   2001:     my @partlist;
1.129     ng       2002:     my @gradePartRespid;
1.375     albertel 2003:     my @part_response_id = &flatten_responseType($responseType);
                   2004:     foreach my $part_response_id (@part_response_id) {
                   2005:     	my ($partid,$respid) = @{ $part_response_id };
                   2006: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2007: 	next if ($seen{$partid} > 0);
1.41      ng       2008: 	$seen{$partid}++;
1.317     banghart 2009: 	next if ($$handgrade{$part_resp} =~ /:no$/ && $env{'form.lastSub'} =~ /^(hdgrade)$/);
1.41      ng       2010: 	push @partlist,$partid;
1.129     ng       2011: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2012: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2013:     }
1.45      ng       2014:     $result='<input type="hidden" name="partlist'.$counter.
                   2015: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2016:     $result.='<input type="hidden" name="gradePartRespid'.
                   2017: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2018:     my $ctr = 0;
                   2019:     while ($ctr < scalar(@partlist)) {
                   2020: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2021: 	    $partlist[$ctr].'" />'."\n";
                   2022: 	$ctr++;
                   2023:     }
                   2024:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2025: 
                   2026:     # print end of form
                   2027:     if ($counter == $total) {
1.297     www      2028: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2029: 	$endform.='<input type="button" value="Save & Next" '.
                   2030: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
                   2031: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
                   2032: 	my $ntstu ='<select name="NTSTU">'.
                   2033: 	    '<option>1</option><option>2</option>'.
                   2034: 	    '<option>3</option><option>5</option>'.
                   2035: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2036: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.119     ng       2037: 	$ntstu =~ s/<option>$nsel</<option selected="on">$nsel</;
                   2038: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2039: 	$endform.='<input type="button" value="Previous" '.
                   2040: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
                   2041: 	    '<input type="button" value="Next" '.
                   2042: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
                   2043: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2044:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2045:             "' name='increment' />";
1.45      ng       2046: 	$endform.='</td><tr></table></form>';
1.324     albertel 2047: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2048: 	$request->print($endform);
                   2049:     }
                   2050:     return '';
1.38      ng       2051: }
                   2052: 
1.44      ng       2053: #--- Retrieve the last submission for all the parts
1.38      ng       2054: sub get_last_submission {
1.119     ng       2055:     my ($returnhash)=@_;
1.46      ng       2056:     my (@string,$timestamp);
1.119     ng       2057:     if ($$returnhash{'version'}) {
1.46      ng       2058: 	my %lasthash=();
                   2059: 	my ($version);
1.119     ng       2060: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
                   2061: 	    foreach (sort(split(/\:/,$$returnhash{$version.':keys'}))) {
                   2062: 		$lasthash{$_}=$$returnhash{$version.':'.$_};
                   2063: 		   $timestamp = scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2064: 	    }
                   2065: 	}
                   2066: 	foreach ((keys %lasthash)) {
                   2067: 	    if ($_ =~ /\.submission$/) {
                   2068: 		my ($partid,$foo) = split(/submission$/,$_);
                   2069: 		my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
                   2070: 		    '<font color="red">Draft Copy</font> ' : '';
                   2071: 		push @string, (join(':',$_,$draft.$lasthash{$_}));
1.41      ng       2072: 	    }
                   2073: 	}
                   2074:     }
1.125     ng       2075:     @string = $string[0] eq '' ? '<font color="red">Nothing submitted - no attempts.</font>' : @string;
1.46      ng       2076:     return \@string,\$timestamp;
1.38      ng       2077: }
1.35      ng       2078: 
1.44      ng       2079: #--- High light keywords, with style choosen by user.
1.38      ng       2080: sub keywords_highlight {
1.44      ng       2081:     my $string    = shift;
1.257     albertel 2082:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2083:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2084:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2085:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.41      ng       2086:     foreach (@keylist) {
1.257     albertel 2087: 	$string =~ s/\b\Q$_\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$_$styleoff<\/font>/gi;
1.41      ng       2088:     }
                   2089:     return $string;
1.38      ng       2090: }
1.36      ng       2091: 
1.44      ng       2092: #--- Called from submission routine
1.38      ng       2093: sub processHandGrade {
1.41      ng       2094:     my ($request) = shift;
1.324     albertel 2095:     my $symb   = &get_symb($request);
                   2096:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2097:     my $button = $env{'form.gradeOpt'};
                   2098:     my $ngrade = $env{'form.NCT'};
                   2099:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2100:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2101:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2102: 
1.44      ng       2103:     if ($button eq 'Save & Next') {
                   2104: 	my $ctr = 0;
                   2105: 	while ($ctr < $ngrade) {
1.257     albertel 2106: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2107: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2108: 	    if ($errorflag eq 'no_score') {
                   2109: 		$ctr++;
                   2110: 		next;
                   2111: 	    }
1.104     albertel 2112: 	    if ($errorflag eq 'not_allowed') {
                   2113: 		$request->print("<font color=\"red\">Not allowed to modify grades for $uname:$udom</font>");
                   2114: 		$ctr++;
                   2115: 		next;
                   2116: 	    }
1.257     albertel 2117: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2118: 	    my ($subject,$message,$msgstatus) = ('','','');
1.62      albertel 2119: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2120: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2121: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.362     albertel 2122: 		$subject.=' ['.&Apache::lonnet::declutter($url).']';
1.44      ng       2123: 		my (@msgnum) = split(/,/,$includemsg);
                   2124: 		foreach (@msgnum) {
1.257     albertel 2125: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2126: 		}
1.80      ng       2127: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2128: 		if ($env{'form.withgrades'.$ctr}) {
                   2129: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
                   2130: 		    $message.=" for <a href=\"".
1.80      ng       2131: 		    &Apache::lonnet::clutter($url).
1.257     albertel 2132: 		    "?symb=$symb\">$env{'form.probTitle'}</a>";
1.298     www      2133: 		}
1.324     albertel 2134: 		$msgstatus = &Apache::lonmsg::user_normal_msg($uname,$udom,
1.362     albertel 2135: 							      $subject,
                   2136: 							      $message);
1.296     www      2137: 		$request->print('<br />'.&mt('Sending message to [_1]@[_2]',$uname,$udom).': '.
                   2138: 				$msgstatus);
1.44      ng       2139: 	    }
1.257     albertel 2140: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2141: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2142: 		foreach my $collabstr (@collabstrs) {
                   2143: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2144: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2145: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2146: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2147: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2148: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2149: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2150: 			    next;
                   2151: 			} else {
                   2152: 			    if ($message ne '') {
1.362     albertel 2153: 				$msgstatus = &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message);
1.150     albertel 2154: 			    }
1.104     albertel 2155: 			}
1.44      ng       2156: 		    }
                   2157: 		}
                   2158: 	    }
                   2159: 	    $ctr++;
                   2160: 	}
                   2161:     }
                   2162: 
1.257     albertel 2163:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2164: 	# Keywords sorted in alphabatical order
1.257     albertel 2165: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2166: 	my %keyhash = ();
1.257     albertel 2167: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2168: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2169: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2170: 	$env{'form.keywords'} = join(' ',@keywords);
                   2171: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2172: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2173: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2174: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2175: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2176: 
                   2177: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2178: 	# New messages are saved in env for the next student.
1.119     ng       2179: 	# All messages are saved in nohist_handgrade.db
                   2180: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2181: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2182: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2183: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2184: 		$idx++;
                   2185: 	    }
                   2186: 	    $ctr++;
1.41      ng       2187: 	}
1.119     ng       2188: 	$ctr = 0;
                   2189: 	while ($ctr < $ngrade) {
1.257     albertel 2190: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2191: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2192: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2193: 		$idx++;
                   2194: 	    }
                   2195: 	    $ctr++;
1.41      ng       2196: 	}
1.257     albertel 2197: 	$env{'form.savemsgN'} = --$idx;
                   2198: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2199: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2200: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2201:     }
1.44      ng       2202:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2203:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2204:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2205: 	my ($ctr,$total) = (0,0);
                   2206: 	while ($ctr < $ngrade) {
1.257     albertel 2207: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2208: 	    $ctr++;
                   2209: 	}
1.257     albertel 2210: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2211: 	$ctr = 0;
                   2212: 	while ($ctr < $total) {
1.257     albertel 2213: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2214: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2215: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2216: 	    &submission($request,$ctr,$total-1);
1.41      ng       2217: 	    $ctr++;
                   2218: 	}
                   2219: 	return '';
                   2220:     }
1.36      ng       2221: 
1.121     ng       2222: # Go directly to grade student - from submission or link from chart page
1.120     ng       2223:     if ($button eq 'Grade Student') {
1.324     albertel 2224: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2225: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2226: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2227: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2228: 	&submission($request,0,0);
                   2229: 	return '';
                   2230:     }
                   2231: 
1.44      ng       2232:     # Get the next/previous one or group of students
1.257     albertel 2233:     my $firststu = $env{'form.unamedom0'};
                   2234:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2235:     my $ctr = 2;
1.41      ng       2236:     while ($laststu eq '') {
1.257     albertel 2237: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2238: 	$ctr++;
                   2239: 	$laststu = $firststu if ($ctr > $ngrade);
                   2240:     }
1.44      ng       2241: 
1.41      ng       2242:     my (@parsedlist,@nextlist);
                   2243:     my ($nextflg) = 0;
1.294     albertel 2244:     foreach (sort 
                   2245: 	     {
                   2246: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2247: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2248: 		 }
                   2249: 		 return $a cmp $b;
                   2250: 	     } (keys(%$fullname))) {
1.41      ng       2251: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2252: 	    push @parsedlist,$_;
                   2253: 	}
                   2254: 	$nextflg = 1 if ($_ eq $laststu);
                   2255: 	if ($button eq 'Previous') {
                   2256: 	    last if ($_ eq $firststu);
                   2257: 	    push @parsedlist,$_;
                   2258: 	}
                   2259:     }
                   2260:     $ctr = 0;
                   2261:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2262:     my ($partlist) = &response_type($symb);
1.41      ng       2263:     foreach my $student (@parsedlist) {
1.257     albertel 2264: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2265: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2266: 	
                   2267: 	if ($submitonly eq 'queued') {
                   2268: 	    my %queue_status = 
                   2269: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2270: 							$udom,$uname);
                   2271: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2272: 	}
                   2273: 
1.156     albertel 2274: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2275: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2276: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2277: 	    my $submitted = 0;
1.248     albertel 2278: 	    my $ungraded = 0;
                   2279: 	    my $incorrect = 0;
1.145     albertel 2280: 	    foreach (keys(%status)) {
                   2281: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2282: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2283: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2284: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2285: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2286: 		    $submitted = 0;
                   2287: 		}
1.41      ng       2288: 	    }
1.156     albertel 2289: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2290: 				     $submitonly eq 'incorrect' ||
                   2291: 				     $submitonly eq 'graded'));
1.248     albertel 2292: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2293: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2294: 	}
                   2295: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2296: 	last if ($ctr == $ntstu);
1.41      ng       2297: 	$ctr++;
                   2298:     }
1.36      ng       2299: 
1.41      ng       2300:     $ctr = 0;
                   2301:     my $total = scalar(@nextlist)-1;
1.39      ng       2302: 
1.41      ng       2303:     foreach (sort @nextlist) {
                   2304: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2305: 	$env{'form.student'}  = $uname;
                   2306: 	$env{'form.userdom'}  = $udom;
                   2307: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2308: 	&submission($request,$ctr,$total);
                   2309: 	$ctr++;
                   2310:     }
                   2311:     if ($total < 0) {
                   2312: 	my $the_end = '<h3><font color="red">LON-CAPA User Message</font></h3><br />'."\n";
                   2313: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2314: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2315: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2316: 	$request->print($the_end);
                   2317:     }
                   2318:     return '';
1.38      ng       2319: }
1.36      ng       2320: 
1.44      ng       2321: #---- Save the score and award for each student, if changed
1.38      ng       2322: sub saveHandGrade {
1.324     albertel 2323:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2324:     my @version_parts;
1.104     albertel 2325:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2326: 					   $env{'request.course.id'});
1.104     albertel 2327:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2328:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2329:     my @parts_graded;
1.77      ng       2330:     my %newrecord  = ();
                   2331:     my ($pts,$wgt) = ('','');
1.269     raeburn  2332:     my %aggregate = ();
                   2333:     my $aggregateflag = 0;
1.301     albertel 2334:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2335:     foreach my $new_part (@parts) {
1.337     banghart 2336: 	#collaborator ($submi may vary for different parts
1.259     banghart 2337: 	if ($submitter && $new_part ne $part) { next; }
                   2338: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2339: 	if ($dropMenu eq 'excused') {
1.259     banghart 2340: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2341: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2342: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2343: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2344: 		}
1.364     banghart 2345: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2346: 	    }
1.125     ng       2347: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2348: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2349: 	    foreach my $key (keys (%record)) {
1.259     banghart 2350: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2351: 	    }
1.259     banghart 2352: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2353: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2354:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2355: 
                   2356:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2357: 					       [$new_part]);
                   2358:             my $aggtries =$totaltries;
1.269     raeburn  2359:             if ($last_resets{$new_part}) {
1.270     albertel 2360:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2361: 					   $new_part);
1.269     raeburn  2362:             }
1.270     albertel 2363: 
                   2364:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2365:             if ($aggtries > 0) {
1.327     albertel 2366:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2367:                 $aggregateflag = 1;
                   2368:             }
1.125     ng       2369: 	} elsif ($dropMenu eq '') {
1.259     banghart 2370: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2371: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2372: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2373: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2374: 		next;
                   2375: 	    }
1.259     banghart 2376: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2377: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2378: 	    my $partial= $pts/$wgt;
1.259     banghart 2379: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2380: 		#do not update score for part if not changed.
1.346     banghart 2381:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2382: 		next;
1.251     banghart 2383: 	    } else {
1.259     banghart 2384: 	        push @parts_graded, $new_part;
1.153     albertel 2385: 	    }
1.259     banghart 2386: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2387: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2388: 	    }
1.259     banghart 2389: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2390: 	    if ($partial == 0) {
1.153     albertel 2391: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2392: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2393: 		}
1.41      ng       2394: 	    } else {
1.153     albertel 2395: 		if ($record{$reckey} ne 'correct_by_override') {
                   2396: 		    $newrecord{$reckey} = 'correct_by_override';
                   2397: 		}
                   2398: 	    }	    
                   2399: 	    if ($submitter && 
1.259     banghart 2400: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2401: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2402: 	    }
1.259     banghart 2403: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2404: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2405: 	}
1.259     banghart 2406: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2407: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2408: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2409: 	        $dropMenu eq 'reset status')
                   2410: 	   {
1.342     banghart 2411: 	    push (@version_parts,$new_part);
1.259     banghart 2412: 	}
1.41      ng       2413:     }
1.301     albertel 2414:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2415:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2416: 
1.344     albertel 2417:     if (%newrecord) {
                   2418:         if (@version_parts) {
1.364     banghart 2419:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2420:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2421: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2422: 	    foreach my $new_part (@version_parts) {
                   2423: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2424: 				$new_part,\%newrecord);
                   2425: 	    }
1.259     banghart 2426:         }
1.44      ng       2427: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2428: 				$env{'request.course.id'},$domain,$stuname);
1.380     albertel 2429: 	&check_and_remove_from_queue(\@parts,\%record,\%newrecord,$symb,
                   2430: 				     $cdom,$cnum,$domain,$stuname);
1.41      ng       2431:     }
1.269     raeburn  2432:     if ($aggregateflag) {
                   2433:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2434: 			      $cdom,$cnum);
1.269     raeburn  2435:     }
1.301     albertel 2436:     return ('',$pts,$wgt);
1.36      ng       2437: }
1.322     albertel 2438: 
1.380     albertel 2439: sub check_and_remove_from_queue {
                   2440:     my ($parts,$record,$newrecord,$symb,$cdom,$cnum,$domain,$stuname) = @_;
                   2441:     my @ungraded_parts;
                   2442:     foreach my $part (@{$parts}) {
                   2443: 	if (    $record->{   'resource.'.$part.'.awarded'} eq ''
                   2444: 	     && $record->{   'resource.'.$part.'.solved' } ne 'excused'
                   2445: 	     && $newrecord->{'resource.'.$part.'.awarded'} eq ''
                   2446: 	     && $newrecord->{'resource.'.$part.'.solved' } ne 'excused'
                   2447: 		) {
                   2448: 	    push(@ungraded_parts, $part);
                   2449: 	}
                   2450:     }
                   2451:     if ( !@ungraded_parts ) {
                   2452: 	&Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2453: 					       $cnum,$domain,$stuname);
                   2454:     }
                   2455: }
                   2456: 
1.337     banghart 2457: sub handback_files {
                   2458:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2459:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2460:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2461: 
                   2462:     my @part_response_id = &flatten_responseType($responseType);
                   2463:     foreach my $part_response_id (@part_response_id) {
                   2464:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2465: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2466:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2467:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2468:                 my $file_counter = 1;
1.367     albertel 2469: 		my $file_msg;
1.337     banghart 2470:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2471:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2472:                     my ($directory,$answer_file) = 
                   2473:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2474:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2475: 		        &file_name_version_ext($answer_file);
1.355     banghart 2476: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2477: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2478: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2479:                     # fix file name
                   2480:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2481:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2482:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2483:             	                                $save_file_name);
1.337     banghart 2484:                     if ($result !~ m|^/uploaded/|) {
                   2485:                         $request->print('<font color="red"> An errror occured ('.$result.
1.355     banghart 2486:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</font><br />');
1.356     banghart 2487:                     } else {
1.360     banghart 2488:                         # mark the file as read only
                   2489:                         my @files = ($save_file_name);
1.372     albertel 2490:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2491:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2492: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2493: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2494: 			}
                   2495:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2496: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2497: 
1.337     banghart 2498:                     }
                   2499:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2500:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2501:                     $file_counter++;
                   2502:                 }
1.367     albertel 2503: 		my $subject = "File Handed Back by Instructor ";
                   2504: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2505: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2506: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2507: 		$message .= " and can be found in your portfolio space.";
                   2508: 		my $url = (&Apache::lonnet::decode_symb($symb))[2];
                   2509: 		$url = &Apache::lonnet::declutter($url);
                   2510: 		my $msgstatus = &Apache::lonmsg::user_normal_msg($stuname,$domain,
                   2511: 								 $subject.' (File Returned) ['.$url.']',$message);                    
                   2512: 
1.337     banghart 2513:             }
                   2514:         }
1.338     banghart 2515:     return;
1.337     banghart 2516: }
                   2517: 
1.313     banghart 2518: sub get_submitted_files {
                   2519:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2520:     my @files;
                   2521:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2522:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2523:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2524:     	    push(@files,$file_url.$file);
                   2525:         }
                   2526:     }
                   2527:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2528:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2529:     }
                   2530:     return (\@files);
                   2531: }
1.322     albertel 2532: 
1.269     raeburn  2533: # ----------- Provides number of tries since last reset.
                   2534: sub get_num_tries {
                   2535:     my ($record,$last_reset,$part) = @_;
                   2536:     my $timestamp = '';
                   2537:     my $num_tries = 0;
                   2538:     if ($$record{'version'}) {
                   2539:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2540:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2541:                 $timestamp = $$record{$version.':timestamp'};
                   2542:                 if ($timestamp > $last_reset) {
                   2543:                     $num_tries ++;
                   2544:                 } else {
                   2545:                     last;
                   2546:                 }
                   2547:             }
                   2548:         }
                   2549:     }
                   2550:     return $num_tries;
                   2551: }
                   2552: 
                   2553: # ----------- Determine decrements required in aggregate totals 
                   2554: sub decrement_aggs {
                   2555:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2556:     my %decrement = (
                   2557:                         attempts => 0,
                   2558:                         users => 0,
                   2559:                         correct => 0
                   2560:                     );
                   2561:     $decrement{'attempts'} = $aggtries;
                   2562:     if ($solvedstatus =~ /^correct/) {
                   2563:         $decrement{'correct'} = 1;
                   2564:     }
                   2565:     if ($aggtries == $totaltries) {
                   2566:         $decrement{'users'} = 1;
                   2567:     }
                   2568:     foreach my $type (keys (%decrement)) {
                   2569:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2570:     }
                   2571:     return;
                   2572: }
                   2573: 
                   2574: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2575: sub get_last_resets {
1.270     albertel 2576:     my ($symb,$courseid,$partids) =@_;
                   2577:     my %last_resets;
1.269     raeburn  2578:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2579:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2580:     my @keys;
                   2581:     foreach my $part (@{$partids}) {
                   2582: 	push(@keys,"$symb\0$part\0resettime");
                   2583:     }
                   2584:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2585: 				     $cdom,$cname);
                   2586:     foreach my $part (@{$partids}) {
                   2587: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2588:     }
1.270     albertel 2589:     return %last_resets;
1.269     raeburn  2590: }
                   2591: 
1.251     banghart 2592: # ----------- Handles creating versions for portfolio files as answers
                   2593: sub version_portfiles {
1.343     banghart 2594:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2595:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2596:     my @returned_keys;
1.255     banghart 2597:     my $parts = join('|', @$parts_graded);
1.359     www      2598:     my $portfolio_root = &propath($domain,$stu_name).
                   2599: 	'/userfiles/portfolio';
1.277     albertel 2600:     foreach my $key (keys(%$record)) {
1.259     banghart 2601:         my $new_portfiles;
1.263     banghart 2602:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2603:             my @versioned_portfiles;
1.367     albertel 2604:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2605:             foreach my $file (@portfiles) {
1.306     banghart 2606:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2607:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2608: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2609: 		    &file_name_version_ext($answer_file);
1.306     banghart 2610:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2611:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2612:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2613:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2614:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2615:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2616:                         [$directory.$new_answer],
1.306     banghart 2617:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2618:                 }
1.252     banghart 2619:             }
1.343     banghart 2620:             $$record{$key} = join(',',@versioned_portfiles);
                   2621:             push(@returned_keys,$key);
1.251     banghart 2622:         }
                   2623:     } 
1.343     banghart 2624:     return (@returned_keys);   
1.305     banghart 2625: }
                   2626: 
1.307     banghart 2627: sub get_next_version {
1.341     banghart 2628:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2629:     my $version;
                   2630:     foreach my $row (@$dir_list) {
                   2631:         my ($file) = split(/\&/,$row,2);
                   2632:         my ($file_name,$file_version,$file_ext) =
                   2633: 	    &file_name_version_ext($file);
                   2634:         if (($file_name eq $answer_name) && 
                   2635: 	    ($file_ext eq $answer_ext)) {
                   2636:                 # gets here if filename and extension match, regardless of version
                   2637:                 if ($file_version ne '') {
                   2638:                 # a versioned file is found  so save it for later
                   2639:                 if ($file_version > $version) {
                   2640: 		    $version = $file_version;
                   2641: 	        }
                   2642:             }
                   2643:         }
                   2644:     } 
                   2645:     $version ++;
                   2646:     return($version);
                   2647: }
                   2648: 
1.305     banghart 2649: sub version_selected_portfile {
1.306     banghart 2650:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2651:     my ($answer_name,$answer_ver,$answer_ext) =
                   2652:         &file_name_version_ext($file_name);
                   2653:     my $new_answer;
                   2654:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2655:     if($env{'form.copy'} eq '-1') {
                   2656:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2657:         $new_answer = 'problem getting file';
                   2658:     } else {
                   2659:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2660:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2661:                             $stu_name,$domain,'copy',
                   2662: 		        '/portfolio'.$directory.$new_answer);
                   2663:     }    
                   2664:     return ($new_answer);
1.251     banghart 2665: }
                   2666: 
1.304     albertel 2667: sub file_name_version_ext {
                   2668:     my ($file)=@_;
                   2669:     my @file_parts = split(/\./, $file);
                   2670:     my ($name,$version,$ext);
                   2671:     if (@file_parts > 1) {
                   2672: 	$ext=pop(@file_parts);
                   2673: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2674: 	    $version=pop(@file_parts);
                   2675: 	}
                   2676: 	$name=join('.',@file_parts);
                   2677:     } else {
                   2678: 	$name=join('.',@file_parts);
                   2679:     }
                   2680:     return($name,$version,$ext);
                   2681: }
                   2682: 
1.44      ng       2683: #--------------------------------------------------------------------------------------
                   2684: #
                   2685: #-------------------------- Next few routines handles grading by section or whole class
                   2686: #
                   2687: #--- Javascript to handle grading by section or whole class
1.42      ng       2688: sub viewgrades_js {
                   2689:     my ($request) = shift;
                   2690: 
1.41      ng       2691:     $request->print(<<VIEWJAVASCRIPT);
                   2692: <script type="text/javascript" language="javascript">
1.45      ng       2693:    function writePoint(partid,weight,point) {
1.125     ng       2694: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2695: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2696: 	if (point == "textval") {
1.125     ng       2697: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2698: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2699: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2700: 		var resetbox = false;
                   2701: 		for (var i=0; i<radioButton.length; i++) {
                   2702: 		    if (radioButton[i].checked) {
                   2703: 			textbox.value = i;
                   2704: 			resetbox = true;
                   2705: 		    }
                   2706: 		}
                   2707: 		if (!resetbox) {
                   2708: 		    textbox.value = "";
                   2709: 		}
                   2710: 		return;
                   2711: 	    }
1.109     matthew  2712: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2713: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2714: 				   ") greater than the weight for the part. Accept?");
                   2715: 		if (resp == false) {
                   2716: 		    textbox.value = "";
                   2717: 		    return;
                   2718: 		}
                   2719: 	    }
1.42      ng       2720: 	    for (var i=0; i<radioButton.length; i++) {
                   2721: 		radioButton[i].checked=false;
1.109     matthew  2722: 		if (parseFloat(point) == i) {
1.42      ng       2723: 		    radioButton[i].checked=true;
                   2724: 		}
                   2725: 	    }
1.41      ng       2726: 
1.42      ng       2727: 	} else {
1.125     ng       2728: 	    textbox.value = parseFloat(point);
1.42      ng       2729: 	}
1.41      ng       2730: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2731: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2732: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2733: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2734: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2735: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2736: 	    if (saveval != "correct") {
                   2737: 		scorename.value = point;
1.43      ng       2738: 		if (selname[0].selected != true) {
                   2739: 		    selname[0].selected = true;
                   2740: 		}
1.42      ng       2741: 	    }
                   2742: 	}
1.125     ng       2743: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2744:     }
                   2745: 
                   2746:     function writeRadText(partid,weight) {
1.125     ng       2747: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2748: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2749:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2750: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2751: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2752: 	    for (var i=0; i<radioButton.length; i++) {
                   2753: 		radioButton[i].checked=false;
                   2754: 
                   2755: 	    }
                   2756: 	    textbox.value = "";
                   2757: 
                   2758: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2759: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2760: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2761: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2762: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2763: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2764: 		if ((saveval != "correct") || override) {
1.42      ng       2765: 		    scorename.value = "";
1.125     ng       2766: 		    if (selval[1].selected) {
                   2767: 			selname[1].selected = true;
                   2768: 		    } else {
                   2769: 			selname[2].selected = true;
                   2770: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2771: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2772: 		    }
1.42      ng       2773: 		}
                   2774: 	    }
1.43      ng       2775: 	} else {
                   2776: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2777: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2778: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2779: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2780: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2781: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2782: 		if ((saveval != "correct") || override) {
1.125     ng       2783: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2784: 		    selname[0].selected = true;
                   2785: 		}
                   2786: 	    }
                   2787: 	}	    
1.42      ng       2788:     }
                   2789: 
                   2790:     function changeSelect(partid,user) {
1.125     ng       2791: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2792: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2793: 	var point  = textbox.value;
1.125     ng       2794: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2795: 
1.109     matthew  2796: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2797: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2798: 	    textbox.value = "";
                   2799: 	    return;
                   2800: 	}
1.109     matthew  2801: 	if (parseFloat(point) > parseFloat(weight)) {
                   2802: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2803: 			       ") greater than the weight of the part. Accept?");
                   2804: 	    if (resp == false) {
                   2805: 		textbox.value = "";
                   2806: 		return;
                   2807: 	    }
                   2808: 	}
1.42      ng       2809: 	selval[0].selected = true;
                   2810:     }
                   2811: 
                   2812:     function changeOneScore(partid,user) {
1.125     ng       2813: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2814: 	if (selval[1].selected || selval[2].selected) {
                   2815: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2816: 	    if (selval[2].selected) {
                   2817: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2818: 	    }
1.269     raeburn  2819:         }
1.42      ng       2820:     }
                   2821: 
                   2822:     function resetEntry(numpart) {
                   2823: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2824: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2825: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2826: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2827: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2828: 	    for (var i=0; i<radioButton.length; i++) {
                   2829: 		radioButton[i].checked=false;
                   2830: 
                   2831: 	    }
                   2832: 	    textbox.value = "";
                   2833: 	    selval[0].selected = true;
                   2834: 
                   2835: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2836: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2837: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2838: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2839: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2840: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2841: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2842: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2843: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2844: 		if (saveselval == "excused") {
1.43      ng       2845: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2846: 		} else {
1.43      ng       2847: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2848: 		}
                   2849: 	    }
1.41      ng       2850: 	}
1.42      ng       2851:     }
                   2852: 
1.41      ng       2853: </script>
                   2854: VIEWJAVASCRIPT
1.42      ng       2855: }
                   2856: 
1.44      ng       2857: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2858: sub viewgrades {
                   2859:     my ($request) = shift;
                   2860:     &viewgrades_js($request);
1.41      ng       2861: 
1.324     albertel 2862:     my ($symb) = &get_symb($request);
1.168     albertel 2863:     #need to make sure we have the correct data for later EXT calls, 
                   2864:     #thus invalidate the cache
                   2865:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2866:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2867:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2868:     &Apache::lonnet::clear_EXT_cache_status();
                   2869: 
1.167     sakharuk 2870:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
1.257     albertel 2871:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
1.41      ng       2872: 
                   2873:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2874:     $result.=&jscriptNform($symb);
1.41      ng       2875: 
1.44      ng       2876:     #beginning of class grading form
1.41      ng       2877:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2878: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2879: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2880: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2881: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2882: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2883: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2884: 
1.126     ng       2885:     my $sectionClass;
1.257     albertel 2886:     if ($env{'form.section'} eq 'all') {
1.126     ng       2887: 	$sectionClass='Class </h3>';
1.257     albertel 2888:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2889: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2890:     } else {
1.257     albertel 2891: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2892:     }
1.126     ng       2893:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2894:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2895: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2896:     #radio buttons/text box for assigning points for a section or class.
                   2897:     #handles different parts of a problem
1.375     albertel 2898:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2899:     my %weight = ();
                   2900:     my $ctsparts = 0;
1.41      ng       2901:     $result.='<table border="0">';
1.45      ng       2902:     my %seen = ();
1.375     albertel 2903:     my @part_response_id = &flatten_responseType($responseType);
                   2904:     foreach my $part_response_id (@part_response_id) {
                   2905:     	my ($partid,$respid) = @{ $part_response_id };
                   2906: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       2907: 	next if $seen{$partid};
                   2908: 	$seen{$partid}++;
1.375     albertel 2909: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       2910: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2911: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   2912: 
1.44      ng       2913: 	$result.='<input type="hidden" name="partid_'.
                   2914: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   2915: 	$result.='<input type="hidden" name="weight_'.
                   2916: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 2917: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 2918: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       2919: 	$result.='<table border="0"><tr>';  
1.41      ng       2920: 	my $ctr = 0;
1.42      ng       2921: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 2922: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 2923: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 2924: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       2925: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   2926: 	    $ctr++;
                   2927: 	}
                   2928: 	$result.='</tr></table>';
1.44      ng       2929: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 2930: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   2931: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       2932: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   2933: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 2934: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 2935: 		$weight{$partid}.')"> '.
1.42      ng       2936: 	    '<option selected="on"> </option>'.
1.125     ng       2937: 	    '<option>excused</option>'.
1.265     www      2938: 	    '<option>reset status</option></select></td>'.
1.266     albertel 2939:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       2940: 	$ctsparts++;
1.41      ng       2941:     }
1.52      albertel 2942:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   2943: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.42      ng       2944:     $result.='<input type="button" value="Reset" '.
1.111     ng       2945: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       2946: 
1.44      ng       2947:     #table listing all the students in a section/class
                   2948:     #header of table
1.126     ng       2949:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       2950:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       2951: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       2952: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 2953:     my (@parts) = sort(&getpartlist($symb));
                   2954:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  2955:     my @partids = ();
1.41      ng       2956:     foreach my $part (@parts) {
                   2957: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       2958: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       2959: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 2960: 	my ($partid) = &split_part_type($part);
1.269     raeburn  2961:         push(@partids, $partid);
1.324     albertel 2962: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       2963: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 2964: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   2965: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       2966: 	    next;
1.207     albertel 2967: 	} else {
                   2968: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       2969: 	}
1.53      albertel 2970: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 2971: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       2972:     }
                   2973:     $result.='</tr>';
1.44      ng       2974: 
1.270     albertel 2975:     my %last_resets = 
                   2976: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  2977: 
1.41      ng       2978:     #get info for each student
1.44      ng       2979:     #list all the students - with points and grade status
1.257     albertel 2980:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       2981:     my $ctr = 0;
1.294     albertel 2982:     foreach (sort 
                   2983: 	     {
                   2984: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2985: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2986: 		 }
                   2987: 		 return $a cmp $b;
                   2988: 	     } (keys(%$fullname))) {
1.126     ng       2989: 	$ctr++;
1.324     albertel 2990: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  2991: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       2992:     }
                   2993:     $result.='</table></td></tr></table>';
                   2994:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       2995:     $result.='<input type="button" value="Save" '.
1.45      ng       2996: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 2997:     if (scalar(%$fullname) eq 0) {
                   2998: 	my $colspan=3+scalar(@parts);
1.257     albertel 2999: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
                   3000: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
1.96      albertel 3001:     }
1.324     albertel 3002:     $result.=&show_grading_menu_form($symb);
1.41      ng       3003:     return $result;
                   3004: }
                   3005: 
1.44      ng       3006: #--- call by previous routine to display each student
1.41      ng       3007: sub viewstudentgrade {
1.324     albertel 3008:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       3009:     my ($uname,$udom) = split(/:/,$student);
                   3010:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  3011:     my %aggregates = (); 
1.233     albertel 3012:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   3013: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   3014: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3015: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       3016: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.257     albertel 3017: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
1.281     albertel 3018:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3019:     foreach my $apart (@$parts) {
                   3020: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3021: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3022:         $result.='<td align="center">';
1.269     raeburn  3023:         my ($aggtries,$totaltries);
                   3024:         unless (exists($aggregates{$part})) {
1.270     albertel 3025: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3026: 
                   3027: 	    $aggtries = $totaltries;
1.269     raeburn  3028:             if ($$last_resets{$part}) {  
1.270     albertel 3029:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3030: 					   $part);
                   3031:             }
1.269     raeburn  3032:             $result.='<input type="hidden" name="'.
                   3033:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3034:             $result.='<input type="hidden" name="'.
                   3035:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3036:             $aggregates{$part} = 1;
                   3037:         }
1.41      ng       3038: 	if ($type eq 'awarded') {
1.320     albertel 3039: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3040: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3041: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3042: 	    $result.='<input type="text" name="'.
1.89      albertel 3043: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3044: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3045: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3046: 	} elsif ($type eq 'solved') {
                   3047: 	    my ($status,$foo)=split(/_/,$score,2);
                   3048: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3049: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3050: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3051: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3052: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3053: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       3054: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   3055: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   3056: 	    $result.='<option>reset status</option>';
1.126     ng       3057: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3058: 	} else {
                   3059: 	    $result.='<input type="hidden" name="'.
                   3060: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3061: 		    "\n";
1.233     albertel 3062: 	    $result.='<input type="text" name="'.
1.122     ng       3063: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3064: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3065: 	}
                   3066:     }
                   3067:     $result.='</tr>';
                   3068:     return $result;
1.38      ng       3069: }
                   3070: 
1.44      ng       3071: #--- change scores for all the students in a section/class
                   3072: #    record does not get update if unchanged
1.38      ng       3073: sub editgrades {
1.41      ng       3074:     my ($request) = @_;
                   3075: 
1.324     albertel 3076:     my $symb=&get_symb($request);
1.45      ng       3077:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
1.257     albertel 3078:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
                   3079:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
1.126     ng       3080: 
1.44      ng       3081:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3082:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3083: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3084: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3085: 
                   3086:     my %scoreptr = (
                   3087: 		    'correct'  =>'correct_by_override',
                   3088: 		    'incorrect'=>'incorrect_by_override',
                   3089: 		    'excused'  =>'excused',
                   3090: 		    'ungraded' =>'ungraded_attempted',
                   3091: 		    'nothing'  => '',
                   3092: 		    );
1.257     albertel 3093:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3094: 
1.44      ng       3095:     my (@partid);
                   3096:     my %weight = ();
1.54      albertel 3097:     my %columns = ();
1.44      ng       3098:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3099: 
1.324     albertel 3100:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3101:     my $header;
1.257     albertel 3102:     while ($ctr < $env{'form.totalparts'}) {
                   3103: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3104: 	push @partid,$partid;
1.257     albertel 3105: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3106: 	$ctr++;
1.54      albertel 3107:     }
1.324     albertel 3108:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3109:     foreach my $partid (@partid) {
                   3110: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3111: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3112: 	$columns{$partid}=2;
                   3113: 	foreach my $stores (@parts) {
                   3114: 	    my ($part,$type) = &split_part_type($stores);
                   3115: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3116: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3117: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3118: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3119: 	    $display =~ s/Number of Attempts/Tries/;
                   3120: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3121: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3122: 	    $columns{$partid}+=2;
                   3123: 	}
                   3124:     }
                   3125:     foreach my $partid (@partid) {
1.324     albertel 3126: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3127: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3128: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3129: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3130: 
1.44      ng       3131:     }
                   3132:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3133:     $result .= $header;
1.44      ng       3134:     $result .= '</tr>'."\n";
1.93      albertel 3135:     my $noupdate;
1.126     ng       3136:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3137:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3138: 	my $line;
1.257     albertel 3139: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3140: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3141: 	my %newrecord;
                   3142: 	my $updateflag = 0;
1.281     albertel 3143: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3144: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3145: 	if (!&canmodify($usec)) {
1.126     ng       3146: 	    my $numcols=scalar(@partid)*4+2;
1.105     albertel 3147: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
                   3148: 	    next;
                   3149: 	}
1.269     raeburn  3150:         my %aggregate = ();
                   3151:         my $aggregateflag = 0;
1.281     albertel 3152: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3153: 	foreach (@partid) {
1.257     albertel 3154: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3155: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3156: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3157: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3158: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3159: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3160: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3161: 	    my $score;
                   3162: 	    if ($partial eq '') {
1.257     albertel 3163: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3164: 	    } elsif ($partial > 0) {
                   3165: 		$score = 'correct_by_override';
                   3166: 	    } elsif ($partial == 0) {
                   3167: 		$score = 'incorrect_by_override';
                   3168: 	    }
1.257     albertel 3169: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3170: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3171: 
1.292     albertel 3172: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3173: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3174: 	    if ($dropMenu eq 'reset status' &&
                   3175: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3176: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3177: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3178: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3179: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3180: 		$updateflag = 1;
1.269     raeburn  3181:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3182:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3183:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3184:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3185:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3186:                     $aggregateflag = 1;
                   3187:                 }
1.139     albertel 3188: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3189: 		$updateflag = 1;
                   3190: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3191: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3192: 		$rec_update++;
1.125     ng       3193: 	    }
                   3194: 
1.93      albertel 3195: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3196: 		'<td align="center">'.$awarded.
                   3197: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3198: 
1.54      albertel 3199: 
                   3200: 	    my $partid=$_;
                   3201: 	    foreach my $stores (@parts) {
                   3202: 		my ($part,$type) = &split_part_type($stores);
                   3203: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3204: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3205: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3206: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3207: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3208: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3209: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3210: 		    $updateflag=1;
                   3211: 		}
1.93      albertel 3212: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3213: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3214: 	    }
1.44      ng       3215: 	}
1.93      albertel 3216: 	$line.='</tr>'."\n";
1.301     albertel 3217: 
                   3218: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3219: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3220: 
1.44      ng       3221: 	if ($updateflag) {
                   3222: 	    $count++;
1.257     albertel 3223: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3224: 				    $udom,$uname);
1.301     albertel 3225: 
                   3226: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3227: 					      $cnum,$udom,$uname)) {
                   3228: 		# need to figure out if should be in queue.
                   3229: 		my %record =  
                   3230: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3231: 					     $udom,$uname);
                   3232: 		my $all_graded = 1;
                   3233: 		my $none_graded = 1;
                   3234: 		foreach my $part (@parts) {
                   3235: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3236: 			$all_graded = 0;
                   3237: 		    } else {
                   3238: 			$none_graded = 0;
                   3239: 		    }
                   3240: 		}
                   3241: 
                   3242: 		if ($all_graded || $none_graded) {
                   3243: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3244: 							   $symb,$cdom,$cnum,
                   3245: 							   $udom,$uname);
                   3246: 		}
                   3247: 	    }
                   3248: 
1.126     ng       3249: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3250: 	    $updateCtr++;
1.93      albertel 3251: 	} else {
1.126     ng       3252: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3253: 	    $noupdateCtr++;
1.44      ng       3254: 	}
1.269     raeburn  3255:         if ($aggregateflag) {
                   3256:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3257: 				  $cdom,$cnum);
1.269     raeburn  3258:         }
1.93      albertel 3259:     }
                   3260:     if ($noupdate) {
1.126     ng       3261: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3262: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3263: 	$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       3264:     }
1.72      ng       3265:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3266: 	&show_grading_menu_form ($symb);
1.125     ng       3267:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3268: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3269: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3270:     return $title.$msg.$result;
1.5       albertel 3271: }
1.54      albertel 3272: 
                   3273: sub split_part_type {
                   3274:     my ($partstr) = @_;
                   3275:     my ($temp,@allparts)=split(/_/,$partstr);
                   3276:     my $type=pop(@allparts);
                   3277:     my $part=join('.',@allparts);
                   3278:     return ($part,$type);
                   3279: }
                   3280: 
1.44      ng       3281: #------------- end of section for handling grading by section/class ---------
                   3282: #
                   3283: #----------------------------------------------------------------------------
                   3284: 
1.5       albertel 3285: 
1.44      ng       3286: #----------------------------------------------------------------------------
                   3287: #
                   3288: #-------------------------- Next few routines handles grading by csv upload
                   3289: #
                   3290: #--- Javascript to handle csv upload
1.27      albertel 3291: sub csvupload_javascript_reverse_associate {
1.246     albertel 3292:     my $error1=&mt('You need to specify the username or ID');
                   3293:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3294:   return(<<ENDPICK);
                   3295:   function verify(vf) {
                   3296:     var foundsomething=0;
                   3297:     var founduname=0;
1.243     albertel 3298:     var foundID=0;
1.27      albertel 3299:     for (i=0;i<=vf.nfields.value;i++) {
                   3300:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3301:       if (i==0 && tw!=0) { foundID=1; }
                   3302:       if (i==1 && tw!=0) { founduname=1; }
                   3303:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3304:     }
1.246     albertel 3305:     if (founduname==0 && foundID==0) {
                   3306: 	alert('$error1');
                   3307: 	return;
1.27      albertel 3308:     }
                   3309:     if (foundsomething==0) {
1.246     albertel 3310: 	alert('$error2');
                   3311: 	return;
1.27      albertel 3312:     }
                   3313:     vf.submit();
                   3314:   }
                   3315:   function flip(vf,tf) {
                   3316:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3317:     var i;
                   3318:     for (i=0;i<=vf.nfields.value;i++) {
                   3319:       //can not pick the same destination field for both name and domain
                   3320:       if (((i ==0)||(i ==1)) && 
                   3321:           ((tf==0)||(tf==1)) && 
                   3322:           (i!=tf) &&
                   3323:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3324:         eval('vf.f'+i+'.selectedIndex=0;')
                   3325:       }
                   3326:     }
                   3327:   }
                   3328: ENDPICK
                   3329: }
                   3330: 
                   3331: sub csvupload_javascript_forward_associate {
1.246     albertel 3332:     my $error1=&mt('You need to specify the username or ID');
                   3333:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3334:   return(<<ENDPICK);
                   3335:   function verify(vf) {
                   3336:     var foundsomething=0;
                   3337:     var founduname=0;
1.243     albertel 3338:     var foundID=0;
1.27      albertel 3339:     for (i=0;i<=vf.nfields.value;i++) {
                   3340:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3341:       if (tw==1) { foundID=1; }
                   3342:       if (tw==2) { founduname=1; }
                   3343:       if (tw>3) { foundsomething=1; }
1.27      albertel 3344:     }
1.246     albertel 3345:     if (founduname==0 && foundID==0) {
                   3346: 	alert('$error1');
                   3347: 	return;
1.27      albertel 3348:     }
                   3349:     if (foundsomething==0) {
1.246     albertel 3350: 	alert('$error2');
                   3351: 	return;
1.27      albertel 3352:     }
                   3353:     vf.submit();
                   3354:   }
                   3355:   function flip(vf,tf) {
                   3356:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3357:     var i;
                   3358:     //can not pick the same destination field twice
                   3359:     for (i=0;i<=vf.nfields.value;i++) {
                   3360:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3361:         eval('vf.f'+i+'.selectedIndex=0;')
                   3362:       }
                   3363:     }
                   3364:   }
                   3365: ENDPICK
                   3366: }
                   3367: 
1.26      albertel 3368: sub csvuploadmap_header {
1.324     albertel 3369:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3370:     my $javascript;
1.257     albertel 3371:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3372: 	$javascript=&csvupload_javascript_reverse_associate();
                   3373:     } else {
                   3374: 	$javascript=&csvupload_javascript_forward_associate();
                   3375:     }
1.45      ng       3376: 
1.324     albertel 3377:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3378:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3379:     my $ignore=&mt('Ignore First Line');
1.41      ng       3380:     $request->print(<<ENDPICK);
1.26      albertel 3381: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.45      ng       3382: <h3><font color="#339933">Uploading Class Grades</font></h3>
                   3383: $result
1.326     albertel 3384: <hr />
1.26      albertel 3385: <h3>Identify fields</h3>
                   3386: Total number of records found in file: $distotal <hr />
                   3387: Enter as many fields as you can. The system will inform you and bring you back
                   3388: to this page if the data selected is insufficient to run your class.<hr />
                   3389: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3390: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3391: <input type="hidden" name="associate"  value="" />
                   3392: <input type="hidden" name="phase"      value="three" />
                   3393: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3394: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3395: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3396: <input type="hidden" name="upfile_associate" 
1.257     albertel 3397:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3398: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3399: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3400: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3401: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3402: <hr />
                   3403: <script type="text/javascript" language="Javascript">
                   3404: $javascript
                   3405: </script>
                   3406: ENDPICK
1.118     ng       3407:     return '';
1.26      albertel 3408: 
                   3409: }
                   3410: 
                   3411: sub csvupload_fields {
1.324     albertel 3412:     my ($symb) = @_;
                   3413:     my (@parts) = &getpartlist($symb);
1.243     albertel 3414:     my @fields=(['ID','Student ID'],
                   3415: 		['username','Student Username'],
                   3416: 		['domain','Student Domain']);
1.324     albertel 3417:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3418:     foreach my $part (sort(@parts)) {
                   3419: 	my @datum;
                   3420: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3421: 	my $name=$part;
                   3422: 	if  (!$display) { $display = $name; }
                   3423: 	@datum=($name,$display);
1.244     albertel 3424: 	if ($name=~/^stores_(.*)_awarded/) {
                   3425: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3426: 	}
1.41      ng       3427: 	push(@fields,\@datum);
                   3428:     }
                   3429:     return (@fields);
1.26      albertel 3430: }
                   3431: 
                   3432: sub csvuploadmap_footer {
1.41      ng       3433:     my ($request,$i,$keyfields) =@_;
                   3434:     $request->print(<<ENDPICK);
1.26      albertel 3435: </table>
                   3436: <input type="hidden" name="nfields" value="$i" />
                   3437: <input type="hidden" name="keyfields" value="$keyfields" />
                   3438: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3439: </form>
                   3440: ENDPICK
                   3441: }
                   3442: 
1.283     albertel 3443: sub checkforfile_js {
1.86      ng       3444:     my $result =<<CSVFORMJS;
                   3445: <script type="text/javascript" language="javascript">
                   3446:     function checkUpload(formname) {
                   3447: 	if (formname.upfile.value == "") {
                   3448: 	    alert("Please use the browse button to select a file from your local directory.");
                   3449: 	    return false;
                   3450: 	}
                   3451: 	formname.submit();
                   3452:     }
                   3453:     </script>
                   3454: CSVFORMJS
1.283     albertel 3455:     return $result;
                   3456: }
                   3457: 
                   3458: sub upcsvScores_form {
                   3459:     my ($request) = shift;
1.324     albertel 3460:     my ($symb)=&get_symb($request);
1.283     albertel 3461:     if (!$symb) {return '';}
                   3462:     my $result=&checkforfile_js();
1.257     albertel 3463:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3464:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3465:     $result.=$table;
1.326     albertel 3466:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3467:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3468:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3469: 	'.</b></td></tr>'."\n";
                   3470:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3471:     my $upload=&mt("Upload Scores");
1.86      ng       3472:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3473:     my $ignore=&mt('Ignore First Line');
1.86      ng       3474:     $result.=<<ENDUPFORM;
1.106     albertel 3475: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3476: <input type="hidden" name="symb" value="$symb" />
                   3477: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3478: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3479: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3480: $upfile_select
1.370     www      3481: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3482: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3483: </form>
                   3484: ENDUPFORM
1.370     www      3485:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3486:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3487:     .'</td></tr></table>'."\n";
1.86      ng       3488:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3489:     $result.=&show_grading_menu_form($symb);
1.86      ng       3490:     return $result;
                   3491: }
                   3492: 
                   3493: 
1.26      albertel 3494: sub csvuploadmap {
1.41      ng       3495:     my ($request)= @_;
1.324     albertel 3496:     my ($symb)=&get_symb($request);
1.41      ng       3497:     if (!$symb) {return '';}
1.72      ng       3498: 
1.41      ng       3499:     my $datatoken;
1.257     albertel 3500:     if (!$env{'form.datatoken'}) {
1.41      ng       3501: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3502:     } else {
1.257     albertel 3503: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3504: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3505:     }
1.41      ng       3506:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3507:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3508:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3509:     my ($i,$keyfields);
                   3510:     if (@records) {
1.324     albertel 3511: 	my @fields=&csvupload_fields($symb);
1.45      ng       3512: 
1.257     albertel 3513: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3514: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3515: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3516: 							  \@fields);
                   3517: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3518: 	    chop($keyfields);
                   3519: 	} else {
                   3520: 	    unshift(@fields,['none','']);
                   3521: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3522: 							    \@fields);
1.311     banghart 3523:             foreach my $rec (@records) {
                   3524:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3525:                 if (%temp) {
                   3526:                     $keyfields=join(',',sort(keys(%temp)));
                   3527:                     last;
                   3528:                 }
                   3529:             }
1.41      ng       3530: 	}
                   3531:     }
                   3532:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3533:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3534: 
1.41      ng       3535:     return '';
1.27      albertel 3536: }
                   3537: 
1.246     albertel 3538: sub csvuploadoptions {
1.41      ng       3539:     my ($request)= @_;
1.324     albertel 3540:     my ($symb)=&get_symb($request);
1.257     albertel 3541:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3542:     my $ignore=&mt('Ignore First Line');
                   3543:     $request->print(<<ENDPICK);
                   3544: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3545: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
                   3546: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3547: <!--
1.246     albertel 3548: <p>
                   3549: <label>
                   3550:    <input type="checkbox" name="show_full_results" />
                   3551:    Show a table of all changes
                   3552: </label>
                   3553: </p>
1.302     albertel 3554: -->
1.246     albertel 3555: <p>
                   3556: <label>
                   3557:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3558:    Overwrite any existing score
                   3559: </label>
                   3560: </p>
                   3561: ENDPICK
                   3562:     my %fields=&get_fields();
                   3563:     if (!defined($fields{'domain'})) {
1.257     albertel 3564: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3565: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3566:     }
1.257     albertel 3567:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3568: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3569: 	my $cleankey=$1;
                   3570: 	if ($cleankey eq 'command') { next; }
                   3571: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3572: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3573:     }
                   3574:     # FIXME do a check for any duplicated user ids...
                   3575:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3576:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3577: <hr /></form>'."\n");
1.324     albertel 3578:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3579:     return '';
                   3580: }
                   3581: 
                   3582: sub get_fields {
                   3583:     my %fields;
1.257     albertel 3584:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3585:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3586: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3587: 	    if ($env{'form.f'.$i} ne 'none') {
                   3588: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3589: 	    }
                   3590: 	} else {
1.257     albertel 3591: 	    if ($env{'form.f'.$i} ne 'none') {
                   3592: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3593: 	    }
                   3594: 	}
1.27      albertel 3595:     }
1.246     albertel 3596:     return %fields;
                   3597: }
                   3598: 
                   3599: sub csvuploadassign {
                   3600:     my ($request)= @_;
1.324     albertel 3601:     my ($symb)=&get_symb($request);
1.246     albertel 3602:     if (!$symb) {return '';}
1.345     bowersj2 3603:     my $error_msg = '';
1.246     albertel 3604:     &Apache::loncommon::load_tmp_file($request);
                   3605:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3606:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3607:     my %fields=&get_fields();
1.41      ng       3608:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3609:     my $courseid=$env{'request.course.id'};
1.97      albertel 3610:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3611:     my @notallowed;
1.41      ng       3612:     my @skipped;
                   3613:     my $countdone=0;
                   3614:     foreach my $grade (@gradedata) {
                   3615: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3616: 	my $domain;
                   3617: 	if ($entries{$fields{'domain'}}) {
                   3618: 	    $domain=$entries{$fields{'domain'}};
                   3619: 	} else {
1.257     albertel 3620: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3621: 	}
1.243     albertel 3622: 	$domain=~s/\s//g;
1.41      ng       3623: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3624: 	$username=~s/\s//g;
1.243     albertel 3625: 	if (!$username) {
                   3626: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3627: 	    $id=~s/\s//g;
1.243     albertel 3628: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3629: 	    $username=$ids{$id};
                   3630: 	}
1.41      ng       3631: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3632: 	    my $id=$entries{$fields{'ID'}};
                   3633: 	    $id=~s/\s//g;
                   3634: 	    if ($id) {
                   3635: 		push(@skipped,"$id:$domain");
                   3636: 	    } else {
                   3637: 		push(@skipped,"$username:$domain");
                   3638: 	    }
1.41      ng       3639: 	    next;
                   3640: 	}
1.108     albertel 3641: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3642: 	if (!&canmodify($usec)) {
                   3643: 	    push(@notallowed,"$username:$domain");
                   3644: 	    next;
                   3645: 	}
1.244     albertel 3646: 	my %points;
1.41      ng       3647: 	my %grades;
                   3648: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3649: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3650: 		$dest eq 'domain') { next; }
                   3651: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3652: 	    if ($dest=~/stores_(.*)_points/) {
                   3653: 		my $part=$1;
                   3654: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3655: 					      $symb,$domain,$username);
1.345     bowersj2 3656:                 if ($wgt) {
                   3657:                     $entries{$fields{$dest}}=~s/\s//g;
                   3658:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3659:                     my $award='correct_by_override';
                   3660:                     $grades{"resource.$part.awarded"}=$pcr;
                   3661:                     $grades{"resource.$part.solved"}=$award;
                   3662:                     $points{$part}=1;
                   3663:                 } else {
                   3664:                     $error_msg = "<br />" .
                   3665:                         &mt("Some point values were assigned"
                   3666:                             ." for problems with a weight "
                   3667:                             ."of zero. These values were "
                   3668:                             ."ignored.");
                   3669:                 }
1.244     albertel 3670: 	    } else {
                   3671: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3672: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3673: 		my $store_key=$dest;
                   3674: 		$store_key=~s/^stores/resource/;
                   3675: 		$store_key=~s/_/\./g;
                   3676: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3677: 	    }
1.41      ng       3678: 	}
1.244     albertel 3679: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
1.257     albertel 3680: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3681: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3682: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3683: 					   $env{'request.course.id'},
                   3684: 					   $domain,$username);
                   3685: 	if ($result eq 'ok') {
                   3686: 	    $request->print('.');
                   3687: 	} else {
                   3688: 	    $request->print("<p>
                   3689:                               <font color='red'>
                   3690:                                  Failed to store student $username\@$domain.
                   3691:                                  Message when trying to store was ($result)
                   3692:                               </font>
                   3693:                              </p>" );
                   3694: 	}
1.41      ng       3695: 	$request->rflush();
                   3696: 	$countdone++;
                   3697:     }
                   3698:     $request->print("<br />Stored $countdone students\n");
                   3699:     if (@skipped) {
1.325     www      3700: 	$request->print('<p><font size="+1"><b>Skipped Students</b></font></p>');
1.106     albertel 3701: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3702:     }
                   3703:     if (@notallowed) {
                   3704: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
                   3705: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3706:     }
1.106     albertel 3707:     $request->print("<br />\n");
1.324     albertel 3708:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3709:     return $error_msg;
1.26      albertel 3710: }
1.44      ng       3711: #------------- end of section for handling csv file upload ---------
                   3712: #
                   3713: #-------------------------------------------------------------------
                   3714: #
1.122     ng       3715: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3716: #
                   3717: #--- Select a page/sequence and a student to grade
1.68      ng       3718: sub pickStudentPage {
                   3719:     my ($request) = shift;
                   3720: 
                   3721:     $request->print(<<LISTJAVASCRIPT);
                   3722: <script type="text/javascript" language="javascript">
                   3723: 
                   3724: function checkPickOne(formname) {
1.76      ng       3725:     if (radioSelection(formname.student) == null) {
1.68      ng       3726: 	alert("Please select the student you wish to grade.");
                   3727: 	return;
                   3728:     }
1.125     ng       3729:     ptr = pullDownSelection(formname.selectpage);
                   3730:     formname.page.value = formname["page"+ptr].value;
                   3731:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3732:     formname.submit();
                   3733: }
                   3734: 
                   3735: </script>
                   3736: LISTJAVASCRIPT
1.118     ng       3737:     &commonJSfunctions($request);
1.324     albertel 3738:     my ($symb) = &get_symb($request);
1.257     albertel 3739:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3740:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3741:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3742: 
                   3743:     my $result='<h3><font color="#339933">&nbsp;'.
                   3744: 	'Manual Grading by Page or Sequence</font></h3>';
                   3745: 
1.80      ng       3746:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3747:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3748:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3749:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3750: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3751: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3752:     my $ctr=0;
1.68      ng       3753:     foreach (@$titles) {
                   3754: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3755: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3756: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3757: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3758: 	$ctr++;
1.68      ng       3759:     }
1.326     albertel 3760:     $result.= '</select>'."<br />\n";
1.70      ng       3761:     $ctr=0;
                   3762:     foreach (@$titles) {
                   3763: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3764: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3765: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3766: 	$ctr++;
                   3767:     }
1.72      ng       3768:     $result.='<input type="hidden" name="page" />'."\n".
                   3769: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3770: 
1.288     albertel 3771:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                   3772: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3773: 
1.71      ng       3774:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3775: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
                   3776: 	'<label><input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions</label>'."\n".
                   3777: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3778: 
1.68      ng       3779:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3780: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3781: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3782: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3783: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3784: 
1.382   ! albertel 3785:     $result.='&nbsp;<b>'.&mt('Use CODE:').' </b>'.
        !          3786: 	'<input type="text" name="CODE" value="" /><br />'."\n";
        !          3787: 
1.80      ng       3788:     $result.='&nbsp;<input type="button" '.
1.126     ng       3789: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3790: 
1.68      ng       3791:     $request->print($result);
                   3792: 
1.326     albertel 3793:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3794: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3795: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3796: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3797: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3798: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3799: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3800:  
1.76      ng       3801:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3802:     my $ptr = 1;
1.294     albertel 3803:     foreach my $student (sort 
                   3804: 			 {
                   3805: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3806: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3807: 			     }
                   3808: 			     return $a cmp $b;
                   3809: 			 } (keys(%$fullname))) {
1.68      ng       3810: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3811: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3812: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3813: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3814: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3815: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3816: 	$ptr++;
                   3817:     }
1.381     albertel 3818:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;</td></tr>' if ($ptr%2 == 0);
                   3819:     $studentTable.='</table></td></tr></table>'."\n";
1.126     ng       3820:     $studentTable.='<input type="button" '.
                   3821: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3822: 
1.324     albertel 3823:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3824:     $request->print($studentTable);
                   3825: 
                   3826:     return '';
                   3827: }
                   3828: 
                   3829: sub getSymbMap {
1.74      albertel 3830:     my ($request) = @_;
1.132     bowersj2 3831:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3832: 
                   3833:     my %symbx = ();
                   3834:     my @titles = ();
1.117     bowersj2 3835:     my $minder = 0;
                   3836: 
                   3837:     # Gather every sequence that has problems.
1.240     albertel 3838:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3839: 					       1,0,1);
1.117     bowersj2 3840:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3841: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.381     albertel 3842: 	    my $title = $minder.'.'.
                   3843: 		&HTML::Entities::encode($sequence->compTitle(),'"\'&');
                   3844: 	    push(@titles, $title); # minder in case two titles are identical
                   3845: 	    $symbx{$title} = &HTML::Entities::encode($sequence->symb(),'"\'&');
1.117     bowersj2 3846: 	    $minder++;
1.241     albertel 3847: 	}
1.68      ng       3848:     }
                   3849:     return \@titles,\%symbx;
                   3850: }
                   3851: 
1.72      ng       3852: #
                   3853: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3854: sub displayPage {
                   3855:     my ($request) = shift;
                   3856: 
1.324     albertel 3857:     my ($symb) = &get_symb($request);
1.257     albertel 3858:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3859:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3860:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3861:     my $pageTitle = $env{'form.page'};
1.103     albertel 3862:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3863:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3864:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3865: 
                   3866:     #need to make sure we have the correct data for later EXT calls, 
                   3867:     #thus invalidate the cache
                   3868:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3869:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3870:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3871:     &Apache::lonnet::clear_EXT_cache_status();
                   3872: 
1.103     albertel 3873:     if (!&canview($usec)) {
1.257     albertel 3874: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
1.324     albertel 3875: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3876: 	return;
                   3877:     }
1.257     albertel 3878:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3879:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3880: 	'</h3>'."\n";
1.382   ! albertel 3881:     if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
        !          3882: 	$result.='<h3>&nbsp;CODE: '.$env{'form.CODE'}.'</h3>'."\n";
        !          3883:     } else {
        !          3884: 	delete($env{'form.CODE'});
        !          3885:     }
1.71      ng       3886:     &sub_page_js($request);
                   3887:     $request->print($result);
                   3888: 
1.132     bowersj2 3889:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3890:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3891:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3892:     if (!$map) {
                   3893: 	$request->print('<font color="red">Unable to view requested sequence. ('.$resUrl.')</font>');
1.324     albertel 3894: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3895: 	return; 
                   3896:     }
1.68      ng       3897:     my $iterator = $navmap->getIterator($map->map_start(),
                   3898: 					$map->map_finish());
                   3899: 
1.71      ng       3900:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3901: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3902: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3903: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3904: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3905: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       3906: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       3907: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3908: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3909: 
1.382   ! albertel 3910:     if (defined($env{'form.CODE'})) {
        !          3911: 	$studentTable.=
        !          3912: 	    '<input type="hidden" name="CODE" value="'.$env{'form.CODE'}.'" />'."\n";
        !          3913:     }
1.381     albertel 3914:     my $checkIcon = '<img alt="'.&mt('Check Mark').
                   3915: 	'" src="'.$request->dir_config('lonIconsURL').
1.71      ng       3916: 	'/check.gif" height="16" border="0" />';
                   3917: 
1.118     ng       3918:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   3919: 	' symbol.'."\n".
1.71      ng       3920: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3921: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       3922: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 3923: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       3924: 
1.329     albertel 3925:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 3926:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       3927:     $iterator->next(); # skip the first BEGIN_MAP
                   3928:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 3929:     while ($depth > 0) {
1.68      ng       3930:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3931:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       3932: 
1.235     albertel 3933:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3934: 	    my $parts = $curRes->parts();
1.68      ng       3935:             my $title = $curRes->compTitle();
1.71      ng       3936: 	    my $symbx = $curRes->symb();
1.196     albertel 3937: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 3938: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       3939: 	    $studentTable.='<td valign="top">';
1.382   ! albertel 3940: 	    my %form = ('CODE' => $env{'form.CODE'},);
1.257     albertel 3941: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 3942: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   3943: 					     undef,'both');
1.71      ng       3944: 	    } else {
1.382   ! albertel 3945: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'},%form);
1.80      ng       3946: 		$companswer =~ s|<form(.*?)>||g;
                   3947: 		$companswer =~ s|</form>||g;
1.71      ng       3948: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       3949: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 3950: #		    $request->print('match='.$1."<br />\n");
1.71      ng       3951: #		}
1.116     ng       3952: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 3953: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       3954: 	    }
                   3955: 
1.257     albertel 3956: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       3957: 
1.257     albertel 3958: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       3959: 		if ($record{'version'} eq '') {
                   3960: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
                   3961: 		} else {
1.116     ng       3962: 		    my %responseType = ();
                   3963: 		    foreach my $partid (@{$parts}) {
1.147     albertel 3964: 			my @responseIds =$curRes->responseIds($partid);
                   3965: 			my @responseType =$curRes->responseType($partid);
                   3966: 			my %responseIds;
                   3967: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   3968: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   3969: 			}
                   3970: 			$responseType{$partid} = \%responseIds;
1.116     ng       3971: 		    }
1.148     albertel 3972: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 3973: 
1.71      ng       3974: 		}
1.257     albertel 3975: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   3976: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       3977: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 3978: 									$env{'request.course.id'},
1.71      ng       3979: 									'','.submission');
                   3980:  
                   3981: 	    }
1.103     albertel 3982: 	    if (&canmodify($usec)) {
                   3983: 		foreach my $partid (@{$parts}) {
                   3984: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   3985: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   3986: 		    $question++;
                   3987: 		}
1.196     albertel 3988: 		$prob++;
1.71      ng       3989: 	    }
                   3990: 	    $studentTable.='</td></tr>';
1.68      ng       3991: 
1.103     albertel 3992: 	}
1.68      ng       3993:         $curRes = $iterator->next();
                   3994:     }
                   3995: 
1.381     albertel 3996:     $studentTable.='</table></td></tr></table>'."\n".
1.125     ng       3997: 	'<input type="button" value="Save" '.
1.381     albertel 3998: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" />'.
1.71      ng       3999: 	'</form>'."\n";
1.324     albertel 4000:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       4001:     $request->print($studentTable);
                   4002: 
                   4003:     return '';
1.119     ng       4004: }
                   4005: 
                   4006: sub displaySubByDates {
1.148     albertel 4007:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 4008:     my $isCODE=0;
1.335     albertel 4009:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 4010:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       4011:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   4012: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   4013: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 4014: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       4015: 	'<td><b>Submission</b></td>'.
                   4016: 	'<td><b>Status&nbsp;</b></td></tr>';
                   4017:     my ($version);
                   4018:     my %mark;
1.148     albertel 4019:     my %orders;
1.119     ng       4020:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 4021:     if (!exists($$record{'1:timestamp'})) {
                   4022: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
                   4023:     }
1.335     albertel 4024: 
                   4025:     my $interaction;
1.119     ng       4026:     for ($version=1;$version<=$$record{'version'};$version++) {
                   4027: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 4028: 	if (exists($$record{$version.':resource.0.version'})) {
                   4029: 	    $interaction = $$record{$version.':resource.0.version'};
                   4030: 	}
                   4031: 
                   4032: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4033: 		             : "$version:resource");
                   4034: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4035: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4036: 	if ($isCODE) {
                   4037: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4038: 	}
1.119     ng       4039: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4040: 	my @displaySub = ();
                   4041: 	foreach my $partid (@{$parts}) {
1.335     albertel 4042: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4043: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4044: 	    
                   4045: 
1.122     ng       4046: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4047: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4048: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4049: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4050: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4051: 
                   4052: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4053: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4054: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4055: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.147     albertel 4056: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
1.207     albertel 4057: 			$responseId.')</font>&nbsp;<b>';
1.335     albertel 4058: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4059: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4060: 		    } else {
                   4061: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4062: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4063: 		    }
1.335     albertel 4064: 		    my $responseType=($isTask ? 'Task'
                   4065:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4066: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4067: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4068: 			$orders{$partid}->{$responseId}=
                   4069: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4070: 		    }
1.147     albertel 4071: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4072: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4073: 		}
                   4074: 	    }
1.335     albertel 4075: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4076: 		$displaySub[1].='Checked in by '.
                   4077: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4078: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4079: 		    '<br />';
                   4080: 	    }
                   4081: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4082: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4083: 		    lc($$record{"$where.$partid.award"}).' '.
                   4084: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4085: 		    '<br />';
                   4086: 	    }
1.335     albertel 4087: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4088: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4089: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4090: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4091: 		$displaySub[2].=
                   4092: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4093: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4094: 	    }
                   4095: 	}
                   4096: 	# needed because old essay regrader has not parts info
                   4097: 	if (exists $$record{"$version:resource.regrader"}) {
                   4098: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4099: 	}
                   4100: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4101: 	if ($displaySub[2]) {
                   4102: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4103: 	}
1.382   ! albertel 4104: 	$studentTable.='&nbsp;</td></tr>';
1.147     albertel 4105:     
1.119     ng       4106:     }
                   4107:     $studentTable.='</table></td></tr></table>';
                   4108:     return $studentTable;
1.71      ng       4109: }
                   4110: 
                   4111: sub updateGradeByPage {
                   4112:     my ($request) = shift;
                   4113: 
1.257     albertel 4114:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4115:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4116:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4117:     my $pageTitle = $env{'form.page'};
1.103     albertel 4118:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4119:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4120:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4121:     if (!&canmodify($usec)) {
1.257     albertel 4122: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
1.324     albertel 4123: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4124: 	return;
                   4125:     }
1.257     albertel 4126:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   4127:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4128: 	'</h3>'."\n";
1.70      ng       4129: 
1.68      ng       4130:     $request->print($result);
                   4131: 
1.132     bowersj2 4132:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4133:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4134:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4135:     if (!$map) {
                   4136: 	$request->print('<font color="red">Unable to grade requested sequence. ('.$resUrl.')</font>');
1.324     albertel 4137: 	my ($symb)=&get_symb($request);
                   4138: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4139: 	return; 
                   4140:     }
1.71      ng       4141:     my $iterator = $navmap->getIterator($map->map_start(),
                   4142: 					$map->map_finish());
1.70      ng       4143: 
1.71      ng       4144:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4145: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4146: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4147: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4148: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4149: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4150: 
                   4151:     $iterator->next(); # skip the first BEGIN_MAP
                   4152:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4153:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4154:     while ($depth > 0) {
1.71      ng       4155:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4156:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4157: 
                   4158:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 4159: 	    my $parts = $curRes->parts();
1.71      ng       4160:             my $title = $curRes->compTitle();
                   4161: 	    my $symbx = $curRes->symb();
1.196     albertel 4162: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4163: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4164: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4165: 
                   4166: 	    my %newrecord=();
                   4167: 	    my @displayPts=();
1.269     raeburn  4168:             my %aggregate = ();
                   4169:             my $aggregateflag = 0;
1.71      ng       4170: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4171: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4172: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4173: 
1.257     albertel 4174: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4175: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4176: 		my $partial = $newpts/$wgt;
                   4177: 		my $score;
                   4178: 		if ($partial > 0) {
                   4179: 		    $score = 'correct_by_override';
1.125     ng       4180: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4181: 		    $score = 'incorrect_by_override';
                   4182: 		}
1.257     albertel 4183: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4184: 		if ($dropMenu eq 'excused') {
1.71      ng       4185: 		    $partial = '';
                   4186: 		    $score = 'excused';
1.125     ng       4187: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4188: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4189: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4190: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4191: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4192: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4193: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4194: 		    $changeflag++;
                   4195: 		    $newpts = '';
1.269     raeburn  4196:                     
                   4197:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4198:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4199:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4200:                     if ($aggtries > 0) {
                   4201:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4202:                         $aggregateflag = 1;
                   4203:                     }
1.71      ng       4204: 		}
1.324     albertel 4205: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4206: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4207: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4208: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4209: 		    '&nbsp;<br />';
1.207     albertel 4210: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4211: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4212: 		    '&nbsp;<br />';
1.71      ng       4213: 		$question++;
1.380     albertel 4214: 		next if ($dropMenu eq 'reset status' || ($newpts eq $oldpts && $score ne 'excused'));
1.125     ng       4215: 
1.71      ng       4216: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4217: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4218: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4219: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4220: 
                   4221: 		$changeflag++;
                   4222: 	    }
                   4223: 	    if (scalar(keys(%newrecord)) > 0) {
1.382   ! albertel 4224: 		my %record = 
        !          4225: 		    &Apache::lonnet::restore($symbx,$env{'request.course.id'},
        !          4226: 					     $udom,$uname);
        !          4227: 
        !          4228: 		if (&Apache::lonnet::validCODE($env{'form.CODE'})) {
        !          4229: 		    $newrecord{'resource.CODE'} = $env{'form.CODE'};
        !          4230: 		} elsif (&Apache::lonnet::validCODE($record{'resource.CODE'})) {
        !          4231: 		    $newrecord{'resource.CODE'} = '';
        !          4232: 		}
1.257     albertel 4233: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4234: 					$udom,$uname);
1.382   ! albertel 4235: 		%record = &Apache::lonnet::restore($symbx,
        !          4236: 						   $env{'request.course.id'},
        !          4237: 						   $udom,$uname);
1.380     albertel 4238: 		&check_and_remove_from_queue($parts,\%record,undef,$symbx,
                   4239: 					     $cdom,$cnum,$udom,$uname);
1.71      ng       4240: 	    }
1.380     albertel 4241: 	    
1.269     raeburn  4242:             if ($aggregateflag) {
                   4243:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4244:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4245:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4246:             }
1.125     ng       4247: 
1.71      ng       4248: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4249: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4250: 		'</tr>';
1.68      ng       4251: 
1.196     albertel 4252: 	    $prob++;
1.68      ng       4253: 	}
1.71      ng       4254:         $curRes = $iterator->next();
1.68      ng       4255:     }
1.98      albertel 4256: 
1.71      ng       4257:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4258:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4259:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4260: 		  'The scores were changed for '.
                   4261: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4262:     $request->print($grademsg.$studentTable);
1.68      ng       4263: 
1.70      ng       4264:     return '';
                   4265: }
                   4266: 
1.72      ng       4267: #-------- end of section for handling grading by page/sequence ---------
                   4268: #
                   4269: #-------------------------------------------------------------------
                   4270: 
1.75      albertel 4271: #--------------------Scantron Grading-----------------------------------
                   4272: #
                   4273: #------ start of section for handling grading by page/sequence ---------
                   4274: 
1.81      albertel 4275: sub defaultFormData {
1.324     albertel 4276:     my ($symb)=@_;
1.81      albertel 4277:     return '
                   4278:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4279:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4280:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4281: }
                   4282: 
1.75      albertel 4283: sub getSequenceDropDown {
                   4284:     my ($request,$symb)=@_;
                   4285:     my $result='<select name="selectpage">'."\n";
                   4286:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4287:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4288:     my $ctr=0;
                   4289:     foreach (@$titles) {
                   4290: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4291: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   4292: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   4293: 	    '>'.$showtitle.'</option>'."\n";
                   4294: 	$ctr++;
                   4295:     }
                   4296:     $result.= '</select>';
                   4297:     return $result;
                   4298: }
                   4299: 
1.202     albertel 4300: sub scantron_filenames {
1.257     albertel 4301:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4302:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4303:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4304: 				    &propath($cdom,$cname));
1.202     albertel 4305:     my @possiblenames;
1.201     albertel 4306:     foreach my $filename (sort(@files)) {
1.157     albertel 4307: 	($filename)=split(/&/,$filename);
                   4308: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4309: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4310: 	push(@possiblenames,$filename);
                   4311:     }
                   4312:     return @possiblenames;
                   4313: }
                   4314: 
                   4315: sub scantron_uploads {
1.209     ng       4316:     my ($file2grade) = @_;
1.202     albertel 4317:     my $result=	'<select name="scantron_selectfile">';
                   4318:     $result.="<option></option>";
                   4319:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       4320: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 4321:     }
                   4322:     $result.="</select>";
                   4323:     return $result;
                   4324: }
                   4325: 
1.82      albertel 4326: sub scantron_scantab {
                   4327:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4328:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4329:     $result.='<option></option>'."\n";
1.82      albertel 4330:     foreach my $line (<$fh>) {
                   4331: 	my ($name,$descrip)=split(/:/,$line);
                   4332: 	if ($name =~ /^\#/) { next; }
                   4333: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4334:     }
                   4335:     $result.='</select>'."\n";
                   4336: 
                   4337:     return $result;
                   4338: }
                   4339: 
1.186     albertel 4340: sub scantron_CODElist {
1.257     albertel 4341:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4342:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4343:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4344:     my $namechoice='<option></option>';
1.225     albertel 4345:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4346: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4347: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4348: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4349:     }
                   4350:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4351:     return $namechoice;
                   4352: }
                   4353: 
                   4354: sub scantron_CODEunique {
1.381     albertel 4355:     my $result='<span style="white-space: nowrap;">
1.272     albertel 4356:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4357:                         value="yes" checked="checked" /> Yes </label>
1.381     albertel 4358:                 </span>
                   4359:                 <span style="white-space: nowrap;">
1.272     albertel 4360:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4361:                         value="no" /> No </label>
1.381     albertel 4362:                 </span>';
1.186     albertel 4363:     return $result;
                   4364: }
                   4365: 
1.75      albertel 4366: sub scantron_selectphase {
1.209     ng       4367:     my ($r,$file2grade) = @_;
1.324     albertel 4368:     my ($symb)=&get_symb($r);
1.75      albertel 4369:     if (!$symb) {return '';}
                   4370:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4371:     my $default_form_data=&defaultFormData($symb);
                   4372:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4373:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4374:     my $format_selector=&scantron_scantab();
1.186     albertel 4375:     my $CODE_selector=&scantron_CODElist();
                   4376:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4377:     my $result;
1.157     albertel 4378:     #FIXME allow instructor to be able to download the scantron file
                   4379:     # and to upload it,
1.75      albertel 4380:     $result.= <<SCANTRONFORM;
1.162     albertel 4381:     <table width="100%" border="0">
1.75      albertel 4382:     <tr>
1.226     albertel 4383:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4384:       <td bgcolor="#777777">
1.203     albertel 4385:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4386:         $default_form_data
1.75      albertel 4387:         <table width="100%" border="0">
                   4388:           <tr bgcolor="#e6ffff">
1.174     albertel 4389:             <td colspan="2">
                   4390:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4391:             </td>
                   4392:           </tr>
                   4393:           <tr bgcolor="#ffffe6">
1.174     albertel 4394:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4395:           </tr>
                   4396:           <tr bgcolor="#ffffe6">
1.174     albertel 4397:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4398:           </tr>
1.82      albertel 4399:           <tr bgcolor="#ffffe6">
1.174     albertel 4400:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4401:           </tr>
1.157     albertel 4402:           <tr bgcolor="#ffffe6">
1.186     albertel 4403:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4404:           </tr>
                   4405:           <tr bgcolor="#ffffe6">
                   4406:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4407:           </tr>
                   4408:           <tr bgcolor="#ffffe6">
1.187     albertel 4409: 	    <td> Options: </td>
                   4410:             <td>
1.272     albertel 4411: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.331     albertel 4412:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
                   4413:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4414: 	    </td>
                   4415:           </tr>
                   4416:           <tr bgcolor="#ffffe6">
1.174     albertel 4417:             <td colspan="2">
1.265     www      4418:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4419:             </td>
                   4420:           </tr>
                   4421:         </table>
1.226     albertel 4422:        </td>
                   4423:      </form>
1.162     albertel 4424:     </tr>
                   4425: SCANTRONFORM
                   4426:    
                   4427:     $r->print($result);
                   4428: 
1.257     albertel 4429:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4430:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4431: 
                   4432:         $r->print(<<SCANTRONFORM);
                   4433:     <tr>
                   4434:       <td bgcolor="#777777">
                   4435:         <table width="100%" border="0">
                   4436:           <tr bgcolor="#e6ffff">
                   4437:             <td>
1.174     albertel 4438:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4439:             </td>
                   4440:           </tr>
                   4441:           <tr bgcolor="#ffffe6">
                   4442:             <td>
                   4443: SCANTRONFORM
1.324     albertel 4444:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4445:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4446:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4447:     $r->print(<<UPLOAD);
                   4448:               <script type="text/javascript" language="javascript">
                   4449:     function checkUpload(formname) {
                   4450: 	if (formname.upfile.value == "") {
                   4451: 	    alert("Please use the browse button to select a file from your local directory.");
                   4452: 	    return false;
                   4453: 	}
                   4454: 	formname.submit();
                   4455:     }
                   4456:               </script>
                   4457: 
                   4458:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4459:                 $default_form_data
                   4460:                 <input name='courseid' type='hidden' value='$cnum' />
                   4461:                 <input name='domainid' type='hidden' value='$cdom' />
                   4462:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4463:                 File to upload:<input type="file" name="upfile" size="50" />
                   4464:                 <br />
                   4465:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4466:               </form>
                   4467: UPLOAD
1.162     albertel 4468: 
                   4469:         $r->print(<<SCANTRONFORM);
                   4470:             </td>
                   4471:           </tr>
1.75      albertel 4472:         </table>
                   4473:       </td>
                   4474:     </tr>
1.162     albertel 4475: SCANTRONFORM
                   4476:     }
1.187     albertel 4477:     $r->print(<<SCANTRONFORM);
                   4478:     <tr>
1.226     albertel 4479:       <form action='/adm/grades' name='scantron_download'>
                   4480:         <td bgcolor="#777777">
1.379     albertel 4481: 	  $default_form_data
1.187     albertel 4482:           <input type="hidden" name="command" value="scantron_download" />
                   4483:           <table width="100%" border="0">
                   4484:             <tr bgcolor="#e6ffff">
                   4485:               <td colspan="2">
                   4486:                 &nbsp;<b>Download a scoring office file</b>
                   4487:               </td>
                   4488:             </tr>
                   4489:             <tr bgcolor="#ffffe6">
                   4490:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4491:             </tr>
                   4492:             <tr bgcolor="#ffffe6">
                   4493:               <td colspan="2">
1.293     www      4494:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4495:               </td>
                   4496:             </tr>
                   4497:           </table>
1.226     albertel 4498:         </td>
                   4499:       </form>
1.187     albertel 4500:     </tr>
                   4501: SCANTRONFORM
1.162     albertel 4502: 
                   4503:     $r->print(<<SCANTRONFORM);
1.75      albertel 4504:   </table>
1.81      albertel 4505: $grading_menu_button
1.75      albertel 4506: SCANTRONFORM
                   4507: 
1.162     albertel 4508:     return
1.75      albertel 4509: }
                   4510: 
1.82      albertel 4511: sub get_scantron_config {
                   4512:     my ($which) = @_;
                   4513:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4514:     my %config;
1.157     albertel 4515:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4516:     foreach my $line (<$fh>) {
                   4517: 	my ($name,$descrip)=split(/:/,$line);
                   4518: 	if ($name ne $which ) { next; }
                   4519: 	chomp($line);
                   4520: 	my @config=split(/:/,$line);
                   4521: 	$config{'name'}=$config[0];
                   4522: 	$config{'description'}=$config[1];
                   4523: 	$config{'CODElocation'}=$config[2];
                   4524: 	$config{'CODEstart'}=$config[3];
                   4525: 	$config{'CODElength'}=$config[4];
                   4526: 	$config{'IDstart'}=$config[5];
                   4527: 	$config{'IDlength'}=$config[6];
                   4528: 	$config{'Qstart'}=$config[7];
                   4529: 	$config{'Qlength'}=$config[8];
                   4530: 	$config{'Qoff'}=$config[9];
                   4531: 	$config{'Qon'}=$config[10];
1.157     albertel 4532: 	$config{'PaperID'}=$config[11];
                   4533: 	$config{'PaperIDlength'}=$config[12];
                   4534: 	$config{'FirstName'}=$config[13];
                   4535: 	$config{'FirstNamelength'}=$config[14];
                   4536: 	$config{'LastName'}=$config[15];
                   4537: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4538: 	last;
                   4539:     }
                   4540:     return %config;
                   4541: }
                   4542: 
                   4543: sub username_to_idmap {
                   4544:     my ($classlist)= @_;
                   4545:     my %idmap;
                   4546:     foreach my $student (keys(%$classlist)) {
                   4547: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4548: 	    $student;
                   4549:     }
                   4550:     return %idmap;
                   4551: }
                   4552: 
1.157     albertel 4553: sub scantron_fixup_scanline {
                   4554:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4555:     if ($field eq 'ID') {
                   4556: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4557: 	    return ($line,1,'New value too large');
1.157     albertel 4558: 	}
                   4559: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4560: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4561: 				     $args->{'newid'});
                   4562: 	}
                   4563: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4564: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4565: 	if ($args->{'newid'}=~/^\s*$/) {
                   4566: 	    &scan_data($scan_data,"$whichline.user",
                   4567: 		       $args->{'username'}.':'.$args->{'domain'});
                   4568: 	}
1.186     albertel 4569:     } elsif ($field eq 'CODE') {
1.192     albertel 4570: 	if ($args->{'CODE_ignore_dup'}) {
                   4571: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4572: 	}
                   4573: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4574: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4575: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4576: 		return ($line,1,'New CODE value too large');
                   4577: 	    }
                   4578: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4579: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4580: 	    }
                   4581: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4582: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4583: 	}
1.157     albertel 4584:     } elsif ($field eq 'answer') {
                   4585: 	my $length=$scantron_config->{'Qlength'};
                   4586: 	my $off=$scantron_config->{'Qoff'};
                   4587: 	my $on=$scantron_config->{'Qon'};
                   4588: 	my $answer=${off}x$length;
                   4589: 	if ($args->{'response'} eq 'none') {
                   4590: 	    &scan_data($scan_data,
                   4591: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4592: 	} else {
1.274     albertel 4593: 	    if ($on eq 'letter') {
                   4594: 		my @alphabet=('A'..'Z');
                   4595: 		$answer=$alphabet[$args->{'response'}];
                   4596: 	    } elsif ($on eq 'number') {
                   4597: 		$answer=$args->{'response'}+1;
                   4598: 	    } else {
                   4599: 		substr($answer,$args->{'response'},1)=$on;
                   4600: 	    }
1.157     albertel 4601: 	    &scan_data($scan_data,
                   4602: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4603: 	}
                   4604: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4605: 	substr($line,$where-1,$length)=$answer;
                   4606:     }
                   4607:     return $line;
                   4608: }
                   4609: 
                   4610: sub scan_data {
                   4611:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4612:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4613:     if (defined($value)) {
                   4614: 	$scan_data->{$filename.'_'.$key} = $value;
                   4615:     }
                   4616:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4617:     return $scan_data->{$filename.'_'.$key};
                   4618: }
                   4619: 
1.82      albertel 4620: sub scantron_parse_scanline {
1.194     albertel 4621:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4622:     my %record;
                   4623:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4624:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4625:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4626: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4627: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4628: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4629: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4630: 	    $record{'scantron.CODE'}=substr($data,
                   4631: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4632: 					    $$scantron_config{'CODElength'});
1.191     albertel 4633: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4634: 		$record{'scantron.useCODE'}=1;
                   4635: 	    }
1.192     albertel 4636: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4637: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4638: 	    }
1.82      albertel 4639: 	} else {
                   4640: 	    #FIXME interpret first N questions
                   4641: 	}
                   4642:     }
1.83      albertel 4643:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4644: 				  $$scantron_config{'IDlength'});
1.157     albertel 4645:     $record{'scantron.PaperID'}=
                   4646: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4647: 	       $$scantron_config{'PaperIDlength'});
                   4648:     $record{'scantron.FirstName'}=
                   4649: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4650: 	       $$scantron_config{'FirstNamelength'});
                   4651:     $record{'scantron.LastName'}=
                   4652: 	substr($data,$$scantron_config{'LastName'}-1,
                   4653: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4654:     if ($justHeader) { return \%record; }
                   4655: 
1.82      albertel 4656:     my @alphabet=('A'..'Z');
                   4657:     my $questnum=0;
                   4658:     while ($questions) {
                   4659: 	$questnum++;
                   4660: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4661: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4662: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4663: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 4664: 	    if ($currentquest eq '?'
                   4665: 		|| $currentquest eq '*') {
1.274     albertel 4666: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4667: 		$record{"scantron.$questnum.answer"}='';
                   4668: 	    } elsif (!$currentquest 
                   4669: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4670: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4671: 		$record{"scantron.$questnum.answer"}='';
                   4672: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4673: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4674: 		}
                   4675: 	    } else {
                   4676: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4677: 	    }
                   4678: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 4679: 	    if ($currentquest eq '?'
                   4680: 		|| $currentquest eq '*') {
1.274     albertel 4681: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4682: 		$record{"scantron.$questnum.answer"}='';
                   4683: 		} elsif (!$currentquest 
                   4684: 			 || $currentquest eq $$scantron_config{'Qoff'} 
                   4685: 			 || $currentquest !~ /^\d$/) {
1.239     albertel 4686: 		$record{"scantron.$questnum.answer"}='';
                   4687: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4688: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4689: 		}
                   4690: 	    } else {
1.371     albertel 4691: 		# wrap zero back to J
                   4692: 		if ($currentquest eq '0') {
                   4693: 		    $record{"scantron.$questnum.answer"}=
                   4694: 			$alphabet[9];
                   4695: 		} else {
                   4696: 		    $record{"scantron.$questnum.answer"}=
                   4697: 			$alphabet[$currentquest-1];
                   4698: 		}
1.239     albertel 4699: 	    }
1.82      albertel 4700: 	} else {
1.239     albertel 4701: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4702: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4703: 		$record{"scantron.$questnum.answer"}='';
                   4704: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4705: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4706: 		}
                   4707: 	    } else {
                   4708: 		$record{"scantron.$questnum.answer"}=
                   4709: 		    $alphabet[length($array[0])];
                   4710: 	    }
                   4711: 	    if (scalar(@array) gt 2) {
                   4712: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4713: 		my @ans=@array;
                   4714: 		my $i=length($ans[0]);shift(@ans);
                   4715: 		while ($#ans) {
                   4716: 		    $i+=length($ans[0])+1;
                   4717: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4718: 		    shift(@ans);
                   4719: 		}
                   4720: 	    }
1.82      albertel 4721: 	}
                   4722:     }
1.83      albertel 4723:     $record{'scantron.maxquest'}=$questnum;
                   4724:     return \%record;
1.82      albertel 4725: }
                   4726: 
                   4727: sub scantron_add_delay {
1.140     albertel 4728:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4729:     push(@$delayqueue,
                   4730: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4731: 	  'ecode' => $errorcode }
                   4732: 	 );
1.82      albertel 4733: }
                   4734: 
                   4735: sub scantron_find_student {
1.157     albertel 4736:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4737:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4738:     if ($scanID =~ /^\s*$/) {
                   4739:  	return &scan_data($scan_data,"$line.user");
                   4740:     }
1.83      albertel 4741:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4742:  	if (lc($id) eq lc($scanID)) {
                   4743:  	    return $$idmap{$id};
                   4744:  	}
1.83      albertel 4745:     }
                   4746:     return undef;
                   4747: }
                   4748: 
                   4749: sub scantron_filter {
                   4750:     my ($curres)=@_;
1.331     albertel 4751: 
                   4752:     if (ref($curres) && $curres->is_problem()) {
                   4753: 	# if the user has asked to not have either hidden
                   4754: 	# or 'randomout' controlled resources to be graded
                   4755: 	# don't include them
                   4756: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   4757: 	    && $curres->randomout) {
                   4758: 	    return 0;
                   4759: 	}
1.83      albertel 4760: 	return 1;
                   4761:     }
                   4762:     return 0;
1.82      albertel 4763: }
                   4764: 
1.157     albertel 4765: sub scantron_process_corrections {
                   4766:     my ($r) = @_;
1.257     albertel 4767:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4768:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4769:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4770:     my $which=$env{'form.scantron_line'};
1.200     albertel 4771:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4772:     my ($skip,$err,$errmsg);
1.257     albertel 4773:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4774: 	$skip=1;
1.257     albertel 4775:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4776: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4777: 	    $env{'form.scantron_domain'};
1.157     albertel 4778: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4779: 	($line,$err,$errmsg)=
                   4780: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4781: 				     'ID',{'newid'=>$newid,
1.257     albertel 4782: 				    'username'=>$env{'form.scantron_username'},
                   4783: 				    'domain'=>$env{'form.scantron_domain'}});
                   4784:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4785: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4786: 	my $newCODE;
1.192     albertel 4787: 	my %args;
1.190     albertel 4788: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4789: 	    $newCODE='use_unfound';
1.190     albertel 4790: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4791: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4792: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4793: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4794: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4795: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4796: 	}
1.257     albertel 4797: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4798: 	    $args{'CODE_ignore_dup'}=1;
                   4799: 	}
                   4800: 	$args{'CODE'}=$newCODE;
1.186     albertel 4801: 	($line,$err,$errmsg)=
                   4802: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4803: 				     'CODE',\%args);
1.257     albertel 4804:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4805: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4806: 	    ($line,$err,$errmsg)=
                   4807: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4808: 					 $which,'answer',
                   4809: 					 { 'question'=>$question,
1.257     albertel 4810: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4811: 	    if ($err) { last; }
                   4812: 	}
                   4813:     }
                   4814:     if ($err) {
1.287     albertel 4815: 	$r->print("<font color='red'>Unable to accept last correction, an error occurred :$errmsg:</font>");
1.157     albertel 4816:     } else {
1.200     albertel 4817: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4818: 	&scantron_putfile($scanlines,$scan_data);
                   4819:     }
                   4820: }
                   4821: 
1.200     albertel 4822: sub reset_skipping_status {
                   4823:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4824:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4825:     &scantron_putfile(undef,$scan_data);
                   4826: }
                   4827: 
1.376     albertel 4828: sub start_skipping {
1.200     albertel 4829:     my ($scan_data,$i)=@_;
                   4830:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4831:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   4832: 	$remembered{$i}=2;
                   4833:     } else {
                   4834: 	$remembered{$i}=1;
                   4835:     }
1.200     albertel 4836:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4837: }
                   4838: 
                   4839: sub should_be_skipped {
1.376     albertel 4840:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 4841:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4842: 	# not redoing old skips
1.376     albertel 4843: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 4844: 	return 0;
                   4845:     }
                   4846:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4847: 
                   4848:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   4849: 	return 0;
                   4850:     }
1.200     albertel 4851:     return 1;
                   4852: }
                   4853: 
                   4854: sub remember_current_skipped {
                   4855:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4856:     my %to_remember;
                   4857:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4858: 	if ($scanlines->{'skipped'}[$i]) {
                   4859: 	    $to_remember{$i}=1;
                   4860: 	}
                   4861:     }
1.376     albertel 4862: 
1.200     albertel 4863:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4864:     &scantron_putfile(undef,$scan_data);
                   4865: }
                   4866: 
                   4867: sub check_for_error {
                   4868:     my ($r,$result)=@_;
                   4869:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4870: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4871:     }
                   4872: }
1.157     albertel 4873: 
1.203     albertel 4874: sub scantron_warning_screen {
                   4875:     my ($button_text)=@_;
1.257     albertel 4876:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4877:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 4878:     my $CODElist;
1.284     albertel 4879:     if ($scantron_config{'CODElocation'} &&
                   4880: 	$scantron_config{'CODEstart'} &&
                   4881: 	$scantron_config{'CODElength'}) {
                   4882: 	$CODElist=$env{'form.scantron_CODElist'};
1.373     albertel 4883: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<font color="red">None</font>'; }
1.284     albertel 4884: 	$CODElist=
                   4885: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 4886: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 4887:     }
1.203     albertel 4888:     return (<<STUFF);
                   4889: <p>
                   4890: <font color="red">Please double check the information
                   4891:                  below before clicking on '$button_text'</font>
                   4892: </p>
                   4893: <table>
1.284     albertel 4894: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4895: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4896: $CODElist
1.203     albertel 4897: </table>
                   4898: </font>
                   4899: <br />
                   4900: <p> If this information is correct, please click on '$button_text'.</p>
                   4901: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4902: 
                   4903: <br />
                   4904: STUFF
                   4905: }
                   4906: 
                   4907: sub scantron_do_warning {
                   4908:     my ($r)=@_;
1.324     albertel 4909:     my ($symb)=&get_symb($r);
1.203     albertel 4910:     if (!$symb) {return '';}
1.324     albertel 4911:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 4912:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 4913:     if ( $env{'form.selectpage'} eq '' ||
                   4914: 	 $env{'form.scantron_selectfile'} eq '' ||
                   4915: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 4916: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 4917: 	if ( $env{'form.selectpage'} eq '') {
1.237     albertel 4918: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
                   4919: 	} 
1.257     albertel 4920: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.237     albertel 4921: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
                   4922: 	} 
1.257     albertel 4923: 	if ( $env{'form.scantron_format'} eq '') {
1.237     albertel 4924: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
                   4925: 	} 
                   4926:     } else {
1.265     www      4927: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 4928: 	$r->print(<<STUFF);
1.203     albertel 4929: $warning
1.265     www      4930: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 4931: <input type="hidden" name="command" value="scantron_validate" />
                   4932: STUFF
1.237     albertel 4933:     }
1.352     albertel 4934:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 4935:     return '';
                   4936: }
                   4937: 
                   4938: sub scantron_form_start {
                   4939:     my ($max_bubble)=@_;
                   4940:     my $result= <<SCANTRONFORM;
                   4941: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 4942:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   4943:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   4944:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 4945:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 4946:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   4947:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   4948:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   4949:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 4950:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 4951: SCANTRONFORM
                   4952:     return $result;
                   4953: }
                   4954: 
1.157     albertel 4955: sub scantron_validate_file {
                   4956:     my ($r) = @_;
1.324     albertel 4957:     my ($symb)=&get_symb($r);
1.157     albertel 4958:     if (!$symb) {return '';}
1.324     albertel 4959:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 4960:     
                   4961:     # do the detection of only doing skipped records first befroe we delete
                   4962:     # them  when doing the corrections reset
1.257     albertel 4963:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 4964: 	&reset_skipping_status();
                   4965:     }
1.257     albertel 4966:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 4967: 	&remember_current_skipped();
1.257     albertel 4968: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 4969:     }
                   4970: 
1.257     albertel 4971:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 4972: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   4973: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   4974: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 4975: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 4976:     }
1.200     albertel 4977: 
1.257     albertel 4978:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 4979: 	&scantron_process_corrections($r);
                   4980:     }
1.191     albertel 4981:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 4982:     #get the student pick code ready
                   4983:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 4984:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 4985:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 4986:     $r->print($result);
                   4987:     
1.334     albertel 4988:     my @validate_phases=( 'sequence',
                   4989: 			  'ID',
1.157     albertel 4990: 			  'CODE',
                   4991: 			  'doublebubble',
                   4992: 			  'missingbubbles');
1.257     albertel 4993:     if (!$env{'form.validatepass'}) {
                   4994: 	$env{'form.validatepass'} = 0;
1.157     albertel 4995:     }
1.257     albertel 4996:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 4997: 
                   4998:     my $stop=0;
                   4999:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   5000: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   5001: 	$r->rflush();
                   5002: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   5003: 	{
                   5004: 	    no strict 'refs';
                   5005: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   5006: 	}
                   5007:     }
                   5008:     if (!$stop) {
1.203     albertel 5009: 	my $warning=&scantron_warning_screen('Start Grading');
                   5010: 	$r->print(<<STUFF);
                   5011: Validation process complete.<br />
                   5012: $warning
                   5013: <input type="submit" name="submit" value="Start Grading" />
                   5014: <input type="hidden" name="command" value="scantron_process" />
                   5015: STUFF
                   5016: 
1.157     albertel 5017:     } else {
                   5018: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   5019: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   5020:     }
                   5021:     if ($stop) {
1.334     albertel 5022: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   5023: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   5024: 	    $r->print(' this error <br />');
                   5025: 
                   5026: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   5027: 	} else {
                   5028: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   5029: 	    $r->print(' using corrected info <br />');
                   5030: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   5031: 	    $r->print(" this scanline saving it for later.");
                   5032: 	}
1.157     albertel 5033:     }
1.352     albertel 5034:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 5035:     return '';
                   5036: }
                   5037: 
1.200     albertel 5038: sub scantron_remove_file {
1.192     albertel 5039:     my ($which)=@_;
1.257     albertel 5040:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5041:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5042:     my $file='scantron_';
1.200     albertel 5043:     if ($which eq 'corrected' || $which eq 'skipped') {
                   5044: 	$file.=$which.'_';
1.192     albertel 5045:     } else {
                   5046: 	return 'refused';
                   5047:     }
1.257     albertel 5048:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5049:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5050: }
                   5051: 
                   5052: sub scantron_remove_scan_data {
1.257     albertel 5053:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5054:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5055:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5056:     my @todelete;
1.257     albertel 5057:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5058:     foreach my $key (@keys) {
                   5059: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5060: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5061: 		$key=~/remember_skipping/) {
                   5062: 		next;
                   5063: 	    }
1.192     albertel 5064: 	    push(@todelete,$key);
                   5065: 	}
                   5066:     }
1.200     albertel 5067:     my $result;
1.192     albertel 5068:     if (@todelete) {
1.200     albertel 5069: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5070:     }
                   5071:     return $result;
                   5072: }
                   5073: 
1.157     albertel 5074: sub scantron_getfile {
1.200     albertel 5075:     #FIXME really would prefer a scantron directory
1.257     albertel 5076:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5077:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5078:     my $lines;
                   5079:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5080: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5081:     my %scanlines;
                   5082:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5083:     my $temp=$scanlines{'orig'};
                   5084:     $scanlines{'count'}=$#$temp;
                   5085: 
                   5086:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5087: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5088:     if ($lines eq '-1') {
                   5089: 	$scanlines{'corrected'}=[];
                   5090:     } else {
                   5091: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5092:     }
                   5093:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5094: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5095:     if ($lines eq '-1') {
                   5096: 	$scanlines{'skipped'}=[];
                   5097:     } else {
                   5098: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5099:     }
1.175     albertel 5100:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5101:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5102:     my %scan_data = @tmp;
                   5103:     return (\%scanlines,\%scan_data);
                   5104: }
                   5105: 
                   5106: sub lonnet_putfile {
                   5107:     my ($contents,$filename)=@_;
1.257     albertel 5108:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5109:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5110:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5111:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5112: 
                   5113: }
                   5114: 
                   5115: sub scantron_putfile {
                   5116:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5117:     #FIXME really would prefer a scantron directory
1.257     albertel 5118:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5119:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5120:     if ($scanlines) {
                   5121: 	my $prefix='scantron_';
1.157     albertel 5122: # no need to update orig, shouldn't change
                   5123: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5124: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5125: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5126: 			$prefix.'corrected_'.
1.257     albertel 5127: 			$env{'form.scantron_selectfile'});
1.200     albertel 5128: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5129: 			$prefix.'skipped_'.
1.257     albertel 5130: 			$env{'form.scantron_selectfile'});
1.200     albertel 5131:     }
1.175     albertel 5132:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5133: }
                   5134: 
                   5135: sub scantron_get_line {
1.200     albertel 5136:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5137:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5138:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5139:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5140:     return $scanlines->{'orig'}[$i]; 
                   5141: }
                   5142: 
1.200     albertel 5143: sub get_todo_count {
                   5144:     my ($scanlines,$scan_data)=@_;
                   5145:     my $count=0;
                   5146:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5147: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5148: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5149: 	$count++;
                   5150:     }
                   5151:     return $count;
                   5152: }
                   5153: 
1.157     albertel 5154: sub scantron_put_line {
1.200     albertel 5155:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5156:     if ($skip) {
                   5157: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5158: 	&start_skipping($scan_data,$i);
1.157     albertel 5159: 	return;
                   5160:     }
                   5161:     $scanlines->{'corrected'}[$i]=$newline;
                   5162: }
                   5163: 
1.376     albertel 5164: sub scantron_clear_skip {
                   5165:     my ($scanlines,$scan_data,$i)=@_;
                   5166:     if (exists($scanlines->{'skipped'}[$i])) {
                   5167: 	undef($scanlines->{'skipped'}[$i]);
                   5168: 	return 1;
                   5169:     }
                   5170:     return 0;
                   5171: }
                   5172: 
1.334     albertel 5173: sub scantron_filter_not_exam {
                   5174:     my ($curres)=@_;
                   5175:     
                   5176:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5177: 	# if the user has asked to not have either hidden
                   5178: 	# or 'randomout' controlled resources to be graded
                   5179: 	# don't include them
                   5180: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5181: 	    && $curres->randomout) {
                   5182: 	    return 0;
                   5183: 	}
                   5184: 	return 1;
                   5185:     }
                   5186:     return 0;
                   5187: }
                   5188: 
                   5189: sub scantron_validate_sequence {
                   5190:     my ($r,$currentphase) = @_;
                   5191: 
                   5192:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5193:     my (undef,undef,$sequence)=
                   5194: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5195: 
                   5196:     my $map=$navmap->getResourceByUrl($sequence);
                   5197: 
                   5198:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5199:                                     value="ignore" />');
                   5200:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5201: 	my @resources=
                   5202: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5203: 	if (@resources) {
1.357     banghart 5204: 	    $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 5205: 	    return (1,$currentphase);
                   5206: 	}
                   5207:     }
                   5208: 
                   5209:     return (0,$currentphase+1);
                   5210: }
                   5211: 
1.157     albertel 5212: sub scantron_validate_ID {
                   5213:     my ($r,$currentphase) = @_;
                   5214:     
                   5215:     #get student info
                   5216:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5217:     my %idmap=&username_to_idmap($classlist);
                   5218: 
                   5219:     #get scantron line setup
1.257     albertel 5220:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5221:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5222: 
                   5223:     my %found=('ids'=>{},'usernames'=>{});
                   5224:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5225: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5226: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5227: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5228: 						 $scan_data);
                   5229: 	my $id=$$scan_record{'scantron.ID'};
                   5230: 	my $found;
                   5231: 	foreach my $checkid (keys(%idmap)) {
                   5232: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5233: 	}
                   5234: 	if ($found) {
                   5235: 	    my $username=$idmap{$found};
                   5236: 	    if ($found{'ids'}{$found}) {
                   5237: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5238: 					 $line,'duplicateID',$found);
1.194     albertel 5239: 		return(1,$currentphase);
1.157     albertel 5240: 	    } elsif ($found{'usernames'}{$username}) {
                   5241: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5242: 					 $line,'duplicateID',$username);
1.194     albertel 5243: 		return(1,$currentphase);
1.157     albertel 5244: 	    }
1.186     albertel 5245: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 5246: 	    $found{'ids'}{$found}++;
                   5247: 	    $found{'usernames'}{$username}++;
                   5248: 	} else {
                   5249: 	    if ($id =~ /^\s*$/) {
1.158     albertel 5250: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 5251: 		if (defined($username) && $found{'usernames'}{$username}) {
                   5252: 		    &scantron_get_correction($r,$i,$scan_record,
                   5253: 					     \%scantron_config,
                   5254: 					     $line,'duplicateID',$username);
1.194     albertel 5255: 		    return(1,$currentphase);
1.157     albertel 5256: 		} elsif (!defined($username)) {
                   5257: 		    &scantron_get_correction($r,$i,$scan_record,
                   5258: 					     \%scantron_config,
                   5259: 					     $line,'incorrectID');
1.194     albertel 5260: 		    return(1,$currentphase);
1.157     albertel 5261: 		}
                   5262: 		$found{'usernames'}{$username}++;
                   5263: 	    } else {
                   5264: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5265: 					 $line,'incorrectID');
1.194     albertel 5266: 		return(1,$currentphase);
1.157     albertel 5267: 	    }
                   5268: 	}
                   5269:     }
                   5270: 
                   5271:     return (0,$currentphase+1);
                   5272: }
                   5273: 
                   5274: sub scantron_get_correction {
                   5275:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   5276: 
                   5277: #FIXME in the case of a duplicated ID the previous line, probaly need
                   5278: #to show both the current line and the previous one and allow skipping
                   5279: #the previous one or the current one
                   5280: 
1.161     albertel 5281:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 5282:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 5283: 	$r->print(" for PaperID <tt>".
                   5284: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5285:     } else {
                   5286: 	$r->print(" in scanline $i <pre>".
                   5287: 		  $line."</pre> \n");
                   5288:     }
1.242     albertel 5289:     my $message="<p>The ID on the form is  <tt>".
                   5290: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5291: 	"The name on the paper is ".
                   5292: 	$$scan_record{'scantron.LastName'}.",".
                   5293: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5294: 
1.157     albertel 5295:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5296:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5297:     if ($error =~ /ID$/) {
1.186     albertel 5298: 	if ($error eq 'incorrectID') {
1.157     albertel 5299: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5300: 	} elsif ($error eq 'duplicateID') {
                   5301: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5302: 	}
1.242     albertel 5303: 	$r->print($message);
1.157     albertel 5304: 	$r->print("<p>How should I handle this? <br /> \n");
                   5305: 	$r->print("\n<ul><li> ");
                   5306: 	#FIXME it would be nice if this sent back the user ID and
                   5307: 	#could do partial userID matches
                   5308: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5309: 				       'scantron_username','scantron_domain'));
                   5310: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5311: 	$r->print("\n@".
1.257     albertel 5312: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5313: 
                   5314: 	$r->print('</li>');
1.186     albertel 5315:     } elsif ($error =~ /CODE$/) {
                   5316: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5317: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5318: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5319: 	    $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 5320: 	}
1.224     albertel 5321: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5322: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5323: 	$r->print($message);
1.186     albertel 5324: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5325: 	$r->print("\n<br /> ");
1.194     albertel 5326: 	my $i=0;
1.273     albertel 5327: 	if ($error eq 'incorrectCODE' 
                   5328: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5329: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5330: 	    if ($closest > 0) {
                   5331: 		foreach my $testcode (@{$closest}) {
                   5332: 		    my $checked='';
                   5333: 		    if (!$i) { $checked=' checked="on" '; }
                   5334: 		    $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' />");
                   5335: 		    $r->print("\n<br />");
                   5336: 		    $i++;
                   5337: 		}
1.194     albertel 5338: 	    }
                   5339: 	}
1.273     albertel 5340: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   5341: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   5342: 	    $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>");
                   5343: 	    $r->print("\n<br />");
                   5344: 	}
1.194     albertel 5345: 
1.188     albertel 5346: 	$r->print(<<ENDSCRIPT);
                   5347: <script type="text/javascript">
                   5348: function change_radio(field) {
1.190     albertel 5349:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5350:     var i;
                   5351:     for (i=0;i<slct.length;i++) {
                   5352:         if (slct[i].value==field) { slct[i].checked=true; }
                   5353:     }
                   5354: }
                   5355: </script>
                   5356: ENDSCRIPT
1.187     albertel 5357: 	my $href="/adm/pickcode?".
1.359     www      5358: 	   "form=".&escape("scantronupload").
                   5359: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   5360: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   5361: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   5362: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 5363: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   5364: 	    $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')\" />");
                   5365: 	    $r->print("\n<br />");
                   5366: 	}
1.272     albertel 5367: 	$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 5368: 	$r->print("\n<br /><br />");
1.157     albertel 5369:     } elsif ($error eq 'doublebubble') {
                   5370: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5371: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5372: 		  join(',',@{$arg}).'" />');
1.242     albertel 5373: 	$r->print($message);
1.157     albertel 5374: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5375: 	foreach my $question (@{$arg}) {
                   5376: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5377: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5378: 	}
                   5379:     } elsif ($error eq 'missingbubble') {
                   5380: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5381: 	$r->print($message);
1.157     albertel 5382: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5383: 	$r->print("Some questions have no scanned bubbles\n");
                   5384: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5385: 		  join(',',@{$arg}).'" />');
                   5386: 	foreach my $question (@{$arg}) {
                   5387: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5388: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5389: 	}
                   5390:     } else {
                   5391: 	$r->print("\n<ul>");
                   5392:     }
                   5393:     $r->print("\n</li></ul>");
                   5394: 
                   5395: }
                   5396: 
                   5397: sub scantron_bubble_selector {
                   5398:     my ($r,$scan_config,$quest,@selected)=@_;
                   5399:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5400: 
                   5401:     my $scmode=$$scan_config{'Qon'};
                   5402:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5403: 
1.157     albertel 5404:     my @alphabet=('A'..'Z');
                   5405:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5406:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5407: 	$r->print("\n".'<td align="center">');
1.157     albertel 5408: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5409: 	else { $r->print('&nbsp;'); }
                   5410: 	$r->print('</td>');
                   5411:     }
1.274     albertel 5412:     $r->print('</tr><tr>');
1.157     albertel 5413:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5414: 	$r->print("\n".
                   5415: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5416: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5417:     }
1.272     albertel 5418:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5419: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5420:     $r->print('</tr></table>');
                   5421: }
                   5422: 
1.194     albertel 5423: sub num_matches {
                   5424:     my ($orig,$code) = @_;
                   5425:     my @code=split(//,$code);
                   5426:     my @orig=split(//,$orig);
                   5427:     my $same=0;
                   5428:     for (my $i=0;$i<scalar(@code);$i++) {
                   5429: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5430:     }
                   5431:     return $same;
                   5432: }
                   5433: 
                   5434: sub scantron_get_closely_matching_CODEs {
                   5435:     my ($allcodes,$CODE)=@_;
                   5436:     my @CODEs;
                   5437:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5438: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5439:     }
                   5440: 
                   5441:     return ($#CODEs,$CODEs[-1]);
                   5442: }
                   5443: 
                   5444: sub get_codes {
1.280     foxr     5445:     my ($old_name, $cdom, $cnum) = @_;
                   5446:     if (!$old_name) {
                   5447: 	$old_name=$env{'form.scantron_CODElist'};
                   5448:     }
                   5449:     if (!$cdom) {
                   5450: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5451:     }
                   5452:     if (!$cnum) {
                   5453: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5454:     }
1.278     albertel 5455:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5456: 				    $cdom,$cnum);
                   5457:     my %allcodes;
                   5458:     if ($result{"type\0$old_name"} eq 'number') {
                   5459: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5460:     } else {
                   5461: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5462:     }
1.194     albertel 5463:     return %allcodes;
                   5464: }
                   5465: 
1.157     albertel 5466: sub scantron_validate_CODE {
                   5467:     my ($r,$currentphase) = @_;
1.257     albertel 5468:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5469:     if ($scantron_config{'CODElocation'} &&
                   5470: 	$scantron_config{'CODEstart'} &&
                   5471: 	$scantron_config{'CODElength'}) {
1.257     albertel 5472: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5473: 	    &FIXME_blow_up()
                   5474: 	}
                   5475:     } else {
                   5476: 	return (0,$currentphase+1);
                   5477:     }
                   5478:     
                   5479:     my %usedCODEs;
                   5480: 
1.194     albertel 5481:     my %allcodes=&get_codes();
1.186     albertel 5482: 
                   5483:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5484:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5485: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5486: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5487: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5488: 						 $scan_data);
                   5489: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5490: 	my $error=0;
1.224     albertel 5491: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5492: 	    &scantron_get_correction($r,$i,$scan_record,
                   5493: 				     \%scantron_config,
                   5494: 				     $line,'incorrectCODE',\%allcodes);
                   5495: 	    return(1,$currentphase);
                   5496: 	}
1.221     albertel 5497: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5498: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5499: 	    &scantron_get_correction($r,$i,$scan_record,
                   5500: 				     \%scantron_config,
1.194     albertel 5501: 				     $line,'incorrectCODE',\%allcodes);
                   5502: 	    return(1,$currentphase);
1.186     albertel 5503: 	}
1.214     albertel 5504: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5505: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5506: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5507: 	    &scantron_get_correction($r,$i,$scan_record,
                   5508: 				     \%scantron_config,
1.194     albertel 5509: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5510: 	    return(1,$currentphase);
1.186     albertel 5511: 	}
1.194     albertel 5512: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5513:     }
1.157     albertel 5514:     return (0,$currentphase+1);
                   5515: }
                   5516: 
                   5517: sub scantron_validate_doublebubble {
                   5518:     my ($r,$currentphase) = @_;
                   5519:     #get student info
                   5520:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5521:     my %idmap=&username_to_idmap($classlist);
                   5522: 
                   5523:     #get scantron line setup
1.257     albertel 5524:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5525:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5526:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5527: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5528: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5529: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5530: 						 $scan_data);
                   5531: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5532: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5533: 				 'doublebubble',
                   5534: 				 $$scan_record{'scantron.doubleerror'});
                   5535:     	return (1,$currentphase);
                   5536:     }
                   5537:     return (0,$currentphase+1);
                   5538: }
                   5539: 
1.330     albertel 5540: sub scantron_get_maxbubble {    
1.257     albertel 5541:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5542: 	$env{'form.scantron_maxbubble'}) {
                   5543: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5544:     }
1.330     albertel 5545: 
1.191     albertel 5546:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5547:     my (undef,undef,$sequence)=
1.257     albertel 5548: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 5549: 
1.191     albertel 5550:     my $map=$navmap->getResourceByUrl($sequence);
                   5551:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 5552: 
                   5553:     &Apache::lonxml::clear_problem_counter();
                   5554: 
1.191     albertel 5555:     foreach my $resource (@resources) {
1.330     albertel 5556: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   5557: 					('symb' => $resource->symb()));
1.191     albertel 5558:     }
                   5559:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 5560:     $env{'form.scantron_maxbubble'} =
                   5561: 	&Apache::lonxml::get_problem_counter()-1;
                   5562: 
1.257     albertel 5563:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5564: }
                   5565: 
1.157     albertel 5566: sub scantron_validate_missingbubbles {
                   5567:     my ($r,$currentphase) = @_;
                   5568:     #get student info
                   5569:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5570:     my %idmap=&username_to_idmap($classlist);
                   5571: 
                   5572:     #get scantron line setup
1.257     albertel 5573:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5574:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5575:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5576:     if (!$max_bubble) { $max_bubble=2**31; }
                   5577:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5578: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5579: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5580: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5581: 						 $scan_data);
                   5582: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5583: 	my @to_correct;
                   5584: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5585: 	    if ($missing > $max_bubble) { next; }
                   5586: 	    push(@to_correct,$missing);
                   5587: 	}
                   5588: 	if (@to_correct) {
                   5589: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5590: 				     $line,'missingbubble',\@to_correct);
                   5591: 	    return (1,$currentphase);
                   5592: 	}
                   5593: 
                   5594:     }
                   5595:     return (0,$currentphase+1);
                   5596: }
                   5597: 
1.82      albertel 5598: sub scantron_process_students {
1.75      albertel 5599:     my ($r) = @_;
1.257     albertel 5600:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5601:     my ($symb)=&get_symb($r);
1.81      albertel 5602:     if (!$symb) {return '';}
1.324     albertel 5603:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5604: 
1.257     albertel 5605:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5606:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5607:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5608:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5609:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5610:     my $map=$navmap->getResourceByUrl($sequence);
                   5611:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5612: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5613:     my $result= <<SCANTRONFORM;
1.81      albertel 5614: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5615:   <input type="hidden" name="command" value="scantron_configphase" />
                   5616:   $default_form_data
                   5617: SCANTRONFORM
1.82      albertel 5618:     $r->print($result);
                   5619: 
                   5620:     my @delayqueue;
1.140     albertel 5621:     my %completedstudents;
                   5622:     
1.200     albertel 5623:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5624:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5625:  				    'Scantron Progress',$count,
1.195     albertel 5626: 				    'inline',undef,'scantronupload');
1.140     albertel 5627:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5628: 					  'Processing first student');
                   5629:     my $start=&Time::HiRes::time();
1.158     albertel 5630:     my $i=-1;
1.200     albertel 5631:     my ($uname,$udom,$started);
1.157     albertel 5632:     while ($i<$scanlines->{'count'}) {
                   5633:  	($uname,$udom)=('','');
                   5634:  	$i++;
1.200     albertel 5635:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5636:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5637: 	if ($started) {
                   5638: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5639: 						     'last student');
                   5640: 	}
                   5641: 	$started=1;
1.157     albertel 5642:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5643:  						 $scan_data);
                   5644:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5645:  					      \%idmap,$i)) {
                   5646:   	    &scantron_add_delay(\@delayqueue,$line,
                   5647:  				'Unable to find a student that matches',1);
                   5648:  	    next;
                   5649:   	}
                   5650:  	if (exists $completedstudents{$uname}) {
                   5651:  	    &scantron_add_delay(\@delayqueue,$line,
                   5652:  				'Student '.$uname.' has multiple sheets',2);
                   5653:  	    next;
                   5654:  	}
                   5655:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 5656: 
                   5657: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 5658:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 5659: 
                   5660: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   5661: 	    &scantron_putfile($scanlines,$scan_data);
                   5662: 	}
1.161     albertel 5663: 	
                   5664: 	my $i=0;
1.83      albertel 5665: 	foreach my $resource (@resources) {
1.85      albertel 5666: 	    $i++;
1.193     albertel 5667: 	    my %form=('submitted'     =>'scantron',
                   5668: 		      'grade_target'  =>'grade',
                   5669: 		      'grade_username'=>$uname,
                   5670: 		      'grade_domain'  =>$udom,
1.257     albertel 5671: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5672: 		      'grade_symb'    =>$resource->symb());
                   5673: 	    if (exists($scan_record->{'scantron.CODE'}) &&
                   5674: 		$scan_record->{'scantron.CODE'}) {
                   5675: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5676: 	    } else {
                   5677: 		$form{'CODE'}='';
1.193     albertel 5678: 	    }
                   5679: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5680: 	    if ($result ne '') {
                   5681: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5682: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5683: 	    }
1.213     albertel 5684: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5685: 	}
1.140     albertel 5686: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5687: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5688:     } continue {
1.330     albertel 5689: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 5690: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5691:     }
1.140     albertel 5692:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5693: #    my $lasttime = &Time::HiRes::time()-$start;
                   5694: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5695: 
1.200     albertel 5696:     $r->print("</form>");
1.324     albertel 5697:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5698:     return '';
1.75      albertel 5699: }
1.157     albertel 5700: 
                   5701: sub scantron_upload_scantron_data {
                   5702:     my ($r)=@_;
1.257     albertel 5703:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5704:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5705: 							  'domainid',
                   5706: 							  'coursename');
1.257     albertel 5707:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5708: 						   'domainid');
1.324     albertel 5709:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5710:     $r->print(<<UPLOAD);
                   5711: <script type="text/javascript" language="javascript">
                   5712:     function checkUpload(formname) {
                   5713: 	if (formname.upfile.value == "") {
                   5714: 	    alert("Please use the browse button to select a file from your local directory.");
                   5715: 	    return false;
                   5716: 	}
                   5717: 	formname.submit();
                   5718:     }
                   5719: </script>
                   5720: 
                   5721: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5722: $default_form_data
1.181     albertel 5723: <table>
                   5724: <tr><td>$select_link </td></tr>
                   5725: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5726: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5727: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5728: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5729: </table>
1.157     albertel 5730: <input name='command' value='scantronupload_save' type='hidden' />
                   5731: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5732: </form>
                   5733: UPLOAD
                   5734:     return '';
                   5735: }
                   5736: 
                   5737: sub scantron_upload_scantron_data_save {
                   5738:     my($r)=@_;
1.324     albertel 5739:     my ($symb)=&get_symb($r,1);
1.182     albertel 5740:     my $doanotherupload=
                   5741: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5742: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5743: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5744: 	'</form>'."\n";
1.257     albertel 5745:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5746: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5747: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5748: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5749: 	if ($symb) {
1.324     albertel 5750: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5751: 	} else {
                   5752: 	    $r->print($doanotherupload);
                   5753: 	}
1.162     albertel 5754: 	return '';
                   5755:     }
1.257     albertel 5756:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5757:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5758:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5759:     #FIXME
                   5760:     #copied from lonnet::userfileupload()
                   5761:     #make that function able to target a specified course
                   5762:     # Replace Windows backslashes by forward slashes
                   5763:     $fname=~s/\\/\//g;
                   5764:     # Get rid of everything but the actual filename
                   5765:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5766:     # Replace spaces by underscores
                   5767:     $fname=~s/\s+/\_/g;
                   5768:     # Replace all other weird characters by nothing
                   5769:     $fname=~s/[^\w\.\-]//g;
                   5770:     # See if there is anything left
                   5771:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5772:     my $uploadedfile=$fname;
1.157     albertel 5773:     $fname='scantron_orig_'.$fname;
1.257     albertel 5774:     if (length($env{'form.upfile'}) < 2) {
                   5775: 	$r->print("<font color='red'>Error:</font> 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 5776:     } else {
1.275     albertel 5777: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5778: 	if ($result =~ m|^/uploaded/|) {
1.257     albertel 5779: 	    $r->print("<font color='green'>Success:</font> Successfully uploaded ".(length($env{'form.upfile'})-1)." bytes of data into location <tt>".$result."</tt>");
1.210     albertel 5780: 	} else {
1.257     albertel 5781: 	    $r->print("<font color='red'>Error:</font> An error (".$result.") occurred when attempting to upload the file, <tt>".&HTML::Entities::encode($env{'form.upfile.filename'},'<>&"')."</tt>");
1.183     albertel 5782: 	}
                   5783:     }
1.174     albertel 5784:     if ($symb) {
1.209     ng       5785: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5786:     } else {
1.182     albertel 5787: 	$r->print($doanotherupload);
1.174     albertel 5788:     }
1.157     albertel 5789:     return '';
                   5790: }
                   5791: 
1.202     albertel 5792: sub valid_file {
                   5793:     my ($requested_file)=@_;
                   5794:     foreach my $filename (sort(&scantron_filenames())) {
                   5795: 	if ($requested_file eq $filename) { return 1; }
                   5796:     }
                   5797:     return 0;
                   5798: }
                   5799: 
                   5800: sub scantron_download_scantron_data {
                   5801:     my ($r)=@_;
1.324     albertel 5802:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5803:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5804:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5805:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5806:     if (! &valid_file($file)) {
                   5807: 	$r->print(<<ERROR);
                   5808: 	<p>
                   5809: 	    The requested file name was invalid.
                   5810:         </p>
                   5811: ERROR
1.324     albertel 5812: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5813: 	return;
                   5814:     }
                   5815:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5816:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5817:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5818:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5819:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5820:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5821:     $r->print(<<DOWNLOAD);
                   5822:     <p>
                   5823: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5824:     </p>
                   5825:     <p>
                   5826: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5827:     </p>
                   5828:     <p>
                   5829: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5830:     </p>
                   5831: DOWNLOAD
1.324     albertel 5832:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5833:     return '';
                   5834: }
1.157     albertel 5835: 
1.75      albertel 5836: #-------- end of section for handling grading scantron forms -------
                   5837: #
                   5838: #-------------------------------------------------------------------
                   5839: 
1.72      ng       5840: #-------------------------- Menu interface -------------------------
                   5841: #
                   5842: #--- Show a Grading Menu button - Calls the next routine ---
                   5843: sub show_grading_menu_form {
1.324     albertel 5844:     my ($symb)=@_;
1.125     ng       5845:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5846: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5847: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5848: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5849: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5850: 	'</form>'."\n";
                   5851:     return $result;
                   5852: }
                   5853: 
1.77      ng       5854: # -- Retrieve choices for grading form
                   5855: sub savedState {
                   5856:     my %savedState = ();
1.257     albertel 5857:     if ($env{'form.saveState'}) {
                   5858: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5859: 	    my ($key,$value) = split(/=/,$_,2);
                   5860: 	    $savedState{$key} = $value;
                   5861: 	}
                   5862:     }
                   5863:     return \%savedState;
                   5864: }
1.76      ng       5865: 
1.72      ng       5866: #--- Displays the main menu page -------
                   5867: sub gradingmenu {
                   5868:     my ($request) = @_;
1.324     albertel 5869:     my ($symb)=&get_symb($request);
1.72      ng       5870:     if (!$symb) {return '';}
1.76      ng       5871:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5872: 
                   5873:     $request->print(<<GRADINGMENUJS);
                   5874: <script type="text/javascript" language="javascript">
1.116     ng       5875:     function checkChoice(formname,val,cmdx) {
                   5876: 	if (val <= 2) {
                   5877: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5878: 	    var cmdsave = cmd;
1.116     ng       5879: 	} else {
                   5880: 	    cmd = cmdx;
1.118     ng       5881: 	    cmdsave = 'submission';
1.116     ng       5882: 	}
                   5883: 	formname.command.value = cmd;
1.118     ng       5884: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5885: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5886: 	if (val < 5) formname.submit();
                   5887: 	if (val == 5) {
1.72      ng       5888: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5889: 	    formname.submit();
                   5890: 	}
1.238     albertel 5891: 	if (val < 7) formname.submit();
1.72      ng       5892:     }
                   5893: 
                   5894:     function checkReceiptNo(formname,nospace) {
                   5895: 	var receiptNo = formname.receipt.value;
                   5896: 	var checkOpt = false;
                   5897: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5898: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5899: 	if (checkOpt) {
                   5900: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5901: 	    formname.receipt.value = "";
                   5902: 	    formname.receipt.focus();
                   5903: 	    return false;
                   5904: 	}
                   5905: 	return true;
                   5906:     }
                   5907: </script>
                   5908: GRADINGMENUJS
1.118     ng       5909:     &commonJSfunctions($request);
                   5910:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
1.324     albertel 5911:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       5912:     $result.=$table;
1.76      ng       5913:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       5914:     my $savedState = &savedState();
1.118     ng       5915:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       5916:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       5917:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       5918:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       5919: 
                   5920:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   5921: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   5922: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   5923: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       5924: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       5925: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       5926: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       5927: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   5928: 
1.326     albertel 5929:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   5930: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       5931: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       5932: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   5933: 
1.326     albertel 5934:     $result.='<table width="100%" border="0">';
1.116     ng       5935:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 5936: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       5937:     if (ref($sections)) {
1.155     albertel 5938: 	foreach (sort (@$sections)) {
                   5939: 	    $result.='<option value="'.$_.'" '.
                   5940: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   5941: 	}
1.116     ng       5942:     }
1.238     albertel 5943:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       5944: 
1.167     sakharuk 5945:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       5946: 
1.116     ng       5947:     $result.='</td></tr>';
                   5948: 
1.288     albertel 5949:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       5950: 	'<input type="radio" name="radioChoice" value="submission" '.
1.326     albertel 5951: 	($saveCmd eq 'submission' ? 'checked' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 5952: 	'</label> <select name="submitonly">'.
1.145     albertel 5953: 	'<option value="yes" '.
1.326     albertel 5954: 	($saveSub eq 'yes' ? 'selected="on"' : '').' />'.&mt('with submissions').'</option>'.
1.301     albertel 5955: 	'<option value="queued" '.
1.326     albertel 5956: 	($saveSub eq 'queued' ? 'selected="on"' : '').' />'.&mt('in grading queue').'</option>'.
1.145     albertel 5957: 	'<option value="graded" '.
1.326     albertel 5958: 	($saveSub eq 'graded' ? 'selected="on"' : '').' />'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 5959: 	'<option value="incorrect" '.
1.326     albertel 5960: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').' />'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 5961: 	'<option value="all" '.
1.326     albertel 5962: 	($saveSub eq 'all' ? 'selected="on"' : '').' />'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       5963: 
1.116     ng       5964:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 5965: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.326     albertel 5966: 	($saveCmd eq 'viewgrades' ? 'checked' : '').' /> '.
1.288     albertel 5967: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       5968: 
1.118     ng       5969:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 5970: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.326     albertel 5971: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').' /> '.
1.288     albertel 5972: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       5973: 
1.116     ng       5974:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       5975: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       5976: 	'</td></tr></table>'."\n";
                   5977: 
                   5978:     $result.='</td><td valign="top">';
                   5979: 
1.326     albertel 5980:     $result.='<table width="100%" border="0">';
1.116     ng       5981:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      5982: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   5983: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       5984: 
1.75      albertel 5985:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       5986: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      5987: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 5988: 
1.257     albertel 5989:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       5990: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      5991: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   5992: 	    ' '.&mt('receipt').': '.
1.257     albertel 5993: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 5994: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       5995: 	    '</td></tr>'."\n";
                   5996:     } 
1.238     albertel 5997:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5998: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   5999: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 6000:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   6001: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   6002: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       6003: 
1.116     ng       6004:     $result.='</form></td></tr></table>'."\n".
1.72      ng       6005: 	'</td></tr></table>'."\n".
                   6006: 	'</td></tr></table>'."\n";
1.44      ng       6007:     return $result;
1.2       albertel 6008: }
                   6009: 
1.285     albertel 6010: sub reset_perm {
                   6011:     undef(%perm);
                   6012: }
                   6013: 
                   6014: sub init_perm {
                   6015:     &reset_perm();
1.300     albertel 6016:     foreach my $test_perm ('vgr','mgr','opa') {
                   6017: 
                   6018: 	my $scope = $env{'request.course.id'};
                   6019: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   6020: 
                   6021: 	    $scope .= '/'.$env{'request.course.sec'};
                   6022: 	    if ( $perm{$test_perm}=
                   6023: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   6024: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   6025: 	    } else {
                   6026: 		delete($perm{$test_perm});
                   6027: 	    }
1.285     albertel 6028: 	}
                   6029:     }
                   6030: }
                   6031: 
1.1       albertel 6032: sub handler {
1.41      ng       6033:     my $request=$_[0];
1.102     albertel 6034: 
1.285     albertel 6035:     &reset_perm();
1.257     albertel 6036:     if ($env{'browser.mathml'}) {
1.141     www      6037: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       6038:     } else {
1.141     www      6039: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       6040:     }
                   6041:     $request->send_http_header;
1.44      ng       6042:     return '' if $request->header_only;
1.41      ng       6043:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 6044:     my $symb=&get_symb($request,1);
1.160     albertel 6045:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   6046:     my $command=$commands[0];
                   6047:     if ($#commands > 0) {
                   6048: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   6049:     }
1.353     albertel 6050:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 6051:     if ($symb eq '' && $command eq '') {
1.257     albertel 6052: 	if ($env{'user.adv'}) {
                   6053: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   6054: 		($env{'form.codethree'})) {
                   6055: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   6056: 		    $env{'form.codethree'};
1.41      ng       6057: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   6058: 		    &Apache::lonnet::checkin($token);
                   6059: 		if ($tsymb) {
1.137     albertel 6060: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       6061: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 6062: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   6063: 					  ('grade_username' => $tuname,
                   6064: 					   'grade_domain' => $tudom,
                   6065: 					   'grade_courseid' => $tcrsid,
                   6066: 					   'grade_symb' => $tsymb)));
1.41      ng       6067: 		    } else {
1.45      ng       6068: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 6069: 		    }
1.41      ng       6070: 		} else {
1.45      ng       6071: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       6072: 		}
1.14      www      6073: 	    } else {
1.41      ng       6074: 		$request->print(&Apache::lonxml::tokeninputfield());
                   6075: 	    }
                   6076: 	}
                   6077:     } else {
1.285     albertel 6078: 	&init_perm();
1.104     albertel 6079: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 6080: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 6081: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       6082: 	    &pickStudentPage($request);
1.103     albertel 6083: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       6084: 	    &displayPage($request);
1.104     albertel 6085: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       6086: 	    &updateGradeByPage($request);
1.104     albertel 6087: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       6088: 	    &processGroup($request);
1.104     albertel 6089: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       6090: 	    $request->print(&gradingmenu($request));
1.104     albertel 6091: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       6092: 	    $request->print(&viewgrades($request));
1.104     albertel 6093: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       6094: 	    $request->print(&processHandGrade($request));
1.106     albertel 6095: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       6096: 	    $request->print(&editgrades($request));
1.106     albertel 6097: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       6098: 	    $request->print(&verifyreceipt($request));
1.106     albertel 6099: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       6100: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 6101: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       6102: 	    $request->print(&csvupload($request));
1.106     albertel 6103: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       6104: 	    $request->print(&csvuploadmap($request));
1.246     albertel 6105: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 6106: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 6107: 		$request->print(&csvuploadoptions($request));
1.41      ng       6108: 	    } else {
1.257     albertel 6109: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   6110: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       6111: 		} else {
1.257     albertel 6112: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       6113: 		}
                   6114: 		$request->print(&csvuploadmap($request));
                   6115: 	    }
1.246     albertel 6116: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   6117: 	    $request->print(&csvuploadassign($request));
1.106     albertel 6118: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 6119: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 6120:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   6121:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 6122: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   6123: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 6124: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 6125: 	    $request->print(&scantron_process_students($request));
1.157     albertel 6126:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 6127:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6128: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 6129:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 6130:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 6131:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6132: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 6133:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 6134:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 6135: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 6136:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 6137: 	} elsif ($command) {
1.157     albertel 6138: 	    $request->print("Access Denied ($command)");
1.26      albertel 6139: 	}
1.2       albertel 6140:     }
1.353     albertel 6141:     $request->print(&Apache::loncommon::end_page());
1.44      ng       6142:     return '';
                   6143: }
                   6144: 
1.1       albertel 6145: 1;
                   6146: 
1.13      albertel 6147: __END__;

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