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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.377   ! albertel    4: # $Id: grades.pm,v 1.376 2006/09/22 21:11:55 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.324     albertel  591:     my $symb     = &Apache::lonnet::symbread();
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.71      ng       1472:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   1473: 	'/check.gif" height="16" border="0" />';
                   1474:     my $wgt    = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb,$udom,$uname);
                   1475:     my $wgtmsg = ($wgt > 0 ? '(problem weight)' : 
                   1476: 		  '<font color="red">problem weight assigned by computer</font>');
                   1477:     $wgt       = ($wgt > 0 ? $wgt : '1');
                   1478:     my $score  = ($$record{'resource.'.$partid.'.awarded'} eq '' ?
1.320     albertel 1479: 		  '' : &compute_points($$record{'resource.'.$partid.'.awarded'},$wgt));
1.71      ng       1480:     my $result='<input type="hidden" name="WGT'.$counter.'_'.$partid.'" value="'.$wgt.'" />'."\n";
1.324     albertel 1481:     my $display_part=&get_display_part($partid,$symb);
1.270     albertel 1482:     my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   1483: 				       [$partid]);
                   1484:     my $aggtries = $$record{'resource.'.$partid.'.tries'};
1.269     raeburn  1485:     if ($last_resets{$partid}) {
                   1486:         $aggtries = &get_num_tries($record,$last_resets{$partid},$partid);
                   1487:     }
1.71      ng       1488:     $result.='<table border="0"><tr><td>'.
1.207     albertel 1489: 	'<b>Part: </b>'.$display_part.' <b>Points: </b></td><td>'."\n";
1.71      ng       1490:     my $ctr = 0;
1.348     bowersj2 1491:     my $thisweight = 0;
1.349     albertel 1492:     my $increment = &get_increment();
1.71      ng       1493:     $result.='<table border="0"><tr>'."\n";  # display radio buttons in a nice table 10 across
1.348     bowersj2 1494:     while ($thisweight<=$wgt) {
1.288     albertel 1495: 	$result.= '<td><nobr><label><input type="radio" name="RADVAL'.$counter.'_'.$partid.'" '.
1.71      ng       1496: 	    'onclick="javascript:writeBox(this.form,\''.$counter.'_'.$partid.'\','.
1.348     bowersj2 1497: 	    $thisweight.')" value="'.$thisweight.'" '.
                   1498: 	    ($score eq $thisweight ? 'checked':'').' /> '.$thisweight."</label></nobr></td>\n";
1.71      ng       1499: 	$result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
1.348     bowersj2 1500:         $thisweight += $increment;
1.71      ng       1501: 	$ctr++;
                   1502:     }
                   1503:     $result.='</tr></table>';
                   1504:     $result.='</td><td>&nbsp;<b>or</b>&nbsp;</td>'."\n";
                   1505:     $result.='<td><input type="text" name="GD_BOX'.$counter.'_'.$partid.'"'.
                   1506: 	($score ne ''? ' value = "'.$score.'"':'').' size="4" '.
                   1507: 	'onChange="javascript:updateRadio(this.form,\''.$counter.'_'.$partid.'\','.
                   1508: 	$wgt.')" /></td>'."\n";
                   1509:     $result.='<td>/'.$wgt.' '.$wgtmsg.
                   1510: 	($$record{'resource.'.$partid.'.solved'} eq 'correct_by_student' ? '&nbsp;'.$checkIcon : '').
                   1511: 	' </td><td>'."\n";
                   1512:     $result.='<select name="GD_SEL'.$counter.'_'.$partid.'" '.
                   1513: 	'onChange="javascript:clearRadBox(this.form,\''.$counter.'_'.$partid.'\')" >'."\n";
                   1514:     if ($$record{'resource.'.$partid.'.solved'} eq 'excused') {
                   1515: 	$result.='<option> </option>'.
1.125     ng       1516: 	    '<option selected="on">excused</option>';
1.71      ng       1517:     } else {
                   1518: 	$result.='<option selected="on"> </option>'.
1.125     ng       1519: 	    '<option>excused</option>';
1.71      ng       1520:     }
1.125     ng       1521:     $result.='<option>reset status</option></select>'."\n";
1.71      ng       1522:     $result.="&nbsp&nbsp\n";
                   1523:     $result.='<input type="hidden" name="stores'.$counter.'_'.$partid.'" value="" />'."\n".
                   1524: 	'<input type="hidden" name="oldpts'.$counter.'_'.$partid.'" value="'.$score.'" />'."\n".
                   1525: 	'<input type="hidden" name="solved'.$counter.'_'.$partid.'" value="'.
1.269     raeburn  1526: 	$$record{'resource.'.$partid.'.solved'}.'" />'."\n".
                   1527:         '<input type="hidden" name="totaltries'.$counter.'_'.$partid.'" value="'.
                   1528:         $$record{'resource.'.$partid.'.tries'}.'" />'."\n".
                   1529:         '<input type="hidden" name="aggtries'.$counter.'_'.$partid.'" value="'.
                   1530:         $aggtries.'" />'."\n";
1.71      ng       1531:     $result.='</td></tr></table>'."\n";
1.323     banghart 1532:     $result.=&handback_box($symb,$uname,$udom,$counter,$partid,$record);
1.318     banghart 1533:     return $result;
                   1534: }
1.322     albertel 1535: 
                   1536: sub handback_box {
1.323     banghart 1537:     my ($symb,$uname,$udom,$counter,$partid,$record) = @_;
1.324     albertel 1538:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.323     banghart 1539:     my (@respids);
1.375     albertel 1540:      my @part_response_id = &flatten_responseType($responseType);
                   1541:     foreach my $part_response_id (@part_response_id) {
                   1542:     	my ($part,$resp) = @{ $part_response_id };
1.323     banghart 1543:         if ($part eq $partid) {
1.375     albertel 1544:             push(@respids,$resp);
1.323     banghart 1545:         }
                   1546:     }
1.318     banghart 1547:     my $result;
1.323     banghart 1548:     foreach my $respid (@respids) {
1.322     albertel 1549: 	my $prefix = $counter.'_'.$partid.'_'.$respid.'_';
                   1550: 	my $files=&get_submitted_files($udom,$uname,$partid,$respid,$record);
                   1551: 	next if (!@$files);
                   1552: 	my $file_counter = 1;
1.313     banghart 1553: 	foreach my $file (@$files) {
1.368     banghart 1554: 	    if ($file =~ /\/portfolio\//) {
                   1555:     	        my ($file_path, $file_disp) = ($file =~ m|(.+/)(.+)$|);
                   1556:     	        my ($name,$version,$ext) = &file_name_version_ext($file_disp);
                   1557:     	        $file_disp = "$name.$ext";
                   1558:     	        $file = $file_path.$file_disp;
                   1559:     	        $result.=&mt('Return commented version of [_1] to student.',
                   1560:     			 '<span class="LC_filename">'.$file_disp.'</span>');
                   1561:     	        $result.='<input type="file"   name="'.$prefix.'returndoc'.$file_counter.'" />'."\n";
                   1562:     	        $result.='<input type="hidden" name="'.$prefix.'origdoc'.$file_counter.'" value="'.$file.'" /><br />';
1.369     banghart 1563:     	        $result.='(File will be uploaded when you click on Save & Next below.)<br />';
1.368     banghart 1564:     	        $file_counter++;
                   1565: 	    }
1.322     albertel 1566: 	}
1.313     banghart 1567:     }
1.318     banghart 1568:     return $result;    
1.71      ng       1569: }
1.44      ng       1570: 
1.58      albertel 1571: sub show_problem {
1.144     albertel 1572:     my ($request,$symb,$uname,$udom,$removeform,$viewon,$mode) = @_;
                   1573:     my $rendered;
1.329     albertel 1574:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1575:     if ($mode eq 'both' or $mode eq 'text') {
                   1576: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.257     albertel 1577: 					     $env{'request.course.id'});
1.144     albertel 1578:     }
1.58      albertel 1579:     if ($removeform) {
                   1580: 	$rendered=~s|<form(.*?)>||g;
                   1581: 	$rendered=~s|</form>||g;
1.374     albertel 1582: 	$rendered=~s|(<input[^>]*name\s*=\s*"?)(\w+)("?)|$1would_have_been_$2$3|g;
1.58      albertel 1583:     }
1.144     albertel 1584:     my $companswer;
                   1585:     if ($mode eq 'both' or $mode eq 'answer') {
1.329     albertel 1586: 	&Apache::lonxml::restore_problem_counter();
1.144     albertel 1587: 	$companswer=&Apache::loncommon::get_student_answers($symb,$uname,$udom,
1.257     albertel 1588: 						    $env{'request.course.id'});
1.144     albertel 1589:     }
1.58      albertel 1590:     if ($removeform) {
                   1591: 	$companswer=~s|<form(.*?)>||g;
                   1592: 	$companswer=~s|</form>||g;
1.144     albertel 1593: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1594:     }
                   1595:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1596:     $result.='<table border="0" width="100%">';
1.144     albertel 1597:     if ($viewon) {
                   1598: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1599: 	if ($mode eq 'both' or $mode eq 'text') {
                   1600: 	    $result.='View of the problem - ';
                   1601: 	} else {
                   1602: 	    $result.='Correct answer: ';
                   1603: 	}
1.257     albertel 1604: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1605:     }
                   1606:     if ($mode eq 'both') {
                   1607: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1608: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1609:     } elsif ($mode eq 'text') {
                   1610: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1611:     } elsif ($mode eq 'answer') {
                   1612: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1613:     }
1.58      albertel 1614:     $result.='</td></tr></table>';
                   1615:     $result.='</td></tr></table><br />';
1.71      ng       1616:     return $result;
1.58      albertel 1617: }
                   1618: 
1.44      ng       1619: # --------------------------- show submissions of a student, option to grade 
                   1620: sub submission {
                   1621:     my ($request,$counter,$total) = @_;
                   1622: 
1.257     albertel 1623:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1624:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1625:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1626:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1627: 
1.324     albertel 1628:     my $symb = &get_symb($request); 
                   1629:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1630: 
                   1631:     if (!&canview($usec)) {
1.116     ng       1632: 	$request->print('<font color="red">Unable to view requested student.('.
1.222     albertel 1633: 			$uname.'@'.$udom.' in section '.$usec.' in course id '.
1.257     albertel 1634: 			$env{'request.course.id'}.')</font>');
1.324     albertel 1635: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1636: 	return;
                   1637:     }
                   1638: 
1.257     albertel 1639:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1640:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1641:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1642:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.122     ng       1643:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   1644: 	'/check.gif" height="16" border="0" />';
1.41      ng       1645: 
                   1646:     # header info
                   1647:     if ($counter == 0) {
                   1648: 	&sub_page_js($request);
1.257     albertel 1649: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1650: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1651: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.76      ng       1652: 
1.45      ng       1653: 	$request->print('<h3>&nbsp;<font color="#339933">Submission Record</font></h3>'."\n".
1.257     albertel 1654: 			'<font size=+1>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n");
1.118     ng       1655: 
1.257     albertel 1656: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1657: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1658: 		$checkIcon.' symbol.'."\n";
                   1659: 	    $request->print($checkMark);
                   1660: 	}
1.41      ng       1661: 
1.44      ng       1662: 	# option to display problem, only once else it cause problems 
                   1663:         # with the form later since the problem has a form.
1.257     albertel 1664: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1665: 	    my $mode;
1.257     albertel 1666: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1667: 		$mode='both';
1.257     albertel 1668: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1669: 		$mode='text';
1.257     albertel 1670: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1671: 		$mode='answer';
                   1672: 	    }
1.329     albertel 1673: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1674: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1675: 	}
                   1676: 	
1.44      ng       1677: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1678:         # if this subroutine has been called once.
1.41      ng       1679: 	my %keyhash = ();
1.257     albertel 1680: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1681: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1682: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1683: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1684: 
1.257     albertel 1685: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1686: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1687: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1688: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1689: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1690: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1691: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1692: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1693: 	}
1.257     albertel 1694: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1695: 
1.303     banghart 1696: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1697: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1698: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1699: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1700: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1701: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1702: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1703: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1704: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.41      ng       1705: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
1.257     albertel 1706: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1707: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1708: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1709: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1710: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1711: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1712: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1713: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1714: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1715: 	if ($env{'form.handgrade'} eq 'yes') {
                   1716: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1717: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1718: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1719: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1720: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1721: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1722: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1723: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1724: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1725: 	    }
1.123     ng       1726: 	}
1.41      ng       1727: 	
                   1728: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1729: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1730: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1731: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1732: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1733: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1734: 		'" />'."\n".
                   1735: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1736: 	    $cts++;
                   1737: 	}
                   1738: 	$request->print($prnmsg);
1.32      ng       1739: 
1.257     albertel 1740: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1741: #
                   1742: # Print out the keyword options line
                   1743: #
1.41      ng       1744: 	    $request->print(<<KEYWORDS);
1.38      ng       1745: &nbsp;<b>Keyword Options:</b>&nbsp;
1.122     ng       1746: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
1.38      ng       1747: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1748:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
                   1749: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
                   1750: KEYWORDS
1.88      www      1751: #
                   1752: # Load the other essays for similarity check
                   1753: #
1.324     albertel 1754:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.88      www      1755: 	    my ($adom,$aname,$apath)=($essayurl=~/^(\w+)\/(\w+)\/(.*)$/);
1.359     www      1756: 	    $apath=&escape($apath);
1.88      www      1757: 	    $apath=~s/\W/\_/gs;
                   1758: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1759:         }
                   1760:     }
1.44      ng       1761: 
1.257     albertel 1762:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1763: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1764: 	my $mode;
1.257     albertel 1765: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1766: 	    $mode='both';
1.257     albertel 1767: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1768: 	    $mode='text';
1.257     albertel 1769: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1770: 	    $mode='answer';
                   1771: 	}
1.329     albertel 1772: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1773: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1774:     }
1.144     albertel 1775: 
1.257     albertel 1776:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1777:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1778: 
1.44      ng       1779:     # Display student info
1.41      ng       1780:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1781:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1782: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1783: 
1.257     albertel 1784:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1785:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1786: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1787: 
1.118     ng       1788:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1789:     my @col_fullnames;
1.56      matthew  1790:     my ($classlist,$fullname);
1.257     albertel 1791:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1792: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1793: 	for (keys (%$handgrade)) {
1.44      ng       1794: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1795: 					    '.maxcollaborators',
                   1796:                                             $symb,$udom,$uname);
                   1797: 	    next if ($ncol <= 0);
                   1798:             s/\_/\./g;
                   1799:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1800:             my @goodcollaborators = ();
                   1801:             my @badcollaborators  = ();
                   1802: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1803: 		$_ =~ s/[\$\^\(\)]//g;
                   1804: 		next if ($_ eq '');
1.80      ng       1805: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1806: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1807: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1808: 		# Doing this grep allows 'fuzzy' specification
                   1809: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1810: 		if (! scalar(@Matches)) {
                   1811: 		    push @badcollaborators,$_;
                   1812: 		} else {
                   1813: 		    push @goodcollaborators, @Matches;
                   1814: 		}
1.80      ng       1815: 	    }
1.86      ng       1816:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1817:                 $result.='<b>Collaborators: </b>';
1.86      ng       1818:                 foreach (@goodcollaborators) {
                   1819: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1820: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1821: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1822: 		}
1.57      matthew  1823:                 $result.='<br />'."\n";
1.150     albertel 1824: 		my ($part)=split(/\./,$_);
1.86      ng       1825: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1826: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1827: 		    "\n";
1.86      ng       1828: 	    }
                   1829: 	    if (scalar(@badcollaborators) > 0) {
                   1830: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1831: 		$result.='This student has submitted ';
                   1832: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1833: 		$result .= ': '.join(', ',@badcollaborators);
                   1834: 		$result .= '</td></tr></table>';
                   1835: 	    }         
                   1836: 	    if (scalar(@badcollaborators > $ncol)) {
                   1837: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1838: 		$result .= 'This student has submitted too many '.
                   1839: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1840: 		$result .= '</td></tr></table>';
                   1841: 	    }
1.41      ng       1842: 	}
                   1843:     }
1.44      ng       1844:     $request->print($result."\n");
1.33      ng       1845: 
1.44      ng       1846:     # print student answer/submission
                   1847:     # Options are (1) Handgaded submission only
                   1848:     #             (2) Last submission, includes submission that is not handgraded 
                   1849:     #                  (for multi-response type part)
                   1850:     #             (3) Last submission plus the parts info
                   1851:     #             (4) The whole record for this student
1.257     albertel 1852:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1853: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1854: 	my $lastsubonly=''.
                   1855: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1856: 	     $$timestamp)."</td></tr>\n";
                   1857: 	if ($$timestamp eq '') {
                   1858: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1859: 	} else {
                   1860: 	    my %seenparts;
1.375     albertel 1861: 	    my @part_response_id = &flatten_responseType($responseType);
                   1862: 	    foreach my $part (@part_response_id) {
                   1863: 		my ($partid,$respid) = @{ $part };
1.324     albertel 1864: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1865: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1866: 		    if (exists($seenparts{$partid})) { next; }
                   1867: 		    $seenparts{$partid}=1;
1.207     albertel 1868: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1869: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1870: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1871: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.151     albertel 1872: 			'\')"; TARGET=_self>'.
1.257     albertel 1873: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1874: 		    $request->print($submitby);
                   1875: 		    next;
                   1876: 		}
                   1877: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1878: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1879: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1880: 			$display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1881: 			' )</font>&nbsp; &nbsp;'.
                   1882: 			'<font color="red">Nothing submitted - no attempts</font><br /><br />';
                   1883: 		    next;
                   1884: 		}
                   1885: 		foreach (@$string) {
                   1886: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
1.375     albertel 1887: 		    if (join('_',@{$part}) ne ($partid.'_'.$respid)) { next; }
1.151     albertel 1888: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1889: 		    # Similarity check
                   1890: 		    my $similar='';
1.257     albertel 1891: 		    if($env{'form.checkPlag'}){
1.151     albertel 1892: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   1893: 			    &most_similar($uname,$udom,$subval);
                   1894: 			if ($osim) {
                   1895: 			    $osim=int($osim*100.0);
                   1896: 			    $similar="<hr /><h3><font color=\"#FF0000\">Essay".
                   1897: 				" is $osim% similar to an essay by ".
                   1898: 				&Apache::loncommon::plainname($oname,$odom).
                   1899: 				'</font></h3><blockquote><i>'.
                   1900: 				&keywords_highlight($oessay).
                   1901: 				'</i></blockquote><hr />';
                   1902: 			}
1.150     albertel 1903: 		    }
1.151     albertel 1904: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1905: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1906: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.377   ! albertel 1907: 			 $$handgrade{$$part[0].'_'.$$part[1]} eq 'yes')) {
1.324     albertel 1908: 			my $display_part=&get_display_part($partid,$symb);
1.207     albertel 1909: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1910: 			    $display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1911: 			    ' )</font>&nbsp; &nbsp;';
1.313     banghart 1912: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1913: 			if (@$files) {
1.232     albertel 1914: 			    $lastsubonly.='<br /><font color="red" size="1">Like all files provided by users, this file may contain virusses</font><br />';
1.303     banghart 1915: 			    my $file_counter = 0;
1.313     banghart 1916: 			    foreach my $file (@$files) {
1.303     banghart 1917: 			        $file_counter ++;
1.232     albertel 1918: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.335     albertel 1919: 				$lastsubonly.='<br /><a href="'.$file.'?rawmode=1" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border=0"> '.$file.'</a>';
1.232     albertel 1920: 			    }
1.236     albertel 1921: 			    $lastsubonly.='<br />';
1.41      ng       1922: 			}
1.151     albertel 1923: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1924: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1925: 					 $respid,\%record,$order);
                   1926: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1927: 		    }
                   1928: 		}
                   1929: 	    }
1.151     albertel 1930: 	}
                   1931: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1932: 	$request->print($lastsubonly);
1.257     albertel 1933:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1934: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1935: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1936:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1937: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1938: 								 $env{'request.course.id'},
1.44      ng       1939: 								 $last,'.submission',
                   1940: 								 'Apache::grades::keywords_highlight'));
1.41      ng       1941:     }
1.120     ng       1942: 
1.121     ng       1943:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   1944: 	.$udom.'" />'."\n");
1.41      ng       1945:     
1.44      ng       1946:     # return if view submission with no grading option
1.257     albertel 1947:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       1948: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       1949: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
                   1950: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 1951: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 1952: 	if (($env{'form.command'} eq 'submission') || 
                   1953: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 1954: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 1955: 	}
1.180     albertel 1956: 	$request->print($toGrade);
1.41      ng       1957: 	return;
1.180     albertel 1958:     } else {
                   1959: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       1960:     }
1.33      ng       1961: 
1.121     ng       1962:     # essay grading message center
1.257     albertel 1963:     if ($env{'form.handgrade'} eq 'yes') {
                   1964: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       1965: 	my $msgfor = $givenn.' '.$lastname;
                   1966: 	if (scalar(@col_fullnames) > 0) {
                   1967: 	    my $lastone = pop @col_fullnames;
                   1968: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   1969: 	}
                   1970: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       1971: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   1972: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   1973: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.118     ng       1974: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
1.350     albertel 1975: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a><label> ('.
                   1976: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" /></label>)'.
1.118     ng       1977: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   1978: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      1979: 	    '<br />&nbsp;('.
                   1980: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       1981: 	$request->print($result);
1.118     ng       1982:     }
1.300     albertel 1983:     if ($perm{'vgr'}) {
1.297     www      1984: 	$request->print('<br />'.
1.300     albertel 1985: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   1986: 						   $uname,$udom,'check'));
1.297     www      1987:     }
1.300     albertel 1988:     if ($perm{'opa'}) {
1.297     www      1989: 	$request->print('<br />'.
1.300     albertel 1990: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   1991: 					 $uname,$udom,$symb,'check'));
1.297     www      1992:     }
1.41      ng       1993: 
                   1994:     my %seen = ();
                   1995:     my @partlist;
1.129     ng       1996:     my @gradePartRespid;
1.375     albertel 1997:     my @part_response_id = &flatten_responseType($responseType);
                   1998:     foreach my $part_response_id (@part_response_id) {
                   1999:     	my ($partid,$respid) = @{ $part_response_id };
                   2000: 	my $part_resp = join('_',@{ $part_response_id });
1.322     albertel 2001: 	next if ($seen{$partid} > 0);
1.41      ng       2002: 	$seen{$partid}++;
1.317     banghart 2003: 	next if ($$handgrade{$part_resp} =~ /:no$/ && $env{'form.lastSub'} =~ /^(hdgrade)$/);
1.41      ng       2004: 	push @partlist,$partid;
1.129     ng       2005: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 2006: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       2007:     }
1.45      ng       2008:     $result='<input type="hidden" name="partlist'.$counter.
                   2009: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       2010:     $result.='<input type="hidden" name="gradePartRespid'.
                   2011: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       2012:     my $ctr = 0;
                   2013:     while ($ctr < scalar(@partlist)) {
                   2014: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   2015: 	    $partlist[$ctr].'" />'."\n";
                   2016: 	$ctr++;
                   2017:     }
                   2018:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       2019: 
                   2020:     # print end of form
                   2021:     if ($counter == $total) {
1.297     www      2022: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       2023: 	$endform.='<input type="button" value="Save & Next" '.
                   2024: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
                   2025: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
                   2026: 	my $ntstu ='<select name="NTSTU">'.
                   2027: 	    '<option>1</option><option>2</option>'.
                   2028: 	    '<option>3</option><option>5</option>'.
                   2029: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 2030: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.119     ng       2031: 	$ntstu =~ s/<option>$nsel</<option selected="on">$nsel</;
                   2032: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       2033: 	$endform.='<input type="button" value="Previous" '.
                   2034: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
                   2035: 	    '<input type="button" value="Next" '.
                   2036: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
                   2037: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.349     albertel 2038:         $endform.="<input type='hidden' value='".&get_increment().
1.348     bowersj2 2039:             "' name='increment' />";
1.45      ng       2040: 	$endform.='</td><tr></table></form>';
1.324     albertel 2041: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       2042: 	$request->print($endform);
                   2043:     }
                   2044:     return '';
1.38      ng       2045: }
                   2046: 
1.44      ng       2047: #--- Retrieve the last submission for all the parts
1.38      ng       2048: sub get_last_submission {
1.119     ng       2049:     my ($returnhash)=@_;
1.46      ng       2050:     my (@string,$timestamp);
1.119     ng       2051:     if ($$returnhash{'version'}) {
1.46      ng       2052: 	my %lasthash=();
                   2053: 	my ($version);
1.119     ng       2054: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
                   2055: 	    foreach (sort(split(/\:/,$$returnhash{$version.':keys'}))) {
                   2056: 		$lasthash{$_}=$$returnhash{$version.':'.$_};
                   2057: 		   $timestamp = scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       2058: 	    }
                   2059: 	}
                   2060: 	foreach ((keys %lasthash)) {
                   2061: 	    if ($_ =~ /\.submission$/) {
                   2062: 		my ($partid,$foo) = split(/submission$/,$_);
                   2063: 		my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
                   2064: 		    '<font color="red">Draft Copy</font> ' : '';
                   2065: 		push @string, (join(':',$_,$draft.$lasthash{$_}));
1.41      ng       2066: 	    }
                   2067: 	}
                   2068:     }
1.125     ng       2069:     @string = $string[0] eq '' ? '<font color="red">Nothing submitted - no attempts.</font>' : @string;
1.46      ng       2070:     return \@string,\$timestamp;
1.38      ng       2071: }
1.35      ng       2072: 
1.44      ng       2073: #--- High light keywords, with style choosen by user.
1.38      ng       2074: sub keywords_highlight {
1.44      ng       2075:     my $string    = shift;
1.257     albertel 2076:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   2077:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       2078:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2079:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.41      ng       2080:     foreach (@keylist) {
1.257     albertel 2081: 	$string =~ s/\b\Q$_\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$_$styleoff<\/font>/gi;
1.41      ng       2082:     }
                   2083:     return $string;
1.38      ng       2084: }
1.36      ng       2085: 
1.44      ng       2086: #--- Called from submission routine
1.38      ng       2087: sub processHandGrade {
1.41      ng       2088:     my ($request) = shift;
1.324     albertel 2089:     my $symb   = &get_symb($request);
                   2090:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2091:     my $button = $env{'form.gradeOpt'};
                   2092:     my $ngrade = $env{'form.NCT'};
                   2093:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2094:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2095:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2096: 
1.44      ng       2097:     if ($button eq 'Save & Next') {
                   2098: 	my $ctr = 0;
                   2099: 	while ($ctr < $ngrade) {
1.257     albertel 2100: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2101: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2102: 	    if ($errorflag eq 'no_score') {
                   2103: 		$ctr++;
                   2104: 		next;
                   2105: 	    }
1.104     albertel 2106: 	    if ($errorflag eq 'not_allowed') {
                   2107: 		$request->print("<font color=\"red\">Not allowed to modify grades for $uname:$udom</font>");
                   2108: 		$ctr++;
                   2109: 		next;
                   2110: 	    }
1.257     albertel 2111: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2112: 	    my ($subject,$message,$msgstatus) = ('','','');
1.62      albertel 2113: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2114: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2115: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.362     albertel 2116: 		$subject.=' ['.&Apache::lonnet::declutter($url).']';
1.44      ng       2117: 		my (@msgnum) = split(/,/,$includemsg);
                   2118: 		foreach (@msgnum) {
1.257     albertel 2119: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2120: 		}
1.80      ng       2121: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2122: 		if ($env{'form.withgrades'.$ctr}) {
                   2123: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
                   2124: 		    $message.=" for <a href=\"".
1.80      ng       2125: 		    &Apache::lonnet::clutter($url).
1.257     albertel 2126: 		    "?symb=$symb\">$env{'form.probTitle'}</a>";
1.298     www      2127: 		}
1.324     albertel 2128: 		$msgstatus = &Apache::lonmsg::user_normal_msg($uname,$udom,
1.362     albertel 2129: 							      $subject,
                   2130: 							      $message);
1.296     www      2131: 		$request->print('<br />'.&mt('Sending message to [_1]@[_2]',$uname,$udom).': '.
                   2132: 				$msgstatus);
1.44      ng       2133: 	    }
1.257     albertel 2134: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2135: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2136: 		foreach my $collabstr (@collabstrs) {
                   2137: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2138: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2139: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2140: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2141: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2142: 			if ($errorflag eq 'not_allowed') {
1.362     albertel 2143: 			    $request->print("<span class=\"LC_error\">".&mt('Not allowed to modify grades for [_1]',"$collaborator:$udom")."</span>");
1.150     albertel 2144: 			    next;
                   2145: 			} else {
                   2146: 			    if ($message ne '') {
1.362     albertel 2147: 				$msgstatus = &Apache::lonmsg::user_normal_msg($collaborator,$udom,$subject,$message);
1.150     albertel 2148: 			    }
1.104     albertel 2149: 			}
1.44      ng       2150: 		    }
                   2151: 		}
                   2152: 	    }
                   2153: 	    $ctr++;
                   2154: 	}
                   2155:     }
                   2156: 
1.257     albertel 2157:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2158: 	# Keywords sorted in alphabatical order
1.257     albertel 2159: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2160: 	my %keyhash = ();
1.257     albertel 2161: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2162: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2163: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2164: 	$env{'form.keywords'} = join(' ',@keywords);
                   2165: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2166: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2167: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2168: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2169: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2170: 
                   2171: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2172: 	# New messages are saved in env for the next student.
1.119     ng       2173: 	# All messages are saved in nohist_handgrade.db
                   2174: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2175: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2176: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2177: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2178: 		$idx++;
                   2179: 	    }
                   2180: 	    $ctr++;
1.41      ng       2181: 	}
1.119     ng       2182: 	$ctr = 0;
                   2183: 	while ($ctr < $ngrade) {
1.257     albertel 2184: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2185: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2186: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2187: 		$idx++;
                   2188: 	    }
                   2189: 	    $ctr++;
1.41      ng       2190: 	}
1.257     albertel 2191: 	$env{'form.savemsgN'} = --$idx;
                   2192: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2193: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2194: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2195:     }
1.44      ng       2196:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2197:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2198:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2199: 	my ($ctr,$total) = (0,0);
                   2200: 	while ($ctr < $ngrade) {
1.257     albertel 2201: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2202: 	    $ctr++;
                   2203: 	}
1.257     albertel 2204: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2205: 	$ctr = 0;
                   2206: 	while ($ctr < $total) {
1.257     albertel 2207: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2208: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2209: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2210: 	    &submission($request,$ctr,$total-1);
1.41      ng       2211: 	    $ctr++;
                   2212: 	}
                   2213: 	return '';
                   2214:     }
1.36      ng       2215: 
1.121     ng       2216: # Go directly to grade student - from submission or link from chart page
1.120     ng       2217:     if ($button eq 'Grade Student') {
1.324     albertel 2218: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2219: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2220: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2221: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2222: 	&submission($request,0,0);
                   2223: 	return '';
                   2224:     }
                   2225: 
1.44      ng       2226:     # Get the next/previous one or group of students
1.257     albertel 2227:     my $firststu = $env{'form.unamedom0'};
                   2228:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2229:     my $ctr = 2;
1.41      ng       2230:     while ($laststu eq '') {
1.257     albertel 2231: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2232: 	$ctr++;
                   2233: 	$laststu = $firststu if ($ctr > $ngrade);
                   2234:     }
1.44      ng       2235: 
1.41      ng       2236:     my (@parsedlist,@nextlist);
                   2237:     my ($nextflg) = 0;
1.294     albertel 2238:     foreach (sort 
                   2239: 	     {
                   2240: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2241: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2242: 		 }
                   2243: 		 return $a cmp $b;
                   2244: 	     } (keys(%$fullname))) {
1.41      ng       2245: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2246: 	    push @parsedlist,$_;
                   2247: 	}
                   2248: 	$nextflg = 1 if ($_ eq $laststu);
                   2249: 	if ($button eq 'Previous') {
                   2250: 	    last if ($_ eq $firststu);
                   2251: 	    push @parsedlist,$_;
                   2252: 	}
                   2253:     }
                   2254:     $ctr = 0;
                   2255:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2256:     my ($partlist) = &response_type($symb);
1.41      ng       2257:     foreach my $student (@parsedlist) {
1.257     albertel 2258: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2259: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2260: 	
                   2261: 	if ($submitonly eq 'queued') {
                   2262: 	    my %queue_status = 
                   2263: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2264: 							$udom,$uname);
                   2265: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2266: 	}
                   2267: 
1.156     albertel 2268: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2269: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2270: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2271: 	    my $submitted = 0;
1.248     albertel 2272: 	    my $ungraded = 0;
                   2273: 	    my $incorrect = 0;
1.145     albertel 2274: 	    foreach (keys(%status)) {
                   2275: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2276: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2277: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2278: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2279: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2280: 		    $submitted = 0;
                   2281: 		}
1.41      ng       2282: 	    }
1.156     albertel 2283: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2284: 				     $submitonly eq 'incorrect' ||
                   2285: 				     $submitonly eq 'graded'));
1.248     albertel 2286: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2287: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2288: 	}
                   2289: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2290: 	last if ($ctr == $ntstu);
1.41      ng       2291: 	$ctr++;
                   2292:     }
1.36      ng       2293: 
1.41      ng       2294:     $ctr = 0;
                   2295:     my $total = scalar(@nextlist)-1;
1.39      ng       2296: 
1.41      ng       2297:     foreach (sort @nextlist) {
                   2298: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2299: 	$env{'form.student'}  = $uname;
                   2300: 	$env{'form.userdom'}  = $udom;
                   2301: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2302: 	&submission($request,$ctr,$total);
                   2303: 	$ctr++;
                   2304:     }
                   2305:     if ($total < 0) {
                   2306: 	my $the_end = '<h3><font color="red">LON-CAPA User Message</font></h3><br />'."\n";
                   2307: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2308: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2309: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2310: 	$request->print($the_end);
                   2311:     }
                   2312:     return '';
1.38      ng       2313: }
1.36      ng       2314: 
1.44      ng       2315: #---- Save the score and award for each student, if changed
1.38      ng       2316: sub saveHandGrade {
1.324     albertel 2317:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.342     banghart 2318:     my @version_parts;
1.104     albertel 2319:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2320: 					   $env{'request.course.id'});
1.104     albertel 2321:     if (!&canmodify($usec)) { return('not_allowed'); }
1.337     banghart 2322:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2323:     my @parts_graded;
1.77      ng       2324:     my %newrecord  = ();
                   2325:     my ($pts,$wgt) = ('','');
1.269     raeburn  2326:     my %aggregate = ();
                   2327:     my $aggregateflag = 0;
1.301     albertel 2328:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2329:     foreach my $new_part (@parts) {
1.337     banghart 2330: 	#collaborator ($submi may vary for different parts
1.259     banghart 2331: 	if ($submitter && $new_part ne $part) { next; }
                   2332: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2333: 	if ($dropMenu eq 'excused') {
1.259     banghart 2334: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2335: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2336: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2337: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2338: 		}
1.364     banghart 2339: 	        $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2340: 	    }
1.125     ng       2341: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2342: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2343: 	    foreach my $key (keys (%record)) {
1.259     banghart 2344: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2345: 	    }
1.259     banghart 2346: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2347: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2348:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2349: 
                   2350:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2351: 					       [$new_part]);
                   2352:             my $aggtries =$totaltries;
1.269     raeburn  2353:             if ($last_resets{$new_part}) {
1.270     albertel 2354:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2355: 					   $new_part);
1.269     raeburn  2356:             }
1.270     albertel 2357: 
                   2358:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2359:             if ($aggtries > 0) {
1.327     albertel 2360:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2361:                 $aggregateflag = 1;
                   2362:             }
1.125     ng       2363: 	} elsif ($dropMenu eq '') {
1.259     banghart 2364: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2365: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2366: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2367: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2368: 		next;
                   2369: 	    }
1.259     banghart 2370: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2371: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2372: 	    my $partial= $pts/$wgt;
1.259     banghart 2373: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2374: 		#do not update score for part if not changed.
1.346     banghart 2375:                 &handback_files($request,$symb,$stuname,$domain,$newflg,$new_part,\%newrecord);
1.153     albertel 2376: 		next;
1.251     banghart 2377: 	    } else {
1.259     banghart 2378: 	        push @parts_graded, $new_part;
1.153     albertel 2379: 	    }
1.259     banghart 2380: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2381: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2382: 	    }
1.259     banghart 2383: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2384: 	    if ($partial == 0) {
1.153     albertel 2385: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2386: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2387: 		}
1.41      ng       2388: 	    } else {
1.153     albertel 2389: 		if ($record{$reckey} ne 'correct_by_override') {
                   2390: 		    $newrecord{$reckey} = 'correct_by_override';
                   2391: 		}
                   2392: 	    }	    
                   2393: 	    if ($submitter && 
1.259     banghart 2394: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2395: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2396: 	    }
1.259     banghart 2397: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2398: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2399: 	}
1.259     banghart 2400: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2401: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2402: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2403: 	        $dropMenu eq 'reset status')
                   2404: 	   {
1.342     banghart 2405: 	    push (@version_parts,$new_part);
1.259     banghart 2406: 	}
1.41      ng       2407:     }
1.301     albertel 2408:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2409:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2410: 
1.344     albertel 2411:     if (%newrecord) {
                   2412:         if (@version_parts) {
1.364     banghart 2413:             my @changed_keys = &version_portfiles(\%record, \@parts_graded, 
                   2414:                                 $env{'request.course.id'}, $symb, $domain, $stuname, \@version_parts);
1.344     albertel 2415: 	    @newrecord{@changed_keys} = @record{@changed_keys};
1.367     albertel 2416: 	    foreach my $new_part (@version_parts) {
                   2417: 		&handback_files($request,$symb,$stuname,$domain,$newflg,
                   2418: 				$new_part,\%newrecord);
                   2419: 	    }
1.259     banghart 2420:         }
1.44      ng       2421: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2422: 				$env{'request.course.id'},$domain,$stuname);
1.301     albertel 2423: 	my @ungraded_parts;
                   2424: 	foreach my $part (@parts) {
                   2425: 	    if ( !defined($record{'resource.'.$part.'.awarded'})
                   2426: 		 && !defined($newrecord{'resource.'.$part.'.awarded'}) ) {
                   2427: 		push(@ungraded_parts, $part);
                   2428: 	    }
                   2429: 	}
                   2430: 	if ( !@ungraded_parts ) {
                   2431: 	    &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2432: 						   $cnum,$domain,$stuname);
                   2433: 	}
1.41      ng       2434:     }
1.269     raeburn  2435:     if ($aggregateflag) {
                   2436:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2437: 			      $cdom,$cnum);
1.269     raeburn  2438:     }
1.301     albertel 2439:     return ('',$pts,$wgt);
1.36      ng       2440: }
1.322     albertel 2441: 
1.337     banghart 2442: sub handback_files {
                   2443:     my ($request,$symb,$stuname,$domain,$newflg,$new_part,$newrecord) = @_;
1.359     www      2444:     my $portfolio_root = &propath($domain,$stuname).'/userfiles/portfolio';
                   2445:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.375     albertel 2446: 
                   2447:     my @part_response_id = &flatten_responseType($responseType);
                   2448:     foreach my $part_response_id (@part_response_id) {
                   2449:     	my ($part_id,$resp_id) = @{ $part_response_id };
                   2450: 	my $part_resp = join('_',@{ $part_response_id });
1.337     banghart 2451:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
                   2452:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2453:                 my $file_counter = 1;
1.367     albertel 2454: 		my $file_msg;
1.337     banghart 2455:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2456:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.338     banghart 2457:                     my ($directory,$answer_file) = 
                   2458:                         ($env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter} =~ /^(.*?)([^\/]*)$/);
                   2459:                     my ($answer_name,$answer_ver,$answer_ext) =
                   2460: 		        &file_name_version_ext($answer_file);
1.355     banghart 2461: 		    my ($portfolio_path) = ($directory =~ /^.+$stuname\/portfolio(.*)/);
1.341     banghart 2462: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2463: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.355     banghart 2464:                     # fix file name
                   2465:                     my ($save_file_name) = (($directory.$answer_name.".$version.".$answer_ext) =~ /^.+\/${stuname}\/(.*)/);
                   2466:                     my $result=&Apache::lonnet::finishuserfileupload($stuname,$domain,
                   2467:             	                                $newflg.'_'.$part_resp.'_returndoc'.$file_counter,
                   2468:             	                                $save_file_name);
1.337     banghart 2469:                     if ($result !~ m|^/uploaded/|) {
                   2470:                         $request->print('<font color="red"> An errror occured ('.$result.
1.355     banghart 2471:                         ') while trying to upload '.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'</font><br />');
1.356     banghart 2472:                     } else {
1.360     banghart 2473:                         # mark the file as read only
                   2474:                         my @files = ($save_file_name);
1.372     albertel 2475:                         my @what = ($symb,$env{'request.course.id'},'handback');
1.360     banghart 2476:                         &Apache::lonnet::mark_as_readonly($domain,$stuname,\@files,\@what);
1.367     albertel 2477: 			if (exists($$newrecord{"resource.$new_part.$resp_id.handback"})) {
                   2478: 			    $$newrecord{"resource.$new_part.$resp_id.handback"}.=',';
                   2479: 			}
                   2480:                         $$newrecord{"resource.$new_part.$resp_id.handback"} .= $save_file_name;
                   2481: 			$file_msg.= "\n".'<br /><span class="LC_filename"><a href="/uploaded/'."$domain/$stuname/".$save_file_name.'">'.$save_file_name."</a></span><br />";
                   2482: 
1.337     banghart 2483:                     }
                   2484:                     $request->print("<br />".$fname." will be the uploaded file name");
1.354     albertel 2485:                     $request->print(" ".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2486:                     $file_counter++;
                   2487:                 }
1.367     albertel 2488: 		my $subject = "File Handed Back by Instructor ";
                   2489: 		my $message = "A file has been returned that was originally submitted in reponse to: <br />";
                   2490: 		$message .= "<strong>".&Apache::lonnet::gettitle($symb)."</strong><br />";
                   2491: 		$message .= ' The returned file(s) are named: '. $file_msg;
                   2492: 		$message .= " and can be found in your portfolio space.";
                   2493: 		my $url = (&Apache::lonnet::decode_symb($symb))[2];
                   2494: 		$url = &Apache::lonnet::declutter($url);
                   2495: 		my $msgstatus = &Apache::lonmsg::user_normal_msg($stuname,$domain,
                   2496: 								 $subject.' (File Returned) ['.$url.']',$message);                    
                   2497: 
1.337     banghart 2498:             }
                   2499:         }
1.338     banghart 2500:     return;
1.337     banghart 2501: }
                   2502: 
1.313     banghart 2503: sub get_submitted_files {
                   2504:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2505:     my @files;
                   2506:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2507:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2508:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2509:     	    push(@files,$file_url.$file);
                   2510:         }
                   2511:     }
                   2512:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2513:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2514:     }
                   2515:     return (\@files);
                   2516: }
1.322     albertel 2517: 
1.269     raeburn  2518: # ----------- Provides number of tries since last reset.
                   2519: sub get_num_tries {
                   2520:     my ($record,$last_reset,$part) = @_;
                   2521:     my $timestamp = '';
                   2522:     my $num_tries = 0;
                   2523:     if ($$record{'version'}) {
                   2524:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2525:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2526:                 $timestamp = $$record{$version.':timestamp'};
                   2527:                 if ($timestamp > $last_reset) {
                   2528:                     $num_tries ++;
                   2529:                 } else {
                   2530:                     last;
                   2531:                 }
                   2532:             }
                   2533:         }
                   2534:     }
                   2535:     return $num_tries;
                   2536: }
                   2537: 
                   2538: # ----------- Determine decrements required in aggregate totals 
                   2539: sub decrement_aggs {
                   2540:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2541:     my %decrement = (
                   2542:                         attempts => 0,
                   2543:                         users => 0,
                   2544:                         correct => 0
                   2545:                     );
                   2546:     $decrement{'attempts'} = $aggtries;
                   2547:     if ($solvedstatus =~ /^correct/) {
                   2548:         $decrement{'correct'} = 1;
                   2549:     }
                   2550:     if ($aggtries == $totaltries) {
                   2551:         $decrement{'users'} = 1;
                   2552:     }
                   2553:     foreach my $type (keys (%decrement)) {
                   2554:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2555:     }
                   2556:     return;
                   2557: }
                   2558: 
                   2559: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2560: sub get_last_resets {
1.270     albertel 2561:     my ($symb,$courseid,$partids) =@_;
                   2562:     my %last_resets;
1.269     raeburn  2563:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2564:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2565:     my @keys;
                   2566:     foreach my $part (@{$partids}) {
                   2567: 	push(@keys,"$symb\0$part\0resettime");
                   2568:     }
                   2569:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2570: 				     $cdom,$cname);
                   2571:     foreach my $part (@{$partids}) {
                   2572: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2573:     }
1.270     albertel 2574:     return %last_resets;
1.269     raeburn  2575: }
                   2576: 
1.251     banghart 2577: # ----------- Handles creating versions for portfolio files as answers
                   2578: sub version_portfiles {
1.343     banghart 2579:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2580:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2581:     my @returned_keys;
1.255     banghart 2582:     my $parts = join('|', @$parts_graded);
1.359     www      2583:     my $portfolio_root = &propath($domain,$stu_name).
                   2584: 	'/userfiles/portfolio';
1.277     albertel 2585:     foreach my $key (keys(%$record)) {
1.259     banghart 2586:         my $new_portfiles;
1.263     banghart 2587:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2588:             my @versioned_portfiles;
1.367     albertel 2589:             my @portfiles = split(/\s*,\s*/,$$record{$key});
1.252     banghart 2590:             foreach my $file (@portfiles) {
1.306     banghart 2591:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2592:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2593: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2594: 		    &file_name_version_ext($answer_file);
1.306     banghart 2595:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2596:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2597:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2598:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2599:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2600:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
1.367     albertel 2601:                         [$directory.$new_answer],
1.306     banghart 2602:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2603:                 }
1.252     banghart 2604:             }
1.343     banghart 2605:             $$record{$key} = join(',',@versioned_portfiles);
                   2606:             push(@returned_keys,$key);
1.251     banghart 2607:         }
                   2608:     } 
1.343     banghart 2609:     return (@returned_keys);   
1.305     banghart 2610: }
                   2611: 
1.307     banghart 2612: sub get_next_version {
1.341     banghart 2613:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2614:     my $version;
                   2615:     foreach my $row (@$dir_list) {
                   2616:         my ($file) = split(/\&/,$row,2);
                   2617:         my ($file_name,$file_version,$file_ext) =
                   2618: 	    &file_name_version_ext($file);
                   2619:         if (($file_name eq $answer_name) && 
                   2620: 	    ($file_ext eq $answer_ext)) {
                   2621:                 # gets here if filename and extension match, regardless of version
                   2622:                 if ($file_version ne '') {
                   2623:                 # a versioned file is found  so save it for later
                   2624:                 if ($file_version > $version) {
                   2625: 		    $version = $file_version;
                   2626: 	        }
                   2627:             }
                   2628:         }
                   2629:     } 
                   2630:     $version ++;
                   2631:     return($version);
                   2632: }
                   2633: 
1.305     banghart 2634: sub version_selected_portfile {
1.306     banghart 2635:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2636:     my ($answer_name,$answer_ver,$answer_ext) =
                   2637:         &file_name_version_ext($file_name);
                   2638:     my $new_answer;
                   2639:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2640:     if($env{'form.copy'} eq '-1') {
                   2641:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2642:         $new_answer = 'problem getting file';
                   2643:     } else {
                   2644:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2645:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2646:                             $stu_name,$domain,'copy',
                   2647: 		        '/portfolio'.$directory.$new_answer);
                   2648:     }    
                   2649:     return ($new_answer);
1.251     banghart 2650: }
                   2651: 
1.304     albertel 2652: sub file_name_version_ext {
                   2653:     my ($file)=@_;
                   2654:     my @file_parts = split(/\./, $file);
                   2655:     my ($name,$version,$ext);
                   2656:     if (@file_parts > 1) {
                   2657: 	$ext=pop(@file_parts);
                   2658: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2659: 	    $version=pop(@file_parts);
                   2660: 	}
                   2661: 	$name=join('.',@file_parts);
                   2662:     } else {
                   2663: 	$name=join('.',@file_parts);
                   2664:     }
                   2665:     return($name,$version,$ext);
                   2666: }
                   2667: 
1.44      ng       2668: #--------------------------------------------------------------------------------------
                   2669: #
                   2670: #-------------------------- Next few routines handles grading by section or whole class
                   2671: #
                   2672: #--- Javascript to handle grading by section or whole class
1.42      ng       2673: sub viewgrades_js {
                   2674:     my ($request) = shift;
                   2675: 
1.41      ng       2676:     $request->print(<<VIEWJAVASCRIPT);
                   2677: <script type="text/javascript" language="javascript">
1.45      ng       2678:    function writePoint(partid,weight,point) {
1.125     ng       2679: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2680: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2681: 	if (point == "textval") {
1.125     ng       2682: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2683: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2684: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2685: 		var resetbox = false;
                   2686: 		for (var i=0; i<radioButton.length; i++) {
                   2687: 		    if (radioButton[i].checked) {
                   2688: 			textbox.value = i;
                   2689: 			resetbox = true;
                   2690: 		    }
                   2691: 		}
                   2692: 		if (!resetbox) {
                   2693: 		    textbox.value = "";
                   2694: 		}
                   2695: 		return;
                   2696: 	    }
1.109     matthew  2697: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2698: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2699: 				   ") greater than the weight for the part. Accept?");
                   2700: 		if (resp == false) {
                   2701: 		    textbox.value = "";
                   2702: 		    return;
                   2703: 		}
                   2704: 	    }
1.42      ng       2705: 	    for (var i=0; i<radioButton.length; i++) {
                   2706: 		radioButton[i].checked=false;
1.109     matthew  2707: 		if (parseFloat(point) == i) {
1.42      ng       2708: 		    radioButton[i].checked=true;
                   2709: 		}
                   2710: 	    }
1.41      ng       2711: 
1.42      ng       2712: 	} else {
1.125     ng       2713: 	    textbox.value = parseFloat(point);
1.42      ng       2714: 	}
1.41      ng       2715: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2716: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2717: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2718: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2719: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2720: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2721: 	    if (saveval != "correct") {
                   2722: 		scorename.value = point;
1.43      ng       2723: 		if (selname[0].selected != true) {
                   2724: 		    selname[0].selected = true;
                   2725: 		}
1.42      ng       2726: 	    }
                   2727: 	}
1.125     ng       2728: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2729:     }
                   2730: 
                   2731:     function writeRadText(partid,weight) {
1.125     ng       2732: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2733: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2734:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2735: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2736: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2737: 	    for (var i=0; i<radioButton.length; i++) {
                   2738: 		radioButton[i].checked=false;
                   2739: 
                   2740: 	    }
                   2741: 	    textbox.value = "";
                   2742: 
                   2743: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2744: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2745: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2746: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2747: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2748: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2749: 		if ((saveval != "correct") || override) {
1.42      ng       2750: 		    scorename.value = "";
1.125     ng       2751: 		    if (selval[1].selected) {
                   2752: 			selname[1].selected = true;
                   2753: 		    } else {
                   2754: 			selname[2].selected = true;
                   2755: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2756: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2757: 		    }
1.42      ng       2758: 		}
                   2759: 	    }
1.43      ng       2760: 	} else {
                   2761: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2762: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2763: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2764: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2765: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2766: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2767: 		if ((saveval != "correct") || override) {
1.125     ng       2768: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2769: 		    selname[0].selected = true;
                   2770: 		}
                   2771: 	    }
                   2772: 	}	    
1.42      ng       2773:     }
                   2774: 
                   2775:     function changeSelect(partid,user) {
1.125     ng       2776: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2777: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2778: 	var point  = textbox.value;
1.125     ng       2779: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2780: 
1.109     matthew  2781: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2782: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2783: 	    textbox.value = "";
                   2784: 	    return;
                   2785: 	}
1.109     matthew  2786: 	if (parseFloat(point) > parseFloat(weight)) {
                   2787: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2788: 			       ") greater than the weight of the part. Accept?");
                   2789: 	    if (resp == false) {
                   2790: 		textbox.value = "";
                   2791: 		return;
                   2792: 	    }
                   2793: 	}
1.42      ng       2794: 	selval[0].selected = true;
                   2795:     }
                   2796: 
                   2797:     function changeOneScore(partid,user) {
1.125     ng       2798: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2799: 	if (selval[1].selected || selval[2].selected) {
                   2800: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2801: 	    if (selval[2].selected) {
                   2802: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2803: 	    }
1.269     raeburn  2804:         }
1.42      ng       2805:     }
                   2806: 
                   2807:     function resetEntry(numpart) {
                   2808: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2809: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2810: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2811: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2812: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2813: 	    for (var i=0; i<radioButton.length; i++) {
                   2814: 		radioButton[i].checked=false;
                   2815: 
                   2816: 	    }
                   2817: 	    textbox.value = "";
                   2818: 	    selval[0].selected = true;
                   2819: 
                   2820: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2821: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2822: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2823: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2824: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2825: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2826: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2827: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2828: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2829: 		if (saveselval == "excused") {
1.43      ng       2830: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2831: 		} else {
1.43      ng       2832: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2833: 		}
                   2834: 	    }
1.41      ng       2835: 	}
1.42      ng       2836:     }
                   2837: 
1.41      ng       2838: </script>
                   2839: VIEWJAVASCRIPT
1.42      ng       2840: }
                   2841: 
1.44      ng       2842: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2843: sub viewgrades {
                   2844:     my ($request) = shift;
                   2845:     &viewgrades_js($request);
1.41      ng       2846: 
1.324     albertel 2847:     my ($symb) = &get_symb($request);
1.168     albertel 2848:     #need to make sure we have the correct data for later EXT calls, 
                   2849:     #thus invalidate the cache
                   2850:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2851:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2852:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2853:     &Apache::lonnet::clear_EXT_cache_status();
                   2854: 
1.167     sakharuk 2855:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
1.257     albertel 2856:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
1.41      ng       2857: 
                   2858:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2859:     $result.=&jscriptNform($symb);
1.41      ng       2860: 
1.44      ng       2861:     #beginning of class grading form
1.41      ng       2862:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2863: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2864: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2865: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2866: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2867: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2868: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2869: 
1.126     ng       2870:     my $sectionClass;
1.257     albertel 2871:     if ($env{'form.section'} eq 'all') {
1.126     ng       2872: 	$sectionClass='Class </h3>';
1.257     albertel 2873:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2874: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2875:     } else {
1.257     albertel 2876: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2877:     }
1.126     ng       2878:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2879:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2880: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2881:     #radio buttons/text box for assigning points for a section or class.
                   2882:     #handles different parts of a problem
1.375     albertel 2883:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.42      ng       2884:     my %weight = ();
                   2885:     my $ctsparts = 0;
1.41      ng       2886:     $result.='<table border="0">';
1.45      ng       2887:     my %seen = ();
1.375     albertel 2888:     my @part_response_id = &flatten_responseType($responseType);
                   2889:     foreach my $part_response_id (@part_response_id) {
                   2890:     	my ($partid,$respid) = @{ $part_response_id };
                   2891: 	my $part_resp = join('_',@{ $part_response_id });
1.45      ng       2892: 	next if $seen{$partid};
                   2893: 	$seen{$partid}++;
1.375     albertel 2894: 	my $handgrade=$$handgrade{$part_resp};
1.42      ng       2895: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2896: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   2897: 
1.44      ng       2898: 	$result.='<input type="hidden" name="partid_'.
                   2899: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   2900: 	$result.='<input type="hidden" name="weight_'.
                   2901: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 2902: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 2903: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       2904: 	$result.='<table border="0"><tr>';  
1.41      ng       2905: 	my $ctr = 0;
1.42      ng       2906: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 2907: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 2908: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 2909: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       2910: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   2911: 	    $ctr++;
                   2912: 	}
                   2913: 	$result.='</tr></table>';
1.44      ng       2914: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 2915: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   2916: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       2917: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   2918: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 2919: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 2920: 		$weight{$partid}.')"> '.
1.42      ng       2921: 	    '<option selected="on"> </option>'.
1.125     ng       2922: 	    '<option>excused</option>'.
1.265     www      2923: 	    '<option>reset status</option></select></td>'.
1.266     albertel 2924:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       2925: 	$ctsparts++;
1.41      ng       2926:     }
1.52      albertel 2927:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   2928: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.42      ng       2929:     $result.='<input type="button" value="Reset" '.
1.111     ng       2930: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       2931: 
1.44      ng       2932:     #table listing all the students in a section/class
                   2933:     #header of table
1.126     ng       2934:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       2935:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       2936: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       2937: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 2938:     my (@parts) = sort(&getpartlist($symb));
                   2939:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  2940:     my @partids = ();
1.41      ng       2941:     foreach my $part (@parts) {
                   2942: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       2943: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       2944: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 2945: 	my ($partid) = &split_part_type($part);
1.269     raeburn  2946:         push(@partids, $partid);
1.324     albertel 2947: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       2948: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 2949: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   2950: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       2951: 	    next;
1.207     albertel 2952: 	} else {
                   2953: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       2954: 	}
1.53      albertel 2955: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 2956: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       2957:     }
                   2958:     $result.='</tr>';
1.44      ng       2959: 
1.270     albertel 2960:     my %last_resets = 
                   2961: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  2962: 
1.41      ng       2963:     #get info for each student
1.44      ng       2964:     #list all the students - with points and grade status
1.257     albertel 2965:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       2966:     my $ctr = 0;
1.294     albertel 2967:     foreach (sort 
                   2968: 	     {
                   2969: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2970: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2971: 		 }
                   2972: 		 return $a cmp $b;
                   2973: 	     } (keys(%$fullname))) {
1.126     ng       2974: 	$ctr++;
1.324     albertel 2975: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  2976: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       2977:     }
                   2978:     $result.='</table></td></tr></table>';
                   2979:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       2980:     $result.='<input type="button" value="Save" '.
1.45      ng       2981: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 2982:     if (scalar(%$fullname) eq 0) {
                   2983: 	my $colspan=3+scalar(@parts);
1.257     albertel 2984: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
                   2985: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
1.96      albertel 2986:     }
1.324     albertel 2987:     $result.=&show_grading_menu_form($symb);
1.41      ng       2988:     return $result;
                   2989: }
                   2990: 
1.44      ng       2991: #--- call by previous routine to display each student
1.41      ng       2992: sub viewstudentgrade {
1.324     albertel 2993:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       2994:     my ($uname,$udom) = split(/:/,$student);
                   2995:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  2996:     my %aggregates = (); 
1.233     albertel 2997:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   2998: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   2999: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       3000: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       3001: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.257     albertel 3002: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
1.281     albertel 3003:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 3004:     foreach my $apart (@$parts) {
                   3005: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       3006: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 3007:         $result.='<td align="center">';
1.269     raeburn  3008:         my ($aggtries,$totaltries);
                   3009:         unless (exists($aggregates{$part})) {
1.270     albertel 3010: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   3011: 
                   3012: 	    $aggtries = $totaltries;
1.269     raeburn  3013:             if ($$last_resets{$part}) {  
1.270     albertel 3014:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   3015: 					   $part);
                   3016:             }
1.269     raeburn  3017:             $result.='<input type="hidden" name="'.
                   3018:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   3019:             $result.='<input type="hidden" name="'.
                   3020:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   3021:             $aggregates{$part} = 1;
                   3022:         }
1.41      ng       3023: 	if ($type eq 'awarded') {
1.320     albertel 3024: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       3025: 	    $result.='<input type="hidden" name="'.
1.89      albertel 3026: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 3027: 	    $result.='<input type="text" name="'.
1.89      albertel 3028: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   3029: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       3030: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       3031: 	} elsif ($type eq 'solved') {
                   3032: 	    my ($status,$foo)=split(/_/,$score,2);
                   3033: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 3034: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3035: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3036: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3037: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3038: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       3039: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   3040: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   3041: 	    $result.='<option>reset status</option>';
1.126     ng       3042: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3043: 	} else {
                   3044: 	    $result.='<input type="hidden" name="'.
                   3045: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3046: 		    "\n";
1.233     albertel 3047: 	    $result.='<input type="text" name="'.
1.122     ng       3048: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3049: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3050: 	}
                   3051:     }
                   3052:     $result.='</tr>';
                   3053:     return $result;
1.38      ng       3054: }
                   3055: 
1.44      ng       3056: #--- change scores for all the students in a section/class
                   3057: #    record does not get update if unchanged
1.38      ng       3058: sub editgrades {
1.41      ng       3059:     my ($request) = @_;
                   3060: 
1.324     albertel 3061:     my $symb=&get_symb($request);
1.45      ng       3062:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
1.257     albertel 3063:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
                   3064:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
1.126     ng       3065: 
1.44      ng       3066:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3067:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3068: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3069: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3070: 
                   3071:     my %scoreptr = (
                   3072: 		    'correct'  =>'correct_by_override',
                   3073: 		    'incorrect'=>'incorrect_by_override',
                   3074: 		    'excused'  =>'excused',
                   3075: 		    'ungraded' =>'ungraded_attempted',
                   3076: 		    'nothing'  => '',
                   3077: 		    );
1.257     albertel 3078:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3079: 
1.44      ng       3080:     my (@partid);
                   3081:     my %weight = ();
1.54      albertel 3082:     my %columns = ();
1.44      ng       3083:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3084: 
1.324     albertel 3085:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3086:     my $header;
1.257     albertel 3087:     while ($ctr < $env{'form.totalparts'}) {
                   3088: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3089: 	push @partid,$partid;
1.257     albertel 3090: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3091: 	$ctr++;
1.54      albertel 3092:     }
1.324     albertel 3093:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3094:     foreach my $partid (@partid) {
                   3095: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3096: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3097: 	$columns{$partid}=2;
                   3098: 	foreach my $stores (@parts) {
                   3099: 	    my ($part,$type) = &split_part_type($stores);
                   3100: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3101: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3102: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3103: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3104: 	    $display =~ s/Number of Attempts/Tries/;
                   3105: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3106: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3107: 	    $columns{$partid}+=2;
                   3108: 	}
                   3109:     }
                   3110:     foreach my $partid (@partid) {
1.324     albertel 3111: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3112: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3113: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3114: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3115: 
1.44      ng       3116:     }
                   3117:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3118:     $result .= $header;
1.44      ng       3119:     $result .= '</tr>'."\n";
1.93      albertel 3120:     my $noupdate;
1.126     ng       3121:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3122:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3123: 	my $line;
1.257     albertel 3124: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3125: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3126: 	my %newrecord;
                   3127: 	my $updateflag = 0;
1.281     albertel 3128: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3129: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3130: 	if (!&canmodify($usec)) {
1.126     ng       3131: 	    my $numcols=scalar(@partid)*4+2;
1.105     albertel 3132: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
                   3133: 	    next;
                   3134: 	}
1.269     raeburn  3135:         my %aggregate = ();
                   3136:         my $aggregateflag = 0;
1.281     albertel 3137: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3138: 	foreach (@partid) {
1.257     albertel 3139: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3140: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3141: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3142: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3143: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3144: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3145: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3146: 	    my $score;
                   3147: 	    if ($partial eq '') {
1.257     albertel 3148: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3149: 	    } elsif ($partial > 0) {
                   3150: 		$score = 'correct_by_override';
                   3151: 	    } elsif ($partial == 0) {
                   3152: 		$score = 'incorrect_by_override';
                   3153: 	    }
1.257     albertel 3154: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3155: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3156: 
1.292     albertel 3157: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3158: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3159: 	    if ($dropMenu eq 'reset status' &&
                   3160: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3161: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3162: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3163: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3164: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3165: 		$updateflag = 1;
1.269     raeburn  3166:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3167:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3168:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3169:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3170:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3171:                     $aggregateflag = 1;
                   3172:                 }
1.139     albertel 3173: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3174: 		$updateflag = 1;
                   3175: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3176: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3177: 		$rec_update++;
1.125     ng       3178: 	    }
                   3179: 
1.93      albertel 3180: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3181: 		'<td align="center">'.$awarded.
                   3182: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3183: 
1.54      albertel 3184: 
                   3185: 	    my $partid=$_;
                   3186: 	    foreach my $stores (@parts) {
                   3187: 		my ($part,$type) = &split_part_type($stores);
                   3188: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3189: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3190: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3191: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3192: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3193: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3194: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3195: 		    $updateflag=1;
                   3196: 		}
1.93      albertel 3197: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3198: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3199: 	    }
1.44      ng       3200: 	}
1.93      albertel 3201: 	$line.='</tr>'."\n";
1.301     albertel 3202: 
                   3203: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3204: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3205: 
1.44      ng       3206: 	if ($updateflag) {
                   3207: 	    $count++;
1.257     albertel 3208: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3209: 				    $udom,$uname);
1.301     albertel 3210: 
                   3211: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3212: 					      $cnum,$udom,$uname)) {
                   3213: 		# need to figure out if should be in queue.
                   3214: 		my %record =  
                   3215: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3216: 					     $udom,$uname);
                   3217: 		my $all_graded = 1;
                   3218: 		my $none_graded = 1;
                   3219: 		foreach my $part (@parts) {
                   3220: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3221: 			$all_graded = 0;
                   3222: 		    } else {
                   3223: 			$none_graded = 0;
                   3224: 		    }
                   3225: 		}
                   3226: 
                   3227: 		if ($all_graded || $none_graded) {
                   3228: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3229: 							   $symb,$cdom,$cnum,
                   3230: 							   $udom,$uname);
                   3231: 		}
                   3232: 	    }
                   3233: 
1.126     ng       3234: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3235: 	    $updateCtr++;
1.93      albertel 3236: 	} else {
1.126     ng       3237: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3238: 	    $noupdateCtr++;
1.44      ng       3239: 	}
1.269     raeburn  3240:         if ($aggregateflag) {
                   3241:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3242: 				  $cdom,$cnum);
1.269     raeburn  3243:         }
1.93      albertel 3244:     }
                   3245:     if ($noupdate) {
1.126     ng       3246: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3247: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3248: 	$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       3249:     }
1.72      ng       3250:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3251: 	&show_grading_menu_form ($symb);
1.125     ng       3252:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3253: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3254: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3255:     return $title.$msg.$result;
1.5       albertel 3256: }
1.54      albertel 3257: 
                   3258: sub split_part_type {
                   3259:     my ($partstr) = @_;
                   3260:     my ($temp,@allparts)=split(/_/,$partstr);
                   3261:     my $type=pop(@allparts);
                   3262:     my $part=join('.',@allparts);
                   3263:     return ($part,$type);
                   3264: }
                   3265: 
1.44      ng       3266: #------------- end of section for handling grading by section/class ---------
                   3267: #
                   3268: #----------------------------------------------------------------------------
                   3269: 
1.5       albertel 3270: 
1.44      ng       3271: #----------------------------------------------------------------------------
                   3272: #
                   3273: #-------------------------- Next few routines handles grading by csv upload
                   3274: #
                   3275: #--- Javascript to handle csv upload
1.27      albertel 3276: sub csvupload_javascript_reverse_associate {
1.246     albertel 3277:     my $error1=&mt('You need to specify the username or ID');
                   3278:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3279:   return(<<ENDPICK);
                   3280:   function verify(vf) {
                   3281:     var foundsomething=0;
                   3282:     var founduname=0;
1.243     albertel 3283:     var foundID=0;
1.27      albertel 3284:     for (i=0;i<=vf.nfields.value;i++) {
                   3285:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3286:       if (i==0 && tw!=0) { foundID=1; }
                   3287:       if (i==1 && tw!=0) { founduname=1; }
                   3288:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3289:     }
1.246     albertel 3290:     if (founduname==0 && foundID==0) {
                   3291: 	alert('$error1');
                   3292: 	return;
1.27      albertel 3293:     }
                   3294:     if (foundsomething==0) {
1.246     albertel 3295: 	alert('$error2');
                   3296: 	return;
1.27      albertel 3297:     }
                   3298:     vf.submit();
                   3299:   }
                   3300:   function flip(vf,tf) {
                   3301:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3302:     var i;
                   3303:     for (i=0;i<=vf.nfields.value;i++) {
                   3304:       //can not pick the same destination field for both name and domain
                   3305:       if (((i ==0)||(i ==1)) && 
                   3306:           ((tf==0)||(tf==1)) && 
                   3307:           (i!=tf) &&
                   3308:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3309:         eval('vf.f'+i+'.selectedIndex=0;')
                   3310:       }
                   3311:     }
                   3312:   }
                   3313: ENDPICK
                   3314: }
                   3315: 
                   3316: sub csvupload_javascript_forward_associate {
1.246     albertel 3317:     my $error1=&mt('You need to specify the username or ID');
                   3318:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3319:   return(<<ENDPICK);
                   3320:   function verify(vf) {
                   3321:     var foundsomething=0;
                   3322:     var founduname=0;
1.243     albertel 3323:     var foundID=0;
1.27      albertel 3324:     for (i=0;i<=vf.nfields.value;i++) {
                   3325:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3326:       if (tw==1) { foundID=1; }
                   3327:       if (tw==2) { founduname=1; }
                   3328:       if (tw>3) { foundsomething=1; }
1.27      albertel 3329:     }
1.246     albertel 3330:     if (founduname==0 && foundID==0) {
                   3331: 	alert('$error1');
                   3332: 	return;
1.27      albertel 3333:     }
                   3334:     if (foundsomething==0) {
1.246     albertel 3335: 	alert('$error2');
                   3336: 	return;
1.27      albertel 3337:     }
                   3338:     vf.submit();
                   3339:   }
                   3340:   function flip(vf,tf) {
                   3341:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3342:     var i;
                   3343:     //can not pick the same destination field twice
                   3344:     for (i=0;i<=vf.nfields.value;i++) {
                   3345:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3346:         eval('vf.f'+i+'.selectedIndex=0;')
                   3347:       }
                   3348:     }
                   3349:   }
                   3350: ENDPICK
                   3351: }
                   3352: 
1.26      albertel 3353: sub csvuploadmap_header {
1.324     albertel 3354:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3355:     my $javascript;
1.257     albertel 3356:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3357: 	$javascript=&csvupload_javascript_reverse_associate();
                   3358:     } else {
                   3359: 	$javascript=&csvupload_javascript_forward_associate();
                   3360:     }
1.45      ng       3361: 
1.324     albertel 3362:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3363:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3364:     my $ignore=&mt('Ignore First Line');
1.41      ng       3365:     $request->print(<<ENDPICK);
1.26      albertel 3366: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.45      ng       3367: <h3><font color="#339933">Uploading Class Grades</font></h3>
                   3368: $result
1.326     albertel 3369: <hr />
1.26      albertel 3370: <h3>Identify fields</h3>
                   3371: Total number of records found in file: $distotal <hr />
                   3372: Enter as many fields as you can. The system will inform you and bring you back
                   3373: to this page if the data selected is insufficient to run your class.<hr />
                   3374: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3375: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3376: <input type="hidden" name="associate"  value="" />
                   3377: <input type="hidden" name="phase"      value="three" />
                   3378: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3379: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3380: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3381: <input type="hidden" name="upfile_associate" 
1.257     albertel 3382:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3383: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3384: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3385: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3386: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3387: <hr />
                   3388: <script type="text/javascript" language="Javascript">
                   3389: $javascript
                   3390: </script>
                   3391: ENDPICK
1.118     ng       3392:     return '';
1.26      albertel 3393: 
                   3394: }
                   3395: 
                   3396: sub csvupload_fields {
1.324     albertel 3397:     my ($symb) = @_;
                   3398:     my (@parts) = &getpartlist($symb);
1.243     albertel 3399:     my @fields=(['ID','Student ID'],
                   3400: 		['username','Student Username'],
                   3401: 		['domain','Student Domain']);
1.324     albertel 3402:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3403:     foreach my $part (sort(@parts)) {
                   3404: 	my @datum;
                   3405: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3406: 	my $name=$part;
                   3407: 	if  (!$display) { $display = $name; }
                   3408: 	@datum=($name,$display);
1.244     albertel 3409: 	if ($name=~/^stores_(.*)_awarded/) {
                   3410: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3411: 	}
1.41      ng       3412: 	push(@fields,\@datum);
                   3413:     }
                   3414:     return (@fields);
1.26      albertel 3415: }
                   3416: 
                   3417: sub csvuploadmap_footer {
1.41      ng       3418:     my ($request,$i,$keyfields) =@_;
                   3419:     $request->print(<<ENDPICK);
1.26      albertel 3420: </table>
                   3421: <input type="hidden" name="nfields" value="$i" />
                   3422: <input type="hidden" name="keyfields" value="$keyfields" />
                   3423: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3424: </form>
                   3425: ENDPICK
                   3426: }
                   3427: 
1.283     albertel 3428: sub checkforfile_js {
1.86      ng       3429:     my $result =<<CSVFORMJS;
                   3430: <script type="text/javascript" language="javascript">
                   3431:     function checkUpload(formname) {
                   3432: 	if (formname.upfile.value == "") {
                   3433: 	    alert("Please use the browse button to select a file from your local directory.");
                   3434: 	    return false;
                   3435: 	}
                   3436: 	formname.submit();
                   3437:     }
                   3438:     </script>
                   3439: CSVFORMJS
1.283     albertel 3440:     return $result;
                   3441: }
                   3442: 
                   3443: sub upcsvScores_form {
                   3444:     my ($request) = shift;
1.324     albertel 3445:     my ($symb)=&get_symb($request);
1.283     albertel 3446:     if (!$symb) {return '';}
                   3447:     my $result=&checkforfile_js();
1.257     albertel 3448:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3449:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3450:     $result.=$table;
1.326     albertel 3451:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3452:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.370     www      3453:     $result.='&nbsp;<b>'.&mt('Specify a file containing the class scores for current resource').
1.86      ng       3454: 	'.</b></td></tr>'."\n";
                   3455:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
1.370     www      3456:     my $upload=&mt("Upload Scores");
1.86      ng       3457:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3458:     my $ignore=&mt('Ignore First Line');
1.86      ng       3459:     $result.=<<ENDUPFORM;
1.106     albertel 3460: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3461: <input type="hidden" name="symb" value="$symb" />
                   3462: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3463: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3464: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3465: $upfile_select
1.370     www      3466: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="$upload" />
1.283     albertel 3467: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3468: </form>
                   3469: ENDUPFORM
1.370     www      3470:     $result.=&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                   3471:                            &mt("How do I create a CSV file from a spreadsheet"))
                   3472:     .'</td></tr></table>'."\n";
1.86      ng       3473:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3474:     $result.=&show_grading_menu_form($symb);
1.86      ng       3475:     return $result;
                   3476: }
                   3477: 
                   3478: 
1.26      albertel 3479: sub csvuploadmap {
1.41      ng       3480:     my ($request)= @_;
1.324     albertel 3481:     my ($symb)=&get_symb($request);
1.41      ng       3482:     if (!$symb) {return '';}
1.72      ng       3483: 
1.41      ng       3484:     my $datatoken;
1.257     albertel 3485:     if (!$env{'form.datatoken'}) {
1.41      ng       3486: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3487:     } else {
1.257     albertel 3488: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3489: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3490:     }
1.41      ng       3491:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3492:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3493:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3494:     my ($i,$keyfields);
                   3495:     if (@records) {
1.324     albertel 3496: 	my @fields=&csvupload_fields($symb);
1.45      ng       3497: 
1.257     albertel 3498: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3499: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3500: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3501: 							  \@fields);
                   3502: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3503: 	    chop($keyfields);
                   3504: 	} else {
                   3505: 	    unshift(@fields,['none','']);
                   3506: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3507: 							    \@fields);
1.311     banghart 3508:             foreach my $rec (@records) {
                   3509:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3510:                 if (%temp) {
                   3511:                     $keyfields=join(',',sort(keys(%temp)));
                   3512:                     last;
                   3513:                 }
                   3514:             }
1.41      ng       3515: 	}
                   3516:     }
                   3517:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3518:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3519: 
1.41      ng       3520:     return '';
1.27      albertel 3521: }
                   3522: 
1.246     albertel 3523: sub csvuploadoptions {
1.41      ng       3524:     my ($request)= @_;
1.324     albertel 3525:     my ($symb)=&get_symb($request);
1.257     albertel 3526:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3527:     my $ignore=&mt('Ignore First Line');
                   3528:     $request->print(<<ENDPICK);
                   3529: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3530: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
                   3531: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3532: <!--
1.246     albertel 3533: <p>
                   3534: <label>
                   3535:    <input type="checkbox" name="show_full_results" />
                   3536:    Show a table of all changes
                   3537: </label>
                   3538: </p>
1.302     albertel 3539: -->
1.246     albertel 3540: <p>
                   3541: <label>
                   3542:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3543:    Overwrite any existing score
                   3544: </label>
                   3545: </p>
                   3546: ENDPICK
                   3547:     my %fields=&get_fields();
                   3548:     if (!defined($fields{'domain'})) {
1.257     albertel 3549: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3550: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3551:     }
1.257     albertel 3552:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3553: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3554: 	my $cleankey=$1;
                   3555: 	if ($cleankey eq 'command') { next; }
                   3556: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3557: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3558:     }
                   3559:     # FIXME do a check for any duplicated user ids...
                   3560:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3561:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3562: <hr /></form>'."\n");
1.324     albertel 3563:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3564:     return '';
                   3565: }
                   3566: 
                   3567: sub get_fields {
                   3568:     my %fields;
1.257     albertel 3569:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3570:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3571: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3572: 	    if ($env{'form.f'.$i} ne 'none') {
                   3573: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3574: 	    }
                   3575: 	} else {
1.257     albertel 3576: 	    if ($env{'form.f'.$i} ne 'none') {
                   3577: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3578: 	    }
                   3579: 	}
1.27      albertel 3580:     }
1.246     albertel 3581:     return %fields;
                   3582: }
                   3583: 
                   3584: sub csvuploadassign {
                   3585:     my ($request)= @_;
1.324     albertel 3586:     my ($symb)=&get_symb($request);
1.246     albertel 3587:     if (!$symb) {return '';}
1.345     bowersj2 3588:     my $error_msg = '';
1.246     albertel 3589:     &Apache::loncommon::load_tmp_file($request);
                   3590:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3591:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3592:     my %fields=&get_fields();
1.41      ng       3593:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3594:     my $courseid=$env{'request.course.id'};
1.97      albertel 3595:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3596:     my @notallowed;
1.41      ng       3597:     my @skipped;
                   3598:     my $countdone=0;
                   3599:     foreach my $grade (@gradedata) {
                   3600: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3601: 	my $domain;
                   3602: 	if ($entries{$fields{'domain'}}) {
                   3603: 	    $domain=$entries{$fields{'domain'}};
                   3604: 	} else {
1.257     albertel 3605: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3606: 	}
1.243     albertel 3607: 	$domain=~s/\s//g;
1.41      ng       3608: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3609: 	$username=~s/\s//g;
1.243     albertel 3610: 	if (!$username) {
                   3611: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3612: 	    $id=~s/\s//g;
1.243     albertel 3613: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3614: 	    $username=$ids{$id};
                   3615: 	}
1.41      ng       3616: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3617: 	    my $id=$entries{$fields{'ID'}};
                   3618: 	    $id=~s/\s//g;
                   3619: 	    if ($id) {
                   3620: 		push(@skipped,"$id:$domain");
                   3621: 	    } else {
                   3622: 		push(@skipped,"$username:$domain");
                   3623: 	    }
1.41      ng       3624: 	    next;
                   3625: 	}
1.108     albertel 3626: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3627: 	if (!&canmodify($usec)) {
                   3628: 	    push(@notallowed,"$username:$domain");
                   3629: 	    next;
                   3630: 	}
1.244     albertel 3631: 	my %points;
1.41      ng       3632: 	my %grades;
                   3633: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3634: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3635: 		$dest eq 'domain') { next; }
                   3636: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3637: 	    if ($dest=~/stores_(.*)_points/) {
                   3638: 		my $part=$1;
                   3639: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3640: 					      $symb,$domain,$username);
1.345     bowersj2 3641:                 if ($wgt) {
                   3642:                     $entries{$fields{$dest}}=~s/\s//g;
                   3643:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3644:                     my $award='correct_by_override';
                   3645:                     $grades{"resource.$part.awarded"}=$pcr;
                   3646:                     $grades{"resource.$part.solved"}=$award;
                   3647:                     $points{$part}=1;
                   3648:                 } else {
                   3649:                     $error_msg = "<br />" .
                   3650:                         &mt("Some point values were assigned"
                   3651:                             ." for problems with a weight "
                   3652:                             ."of zero. These values were "
                   3653:                             ."ignored.");
                   3654:                 }
1.244     albertel 3655: 	    } else {
                   3656: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3657: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3658: 		my $store_key=$dest;
                   3659: 		$store_key=~s/^stores/resource/;
                   3660: 		$store_key=~s/_/\./g;
                   3661: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3662: 	    }
1.41      ng       3663: 	}
1.244     albertel 3664: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
1.257     albertel 3665: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3666: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3667: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3668: 					   $env{'request.course.id'},
                   3669: 					   $domain,$username);
                   3670: 	if ($result eq 'ok') {
                   3671: 	    $request->print('.');
                   3672: 	} else {
                   3673: 	    $request->print("<p>
                   3674:                               <font color='red'>
                   3675:                                  Failed to store student $username\@$domain.
                   3676:                                  Message when trying to store was ($result)
                   3677:                               </font>
                   3678:                              </p>" );
                   3679: 	}
1.41      ng       3680: 	$request->rflush();
                   3681: 	$countdone++;
                   3682:     }
                   3683:     $request->print("<br />Stored $countdone students\n");
                   3684:     if (@skipped) {
1.325     www      3685: 	$request->print('<p><font size="+1"><b>Skipped Students</b></font></p>');
1.106     albertel 3686: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3687:     }
                   3688:     if (@notallowed) {
                   3689: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
                   3690: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3691:     }
1.106     albertel 3692:     $request->print("<br />\n");
1.324     albertel 3693:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3694:     return $error_msg;
1.26      albertel 3695: }
1.44      ng       3696: #------------- end of section for handling csv file upload ---------
                   3697: #
                   3698: #-------------------------------------------------------------------
                   3699: #
1.122     ng       3700: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3701: #
                   3702: #--- Select a page/sequence and a student to grade
1.68      ng       3703: sub pickStudentPage {
                   3704:     my ($request) = shift;
                   3705: 
                   3706:     $request->print(<<LISTJAVASCRIPT);
                   3707: <script type="text/javascript" language="javascript">
                   3708: 
                   3709: function checkPickOne(formname) {
1.76      ng       3710:     if (radioSelection(formname.student) == null) {
1.68      ng       3711: 	alert("Please select the student you wish to grade.");
                   3712: 	return;
                   3713:     }
1.125     ng       3714:     ptr = pullDownSelection(formname.selectpage);
                   3715:     formname.page.value = formname["page"+ptr].value;
                   3716:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3717:     formname.submit();
                   3718: }
                   3719: 
                   3720: </script>
                   3721: LISTJAVASCRIPT
1.118     ng       3722:     &commonJSfunctions($request);
1.324     albertel 3723:     my ($symb) = &get_symb($request);
1.257     albertel 3724:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3725:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3726:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3727: 
                   3728:     my $result='<h3><font color="#339933">&nbsp;'.
                   3729: 	'Manual Grading by Page or Sequence</font></h3>';
                   3730: 
1.80      ng       3731:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3732:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3733:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3734:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3735: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3736: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3737:     my $ctr=0;
1.68      ng       3738:     foreach (@$titles) {
                   3739: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3740: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3741: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3742: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3743: 	$ctr++;
1.68      ng       3744:     }
1.326     albertel 3745:     $result.= '</select>'."<br />\n";
1.70      ng       3746:     $ctr=0;
                   3747:     foreach (@$titles) {
                   3748: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3749: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3750: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3751: 	$ctr++;
                   3752:     }
1.72      ng       3753:     $result.='<input type="hidden" name="page" />'."\n".
                   3754: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3755: 
1.288     albertel 3756:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                   3757: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3758: 
1.71      ng       3759:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3760: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
                   3761: 	'<label><input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions</label>'."\n".
                   3762: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3763: 
1.68      ng       3764:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3765: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3766: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3767: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3768: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3769: 
1.80      ng       3770:     $result.='&nbsp;<input type="button" '.
1.126     ng       3771: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3772: 
1.68      ng       3773:     $request->print($result);
                   3774: 
1.326     albertel 3775:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3776: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3777: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3778: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3779: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3780: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3781: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3782:  
1.76      ng       3783:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3784:     my $ptr = 1;
1.294     albertel 3785:     foreach my $student (sort 
                   3786: 			 {
                   3787: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3788: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3789: 			     }
                   3790: 			     return $a cmp $b;
                   3791: 			 } (keys(%$fullname))) {
1.68      ng       3792: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3793: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3794: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3795: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3796: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3797: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3798: 	$ptr++;
                   3799:     }
1.126     ng       3800:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
1.68      ng       3801:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
1.126     ng       3802:     $studentTable.='<input type="button" '.
                   3803: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3804: 
1.324     albertel 3805:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3806:     $request->print($studentTable);
                   3807: 
                   3808:     return '';
                   3809: }
                   3810: 
                   3811: sub getSymbMap {
1.74      albertel 3812:     my ($request) = @_;
1.132     bowersj2 3813:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3814: 
                   3815:     my %symbx = ();
                   3816:     my @titles = ();
1.117     bowersj2 3817:     my $minder = 0;
                   3818: 
                   3819:     # Gather every sequence that has problems.
1.240     albertel 3820:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3821: 					       1,0,1);
1.117     bowersj2 3822:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3823: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.117     bowersj2 3824: 	    my $title = $minder.'.'.$sequence->compTitle();
                   3825: 	    push @titles, $title; # minder in case two titles are identical
                   3826: 	    $symbx{$title} = $sequence->symb();
                   3827: 	    $minder++;
1.241     albertel 3828: 	}
1.68      ng       3829:     }
                   3830:     return \@titles,\%symbx;
                   3831: }
                   3832: 
1.72      ng       3833: #
                   3834: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3835: sub displayPage {
                   3836:     my ($request) = shift;
                   3837: 
1.324     albertel 3838:     my ($symb) = &get_symb($request);
1.257     albertel 3839:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3840:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3841:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3842:     my $pageTitle = $env{'form.page'};
1.103     albertel 3843:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3844:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3845:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3846: 
                   3847:     #need to make sure we have the correct data for later EXT calls, 
                   3848:     #thus invalidate the cache
                   3849:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3850:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3851:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3852:     &Apache::lonnet::clear_EXT_cache_status();
                   3853: 
1.103     albertel 3854:     if (!&canview($usec)) {
1.257     albertel 3855: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
1.324     albertel 3856: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3857: 	return;
                   3858:     }
1.257     albertel 3859:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3860:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3861: 	'</h3>'."\n";
1.71      ng       3862:     &sub_page_js($request);
                   3863:     $request->print($result);
                   3864: 
1.132     bowersj2 3865:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3866:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3867:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3868:     if (!$map) {
                   3869: 	$request->print('<font color="red">Unable to view requested sequence. ('.$resUrl.')</font>');
1.324     albertel 3870: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3871: 	return; 
                   3872:     }
1.68      ng       3873:     my $iterator = $navmap->getIterator($map->map_start(),
                   3874: 					$map->map_finish());
                   3875: 
1.71      ng       3876:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3877: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3878: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3879: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3880: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3881: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       3882: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       3883: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3884: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3885: 
                   3886:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   3887: 	'/check.gif" height="16" border="0" />';
                   3888: 
1.118     ng       3889:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   3890: 	' symbol.'."\n".
1.71      ng       3891: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3892: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       3893: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 3894: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       3895: 
1.329     albertel 3896:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 3897:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       3898:     $iterator->next(); # skip the first BEGIN_MAP
                   3899:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 3900:     while ($depth > 0) {
1.68      ng       3901:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3902:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       3903: 
1.235     albertel 3904:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3905: 	    my $parts = $curRes->parts();
1.68      ng       3906:             my $title = $curRes->compTitle();
1.71      ng       3907: 	    my $symbx = $curRes->symb();
1.196     albertel 3908: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 3909: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       3910: 	    $studentTable.='<td valign="top">';
1.257     albertel 3911: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 3912: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   3913: 					     undef,'both');
1.71      ng       3914: 	    } else {
1.257     albertel 3915: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'});
1.80      ng       3916: 		$companswer =~ s|<form(.*?)>||g;
                   3917: 		$companswer =~ s|</form>||g;
1.71      ng       3918: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       3919: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 3920: #		    $request->print('match='.$1."<br />\n");
1.71      ng       3921: #		}
1.116     ng       3922: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 3923: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       3924: 	    }
                   3925: 
1.257     albertel 3926: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       3927: 
1.257     albertel 3928: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       3929: 		if ($record{'version'} eq '') {
                   3930: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
                   3931: 		} else {
1.116     ng       3932: 		    my %responseType = ();
                   3933: 		    foreach my $partid (@{$parts}) {
1.147     albertel 3934: 			my @responseIds =$curRes->responseIds($partid);
                   3935: 			my @responseType =$curRes->responseType($partid);
                   3936: 			my %responseIds;
                   3937: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   3938: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   3939: 			}
                   3940: 			$responseType{$partid} = \%responseIds;
1.116     ng       3941: 		    }
1.148     albertel 3942: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 3943: 
1.71      ng       3944: 		}
1.257     albertel 3945: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   3946: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       3947: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 3948: 									$env{'request.course.id'},
1.71      ng       3949: 									'','.submission');
                   3950:  
                   3951: 	    }
1.103     albertel 3952: 	    if (&canmodify($usec)) {
                   3953: 		foreach my $partid (@{$parts}) {
                   3954: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   3955: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   3956: 		    $question++;
                   3957: 		}
1.196     albertel 3958: 		$prob++;
1.71      ng       3959: 	    }
                   3960: 	    $studentTable.='</td></tr>';
1.68      ng       3961: 
1.103     albertel 3962: 	}
1.68      ng       3963:         $curRes = $iterator->next();
                   3964:     }
                   3965: 
1.71      ng       3966:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
1.125     ng       3967: 	'<input type="button" value="Save" '.
1.71      ng       3968: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
                   3969: 	'</form>'."\n";
1.324     albertel 3970:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       3971:     $request->print($studentTable);
                   3972: 
                   3973:     return '';
1.119     ng       3974: }
                   3975: 
                   3976: sub displaySubByDates {
1.148     albertel 3977:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 3978:     my $isCODE=0;
1.335     albertel 3979:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 3980:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       3981:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   3982: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   3983: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 3984: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       3985: 	'<td><b>Submission</b></td>'.
                   3986: 	'<td><b>Status&nbsp;</b></td></tr>';
                   3987:     my ($version);
                   3988:     my %mark;
1.148     albertel 3989:     my %orders;
1.119     ng       3990:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 3991:     if (!exists($$record{'1:timestamp'})) {
                   3992: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
                   3993:     }
1.335     albertel 3994: 
                   3995:     my $interaction;
1.119     ng       3996:     for ($version=1;$version<=$$record{'version'};$version++) {
                   3997: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 3998: 	if (exists($$record{$version.':resource.0.version'})) {
                   3999: 	    $interaction = $$record{$version.':resource.0.version'};
                   4000: 	}
                   4001: 
                   4002: 	my $where = ($isTask ? "$version:resource.$interaction"
                   4003: 		             : "$version:resource");
                   4004: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       4005: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 4006: 	if ($isCODE) {
                   4007: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   4008: 	}
1.119     ng       4009: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   4010: 	my @displaySub = ();
                   4011: 	foreach my $partid (@{$parts}) {
1.335     albertel 4012: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   4013: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   4014: 	    
                   4015: 
1.122     ng       4016: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 4017: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 4018: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 4019: 		if (exists($$record{$version.':'.$matchKey}) &&
                   4020: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 4021: 
                   4022: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   4023: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   4024: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 4025: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.147     albertel 4026: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
1.207     albertel 4027: 			$responseId.')</font>&nbsp;<b>';
1.335     albertel 4028: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 4029: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   4030: 		    } else {
                   4031: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 4032: 			    $$record{"$where.$partid.tries"};
1.147     albertel 4033: 		    }
1.335     albertel 4034: 		    my $responseType=($isTask ? 'Task'
                   4035:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 4036: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   4037: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4038: 			$orders{$partid}->{$responseId}=
                   4039: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4040: 		    }
1.147     albertel 4041: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4042: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4043: 		}
                   4044: 	    }
1.335     albertel 4045: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4046: 		$displaySub[1].='Checked in by '.
                   4047: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4048: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4049: 		    '<br />';
                   4050: 	    }
                   4051: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4052: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4053: 		    lc($$record{"$where.$partid.award"}).' '.
                   4054: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4055: 		    '<br />';
                   4056: 	    }
1.335     albertel 4057: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4058: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4059: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4060: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4061: 		$displaySub[2].=
                   4062: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4063: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4064: 	    }
                   4065: 	}
                   4066: 	# needed because old essay regrader has not parts info
                   4067: 	if (exists $$record{"$version:resource.regrader"}) {
                   4068: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4069: 	}
                   4070: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4071: 	if ($displaySub[2]) {
                   4072: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4073: 	}
                   4074: 	$studentTable.='&nbsp;</td></tr>';
                   4075:     
1.119     ng       4076:     }
                   4077:     $studentTable.='</table></td></tr></table>';
                   4078:     return $studentTable;
1.71      ng       4079: }
                   4080: 
                   4081: sub updateGradeByPage {
                   4082:     my ($request) = shift;
                   4083: 
1.257     albertel 4084:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4085:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4086:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4087:     my $pageTitle = $env{'form.page'};
1.103     albertel 4088:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4089:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4090:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4091:     if (!&canmodify($usec)) {
1.257     albertel 4092: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
1.324     albertel 4093: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4094: 	return;
                   4095:     }
1.257     albertel 4096:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   4097:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4098: 	'</h3>'."\n";
1.70      ng       4099: 
1.68      ng       4100:     $request->print($result);
                   4101: 
1.132     bowersj2 4102:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4103:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4104:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4105:     if (!$map) {
                   4106: 	$request->print('<font color="red">Unable to grade requested sequence. ('.$resUrl.')</font>');
1.324     albertel 4107: 	my ($symb)=&get_symb($request);
                   4108: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4109: 	return; 
                   4110:     }
1.71      ng       4111:     my $iterator = $navmap->getIterator($map->map_start(),
                   4112: 					$map->map_finish());
1.70      ng       4113: 
1.71      ng       4114:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4115: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4116: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4117: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4118: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4119: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4120: 
                   4121:     $iterator->next(); # skip the first BEGIN_MAP
                   4122:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4123:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4124:     while ($depth > 0) {
1.71      ng       4125:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4126:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4127: 
                   4128:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 4129: 	    my $parts = $curRes->parts();
1.71      ng       4130:             my $title = $curRes->compTitle();
                   4131: 	    my $symbx = $curRes->symb();
1.196     albertel 4132: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4133: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4134: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4135: 
                   4136: 	    my %newrecord=();
                   4137: 	    my @displayPts=();
1.269     raeburn  4138:             my %aggregate = ();
                   4139:             my $aggregateflag = 0;
1.71      ng       4140: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4141: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4142: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4143: 
1.257     albertel 4144: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4145: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4146: 		my $partial = $newpts/$wgt;
                   4147: 		my $score;
                   4148: 		if ($partial > 0) {
                   4149: 		    $score = 'correct_by_override';
1.125     ng       4150: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4151: 		    $score = 'incorrect_by_override';
                   4152: 		}
1.257     albertel 4153: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4154: 		if ($dropMenu eq 'excused') {
1.71      ng       4155: 		    $partial = '';
                   4156: 		    $score = 'excused';
1.125     ng       4157: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4158: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4159: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4160: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4161: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4162: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4163: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4164: 		    $changeflag++;
                   4165: 		    $newpts = '';
1.269     raeburn  4166:                     
                   4167:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4168:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4169:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4170:                     if ($aggtries > 0) {
                   4171:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4172:                         $aggregateflag = 1;
                   4173:                     }
1.71      ng       4174: 		}
1.324     albertel 4175: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4176: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4177: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4178: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4179: 		    '&nbsp;<br />';
1.207     albertel 4180: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4181: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4182: 		    '&nbsp;<br />';
1.71      ng       4183: 
                   4184: 		$question++;
1.125     ng       4185: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
                   4186: 
1.71      ng       4187: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4188: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4189: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4190: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4191: 
                   4192: 		$changeflag++;
                   4193: 	    }
                   4194: 	    if (scalar(keys(%newrecord)) > 0) {
1.257     albertel 4195: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4196: 					$udom,$uname);
                   4197: 	    }
1.269     raeburn  4198:             if ($aggregateflag) {
                   4199:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4200:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4201:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4202:             }
1.125     ng       4203: 
1.71      ng       4204: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4205: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4206: 		'</tr>';
1.68      ng       4207: 
1.196     albertel 4208: 	    $prob++;
1.68      ng       4209: 	}
1.71      ng       4210:         $curRes = $iterator->next();
1.68      ng       4211:     }
1.98      albertel 4212: 
1.71      ng       4213:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4214:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4215:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4216: 		  'The scores were changed for '.
                   4217: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4218:     $request->print($grademsg.$studentTable);
1.68      ng       4219: 
1.70      ng       4220:     return '';
                   4221: }
                   4222: 
1.72      ng       4223: #-------- end of section for handling grading by page/sequence ---------
                   4224: #
                   4225: #-------------------------------------------------------------------
                   4226: 
1.75      albertel 4227: #--------------------Scantron Grading-----------------------------------
                   4228: #
                   4229: #------ start of section for handling grading by page/sequence ---------
                   4230: 
1.81      albertel 4231: sub defaultFormData {
1.324     albertel 4232:     my ($symb)=@_;
1.81      albertel 4233:     return '
                   4234:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4235:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4236:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4237: }
                   4238: 
1.75      albertel 4239: sub getSequenceDropDown {
                   4240:     my ($request,$symb)=@_;
                   4241:     my $result='<select name="selectpage">'."\n";
                   4242:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4243:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4244:     my $ctr=0;
                   4245:     foreach (@$titles) {
                   4246: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4247: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   4248: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   4249: 	    '>'.$showtitle.'</option>'."\n";
                   4250: 	$ctr++;
                   4251:     }
                   4252:     $result.= '</select>';
                   4253:     return $result;
                   4254: }
                   4255: 
1.202     albertel 4256: sub scantron_filenames {
1.257     albertel 4257:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4258:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4259:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.359     www      4260: 				    &propath($cdom,$cname));
1.202     albertel 4261:     my @possiblenames;
1.201     albertel 4262:     foreach my $filename (sort(@files)) {
1.157     albertel 4263: 	($filename)=split(/&/,$filename);
                   4264: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4265: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4266: 	push(@possiblenames,$filename);
                   4267:     }
                   4268:     return @possiblenames;
                   4269: }
                   4270: 
                   4271: sub scantron_uploads {
1.209     ng       4272:     my ($file2grade) = @_;
1.202     albertel 4273:     my $result=	'<select name="scantron_selectfile">';
                   4274:     $result.="<option></option>";
                   4275:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       4276: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 4277:     }
                   4278:     $result.="</select>";
                   4279:     return $result;
                   4280: }
                   4281: 
1.82      albertel 4282: sub scantron_scantab {
                   4283:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4284:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4285:     $result.='<option></option>'."\n";
1.82      albertel 4286:     foreach my $line (<$fh>) {
                   4287: 	my ($name,$descrip)=split(/:/,$line);
                   4288: 	if ($name =~ /^\#/) { next; }
                   4289: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4290:     }
                   4291:     $result.='</select>'."\n";
                   4292: 
                   4293:     return $result;
                   4294: }
                   4295: 
1.186     albertel 4296: sub scantron_CODElist {
1.257     albertel 4297:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4298:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4299:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4300:     my $namechoice='<option></option>';
1.225     albertel 4301:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4302: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4303: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4304: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4305:     }
                   4306:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4307:     return $namechoice;
                   4308: }
                   4309: 
                   4310: sub scantron_CODEunique {
                   4311:     my $result='<nobr>
1.272     albertel 4312:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4313:                         value="yes" checked="checked" /> Yes </label>
1.186     albertel 4314:                 </nobr>
                   4315:                 <nobr>
1.272     albertel 4316:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4317:                         value="no" /> No </label>
1.186     albertel 4318:                 </nobr>';
                   4319:     return $result;
                   4320: }
                   4321: 
1.75      albertel 4322: sub scantron_selectphase {
1.209     ng       4323:     my ($r,$file2grade) = @_;
1.324     albertel 4324:     my ($symb)=&get_symb($r);
1.75      albertel 4325:     if (!$symb) {return '';}
                   4326:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4327:     my $default_form_data=&defaultFormData($symb);
                   4328:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4329:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4330:     my $format_selector=&scantron_scantab();
1.186     albertel 4331:     my $CODE_selector=&scantron_CODElist();
                   4332:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4333:     my $result;
1.157     albertel 4334:     #FIXME allow instructor to be able to download the scantron file
                   4335:     # and to upload it,
1.75      albertel 4336:     $result.= <<SCANTRONFORM;
1.162     albertel 4337:     <table width="100%" border="0">
1.75      albertel 4338:     <tr>
1.226     albertel 4339:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4340:       <td bgcolor="#777777">
1.203     albertel 4341:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4342:         $default_form_data
1.75      albertel 4343:         <table width="100%" border="0">
                   4344:           <tr bgcolor="#e6ffff">
1.174     albertel 4345:             <td colspan="2">
                   4346:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4347:             </td>
                   4348:           </tr>
                   4349:           <tr bgcolor="#ffffe6">
1.174     albertel 4350:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4351:           </tr>
                   4352:           <tr bgcolor="#ffffe6">
1.174     albertel 4353:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4354:           </tr>
1.82      albertel 4355:           <tr bgcolor="#ffffe6">
1.174     albertel 4356:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4357:           </tr>
1.157     albertel 4358:           <tr bgcolor="#ffffe6">
1.186     albertel 4359:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4360:           </tr>
                   4361:           <tr bgcolor="#ffffe6">
                   4362:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4363:           </tr>
                   4364:           <tr bgcolor="#ffffe6">
1.187     albertel 4365: 	    <td> Options: </td>
                   4366:             <td>
1.272     albertel 4367: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.331     albertel 4368:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
                   4369:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4370: 	    </td>
                   4371:           </tr>
                   4372:           <tr bgcolor="#ffffe6">
1.174     albertel 4373:             <td colspan="2">
1.265     www      4374:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4375:             </td>
                   4376:           </tr>
                   4377:         </table>
1.226     albertel 4378:        </td>
                   4379:      </form>
1.162     albertel 4380:     </tr>
                   4381: SCANTRONFORM
                   4382:    
                   4383:     $r->print($result);
                   4384: 
1.257     albertel 4385:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4386:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4387: 
                   4388:         $r->print(<<SCANTRONFORM);
                   4389:     <tr>
                   4390:       <td bgcolor="#777777">
                   4391:         <table width="100%" border="0">
                   4392:           <tr bgcolor="#e6ffff">
                   4393:             <td>
1.174     albertel 4394:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4395:             </td>
                   4396:           </tr>
                   4397:           <tr bgcolor="#ffffe6">
                   4398:             <td>
                   4399: SCANTRONFORM
1.324     albertel 4400:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4401:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4402:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4403:     $r->print(<<UPLOAD);
                   4404:               <script type="text/javascript" language="javascript">
                   4405:     function checkUpload(formname) {
                   4406: 	if (formname.upfile.value == "") {
                   4407: 	    alert("Please use the browse button to select a file from your local directory.");
                   4408: 	    return false;
                   4409: 	}
                   4410: 	formname.submit();
                   4411:     }
                   4412:               </script>
                   4413: 
                   4414:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4415:                 $default_form_data
                   4416:                 <input name='courseid' type='hidden' value='$cnum' />
                   4417:                 <input name='domainid' type='hidden' value='$cdom' />
                   4418:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4419:                 File to upload:<input type="file" name="upfile" size="50" />
                   4420:                 <br />
                   4421:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4422:               </form>
                   4423: UPLOAD
1.162     albertel 4424: 
                   4425:         $r->print(<<SCANTRONFORM);
                   4426:             </td>
                   4427:           </tr>
1.75      albertel 4428:         </table>
                   4429:       </td>
                   4430:     </tr>
1.162     albertel 4431: SCANTRONFORM
                   4432:     }
1.187     albertel 4433:     $r->print(<<SCANTRONFORM);
                   4434:     <tr>
1.226     albertel 4435:       <form action='/adm/grades' name='scantron_download'>
                   4436:         <td bgcolor="#777777">
1.187     albertel 4437:           <input type="hidden" name="command" value="scantron_download" />
                   4438:           <table width="100%" border="0">
                   4439:             <tr bgcolor="#e6ffff">
                   4440:               <td colspan="2">
                   4441:                 &nbsp;<b>Download a scoring office file</b>
                   4442:               </td>
                   4443:             </tr>
                   4444:             <tr bgcolor="#ffffe6">
                   4445:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4446:             </tr>
                   4447:             <tr bgcolor="#ffffe6">
                   4448:               <td colspan="2">
1.293     www      4449:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4450:               </td>
                   4451:             </tr>
                   4452:           </table>
1.226     albertel 4453:         </td>
                   4454:       </form>
1.187     albertel 4455:     </tr>
                   4456: SCANTRONFORM
1.162     albertel 4457: 
                   4458:     $r->print(<<SCANTRONFORM);
1.75      albertel 4459:   </table>
1.81      albertel 4460: $grading_menu_button
1.75      albertel 4461: SCANTRONFORM
                   4462: 
1.162     albertel 4463:     return
1.75      albertel 4464: }
                   4465: 
1.82      albertel 4466: sub get_scantron_config {
                   4467:     my ($which) = @_;
                   4468:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4469:     my %config;
1.157     albertel 4470:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4471:     foreach my $line (<$fh>) {
                   4472: 	my ($name,$descrip)=split(/:/,$line);
                   4473: 	if ($name ne $which ) { next; }
                   4474: 	chomp($line);
                   4475: 	my @config=split(/:/,$line);
                   4476: 	$config{'name'}=$config[0];
                   4477: 	$config{'description'}=$config[1];
                   4478: 	$config{'CODElocation'}=$config[2];
                   4479: 	$config{'CODEstart'}=$config[3];
                   4480: 	$config{'CODElength'}=$config[4];
                   4481: 	$config{'IDstart'}=$config[5];
                   4482: 	$config{'IDlength'}=$config[6];
                   4483: 	$config{'Qstart'}=$config[7];
                   4484: 	$config{'Qlength'}=$config[8];
                   4485: 	$config{'Qoff'}=$config[9];
                   4486: 	$config{'Qon'}=$config[10];
1.157     albertel 4487: 	$config{'PaperID'}=$config[11];
                   4488: 	$config{'PaperIDlength'}=$config[12];
                   4489: 	$config{'FirstName'}=$config[13];
                   4490: 	$config{'FirstNamelength'}=$config[14];
                   4491: 	$config{'LastName'}=$config[15];
                   4492: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4493: 	last;
                   4494:     }
                   4495:     return %config;
                   4496: }
                   4497: 
                   4498: sub username_to_idmap {
                   4499:     my ($classlist)= @_;
                   4500:     my %idmap;
                   4501:     foreach my $student (keys(%$classlist)) {
                   4502: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4503: 	    $student;
                   4504:     }
                   4505:     return %idmap;
                   4506: }
                   4507: 
1.157     albertel 4508: sub scantron_fixup_scanline {
                   4509:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4510:     if ($field eq 'ID') {
                   4511: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4512: 	    return ($line,1,'New value too large');
1.157     albertel 4513: 	}
                   4514: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4515: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4516: 				     $args->{'newid'});
                   4517: 	}
                   4518: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4519: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4520: 	if ($args->{'newid'}=~/^\s*$/) {
                   4521: 	    &scan_data($scan_data,"$whichline.user",
                   4522: 		       $args->{'username'}.':'.$args->{'domain'});
                   4523: 	}
1.186     albertel 4524:     } elsif ($field eq 'CODE') {
1.192     albertel 4525: 	if ($args->{'CODE_ignore_dup'}) {
                   4526: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4527: 	}
                   4528: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4529: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4530: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4531: 		return ($line,1,'New CODE value too large');
                   4532: 	    }
                   4533: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4534: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4535: 	    }
                   4536: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4537: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4538: 	}
1.157     albertel 4539:     } elsif ($field eq 'answer') {
                   4540: 	my $length=$scantron_config->{'Qlength'};
                   4541: 	my $off=$scantron_config->{'Qoff'};
                   4542: 	my $on=$scantron_config->{'Qon'};
                   4543: 	my $answer=${off}x$length;
                   4544: 	if ($args->{'response'} eq 'none') {
                   4545: 	    &scan_data($scan_data,
                   4546: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4547: 	} else {
1.274     albertel 4548: 	    if ($on eq 'letter') {
                   4549: 		my @alphabet=('A'..'Z');
                   4550: 		$answer=$alphabet[$args->{'response'}];
                   4551: 	    } elsif ($on eq 'number') {
                   4552: 		$answer=$args->{'response'}+1;
                   4553: 	    } else {
                   4554: 		substr($answer,$args->{'response'},1)=$on;
                   4555: 	    }
1.157     albertel 4556: 	    &scan_data($scan_data,
                   4557: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4558: 	}
                   4559: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4560: 	substr($line,$where-1,$length)=$answer;
                   4561:     }
                   4562:     return $line;
                   4563: }
                   4564: 
                   4565: sub scan_data {
                   4566:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4567:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4568:     if (defined($value)) {
                   4569: 	$scan_data->{$filename.'_'.$key} = $value;
                   4570:     }
                   4571:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4572:     return $scan_data->{$filename.'_'.$key};
                   4573: }
                   4574: 
1.82      albertel 4575: sub scantron_parse_scanline {
1.194     albertel 4576:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4577:     my %record;
                   4578:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4579:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4580:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4581: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4582: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4583: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4584: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4585: 	    $record{'scantron.CODE'}=substr($data,
                   4586: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4587: 					    $$scantron_config{'CODElength'});
1.191     albertel 4588: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4589: 		$record{'scantron.useCODE'}=1;
                   4590: 	    }
1.192     albertel 4591: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4592: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4593: 	    }
1.82      albertel 4594: 	} else {
                   4595: 	    #FIXME interpret first N questions
                   4596: 	}
                   4597:     }
1.83      albertel 4598:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4599: 				  $$scantron_config{'IDlength'});
1.157     albertel 4600:     $record{'scantron.PaperID'}=
                   4601: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4602: 	       $$scantron_config{'PaperIDlength'});
                   4603:     $record{'scantron.FirstName'}=
                   4604: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4605: 	       $$scantron_config{'FirstNamelength'});
                   4606:     $record{'scantron.LastName'}=
                   4607: 	substr($data,$$scantron_config{'LastName'}-1,
                   4608: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4609:     if ($justHeader) { return \%record; }
                   4610: 
1.82      albertel 4611:     my @alphabet=('A'..'Z');
                   4612:     my $questnum=0;
                   4613:     while ($questions) {
                   4614: 	$questnum++;
                   4615: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4616: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4617: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4618: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.371     albertel 4619: 	    if ($currentquest eq '?'
                   4620: 		|| $currentquest eq '*') {
1.274     albertel 4621: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4622: 		$record{"scantron.$questnum.answer"}='';
                   4623: 	    } elsif (!$currentquest 
                   4624: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4625: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4626: 		$record{"scantron.$questnum.answer"}='';
                   4627: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4628: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4629: 		}
                   4630: 	    } else {
                   4631: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4632: 	    }
                   4633: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.371     albertel 4634: 	    if ($currentquest eq '?'
                   4635: 		|| $currentquest eq '*') {
1.274     albertel 4636: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4637: 		$record{"scantron.$questnum.answer"}='';
                   4638: 		} elsif (!$currentquest 
                   4639: 			 || $currentquest eq $$scantron_config{'Qoff'} 
                   4640: 			 || $currentquest !~ /^\d$/) {
1.239     albertel 4641: 		$record{"scantron.$questnum.answer"}='';
                   4642: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4643: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4644: 		}
                   4645: 	    } else {
1.371     albertel 4646: 		# wrap zero back to J
                   4647: 		if ($currentquest eq '0') {
                   4648: 		    $record{"scantron.$questnum.answer"}=
                   4649: 			$alphabet[9];
                   4650: 		} else {
                   4651: 		    $record{"scantron.$questnum.answer"}=
                   4652: 			$alphabet[$currentquest-1];
                   4653: 		}
1.239     albertel 4654: 	    }
1.82      albertel 4655: 	} else {
1.239     albertel 4656: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4657: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4658: 		$record{"scantron.$questnum.answer"}='';
                   4659: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4660: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4661: 		}
                   4662: 	    } else {
                   4663: 		$record{"scantron.$questnum.answer"}=
                   4664: 		    $alphabet[length($array[0])];
                   4665: 	    }
                   4666: 	    if (scalar(@array) gt 2) {
                   4667: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4668: 		my @ans=@array;
                   4669: 		my $i=length($ans[0]);shift(@ans);
                   4670: 		while ($#ans) {
                   4671: 		    $i+=length($ans[0])+1;
                   4672: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4673: 		    shift(@ans);
                   4674: 		}
                   4675: 	    }
1.82      albertel 4676: 	}
                   4677:     }
1.83      albertel 4678:     $record{'scantron.maxquest'}=$questnum;
                   4679:     return \%record;
1.82      albertel 4680: }
                   4681: 
                   4682: sub scantron_add_delay {
1.140     albertel 4683:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4684:     push(@$delayqueue,
                   4685: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4686: 	  'ecode' => $errorcode }
                   4687: 	 );
1.82      albertel 4688: }
                   4689: 
                   4690: sub scantron_find_student {
1.157     albertel 4691:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4692:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4693:     if ($scanID =~ /^\s*$/) {
                   4694:  	return &scan_data($scan_data,"$line.user");
                   4695:     }
1.83      albertel 4696:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4697:  	if (lc($id) eq lc($scanID)) {
                   4698:  	    return $$idmap{$id};
                   4699:  	}
1.83      albertel 4700:     }
                   4701:     return undef;
                   4702: }
                   4703: 
                   4704: sub scantron_filter {
                   4705:     my ($curres)=@_;
1.331     albertel 4706: 
                   4707:     if (ref($curres) && $curres->is_problem()) {
                   4708: 	# if the user has asked to not have either hidden
                   4709: 	# or 'randomout' controlled resources to be graded
                   4710: 	# don't include them
                   4711: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   4712: 	    && $curres->randomout) {
                   4713: 	    return 0;
                   4714: 	}
1.83      albertel 4715: 	return 1;
                   4716:     }
                   4717:     return 0;
1.82      albertel 4718: }
                   4719: 
1.157     albertel 4720: sub scantron_process_corrections {
                   4721:     my ($r) = @_;
1.257     albertel 4722:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4723:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4724:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4725:     my $which=$env{'form.scantron_line'};
1.200     albertel 4726:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4727:     my ($skip,$err,$errmsg);
1.257     albertel 4728:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4729: 	$skip=1;
1.257     albertel 4730:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4731: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4732: 	    $env{'form.scantron_domain'};
1.157     albertel 4733: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4734: 	($line,$err,$errmsg)=
                   4735: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4736: 				     'ID',{'newid'=>$newid,
1.257     albertel 4737: 				    'username'=>$env{'form.scantron_username'},
                   4738: 				    'domain'=>$env{'form.scantron_domain'}});
                   4739:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4740: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4741: 	my $newCODE;
1.192     albertel 4742: 	my %args;
1.190     albertel 4743: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4744: 	    $newCODE='use_unfound';
1.190     albertel 4745: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4746: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4747: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4748: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4749: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4750: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4751: 	}
1.257     albertel 4752: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4753: 	    $args{'CODE_ignore_dup'}=1;
                   4754: 	}
                   4755: 	$args{'CODE'}=$newCODE;
1.186     albertel 4756: 	($line,$err,$errmsg)=
                   4757: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4758: 				     'CODE',\%args);
1.257     albertel 4759:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4760: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4761: 	    ($line,$err,$errmsg)=
                   4762: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4763: 					 $which,'answer',
                   4764: 					 { 'question'=>$question,
1.257     albertel 4765: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4766: 	    if ($err) { last; }
                   4767: 	}
                   4768:     }
                   4769:     if ($err) {
1.287     albertel 4770: 	$r->print("<font color='red'>Unable to accept last correction, an error occurred :$errmsg:</font>");
1.157     albertel 4771:     } else {
1.200     albertel 4772: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4773: 	&scantron_putfile($scanlines,$scan_data);
                   4774:     }
                   4775: }
                   4776: 
1.200     albertel 4777: sub reset_skipping_status {
                   4778:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4779:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4780:     &scantron_putfile(undef,$scan_data);
                   4781: }
                   4782: 
1.376     albertel 4783: sub start_skipping {
1.200     albertel 4784:     my ($scan_data,$i)=@_;
                   4785:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4786:     if ($env{'form.scantron_options_redo'} =~ /^redo_/) {
                   4787: 	$remembered{$i}=2;
                   4788:     } else {
                   4789: 	$remembered{$i}=1;
                   4790:     }
1.200     albertel 4791:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4792: }
                   4793: 
                   4794: sub should_be_skipped {
1.376     albertel 4795:     my ($scanlines,$scan_data,$i)=@_;
1.257     albertel 4796:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4797: 	# not redoing old skips
1.376     albertel 4798: 	if ($scanlines->{'skipped'}[$i]) { return 1; }
1.200     albertel 4799: 	return 0;
                   4800:     }
                   4801:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
1.376     albertel 4802: 
                   4803:     if (exists($remembered{$i}) && $remembered{$i} != 2 ) {
                   4804: 	return 0;
                   4805:     }
1.200     albertel 4806:     return 1;
                   4807: }
                   4808: 
                   4809: sub remember_current_skipped {
                   4810:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4811:     my %to_remember;
                   4812:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4813: 	if ($scanlines->{'skipped'}[$i]) {
                   4814: 	    $to_remember{$i}=1;
                   4815: 	}
                   4816:     }
1.376     albertel 4817: 
1.200     albertel 4818:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4819:     &scantron_putfile(undef,$scan_data);
                   4820: }
                   4821: 
                   4822: sub check_for_error {
                   4823:     my ($r,$result)=@_;
                   4824:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4825: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4826:     }
                   4827: }
1.157     albertel 4828: 
1.203     albertel 4829: sub scantron_warning_screen {
                   4830:     my ($button_text)=@_;
1.257     albertel 4831:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4832:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.373     albertel 4833:     my $CODElist;
1.284     albertel 4834:     if ($scantron_config{'CODElocation'} &&
                   4835: 	$scantron_config{'CODEstart'} &&
                   4836: 	$scantron_config{'CODElength'}) {
                   4837: 	$CODElist=$env{'form.scantron_CODElist'};
1.373     albertel 4838: 	if ($env{'form.scantron_CODElist'} eq '') { $CODElist='<font color="red">None</font>'; }
1.284     albertel 4839: 	$CODElist=
                   4840: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
1.373     albertel 4841: 	    $env{'form.scantron_CODElist'}.'</tt></td></tr>';
1.284     albertel 4842:     }
1.203     albertel 4843:     return (<<STUFF);
                   4844: <p>
                   4845: <font color="red">Please double check the information
                   4846:                  below before clicking on '$button_text'</font>
                   4847: </p>
                   4848: <table>
1.284     albertel 4849: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4850: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4851: $CODElist
1.203     albertel 4852: </table>
                   4853: </font>
                   4854: <br />
                   4855: <p> If this information is correct, please click on '$button_text'.</p>
                   4856: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4857: 
                   4858: <br />
                   4859: STUFF
                   4860: }
                   4861: 
                   4862: sub scantron_do_warning {
                   4863:     my ($r)=@_;
1.324     albertel 4864:     my ($symb)=&get_symb($r);
1.203     albertel 4865:     if (!$symb) {return '';}
1.324     albertel 4866:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 4867:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 4868:     if ( $env{'form.selectpage'} eq '' ||
                   4869: 	 $env{'form.scantron_selectfile'} eq '' ||
                   4870: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 4871: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 4872: 	if ( $env{'form.selectpage'} eq '') {
1.237     albertel 4873: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
                   4874: 	} 
1.257     albertel 4875: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.237     albertel 4876: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
                   4877: 	} 
1.257     albertel 4878: 	if ( $env{'form.scantron_format'} eq '') {
1.237     albertel 4879: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
                   4880: 	} 
                   4881:     } else {
1.265     www      4882: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 4883: 	$r->print(<<STUFF);
1.203     albertel 4884: $warning
1.265     www      4885: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 4886: <input type="hidden" name="command" value="scantron_validate" />
                   4887: STUFF
1.237     albertel 4888:     }
1.352     albertel 4889:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 4890:     return '';
                   4891: }
                   4892: 
                   4893: sub scantron_form_start {
                   4894:     my ($max_bubble)=@_;
                   4895:     my $result= <<SCANTRONFORM;
                   4896: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 4897:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   4898:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   4899:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 4900:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 4901:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   4902:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   4903:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   4904:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 4905:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 4906: SCANTRONFORM
                   4907:     return $result;
                   4908: }
                   4909: 
1.157     albertel 4910: sub scantron_validate_file {
                   4911:     my ($r) = @_;
1.324     albertel 4912:     my ($symb)=&get_symb($r);
1.157     albertel 4913:     if (!$symb) {return '';}
1.324     albertel 4914:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 4915:     
                   4916:     # do the detection of only doing skipped records first befroe we delete
                   4917:     # them  when doing the corrections reset
1.257     albertel 4918:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 4919: 	&reset_skipping_status();
                   4920:     }
1.257     albertel 4921:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 4922: 	&remember_current_skipped();
1.257     albertel 4923: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 4924:     }
                   4925: 
1.257     albertel 4926:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 4927: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   4928: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   4929: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 4930: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 4931:     }
1.200     albertel 4932: 
1.257     albertel 4933:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 4934: 	&scantron_process_corrections($r);
                   4935:     }
1.191     albertel 4936:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 4937:     #get the student pick code ready
                   4938:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 4939:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 4940:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 4941:     $r->print($result);
                   4942:     
1.334     albertel 4943:     my @validate_phases=( 'sequence',
                   4944: 			  'ID',
1.157     albertel 4945: 			  'CODE',
                   4946: 			  'doublebubble',
                   4947: 			  'missingbubbles');
1.257     albertel 4948:     if (!$env{'form.validatepass'}) {
                   4949: 	$env{'form.validatepass'} = 0;
1.157     albertel 4950:     }
1.257     albertel 4951:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 4952: 
                   4953:     my $stop=0;
                   4954:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   4955: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   4956: 	$r->rflush();
                   4957: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   4958: 	{
                   4959: 	    no strict 'refs';
                   4960: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   4961: 	}
                   4962:     }
                   4963:     if (!$stop) {
1.203     albertel 4964: 	my $warning=&scantron_warning_screen('Start Grading');
                   4965: 	$r->print(<<STUFF);
                   4966: Validation process complete.<br />
                   4967: $warning
                   4968: <input type="submit" name="submit" value="Start Grading" />
                   4969: <input type="hidden" name="command" value="scantron_process" />
                   4970: STUFF
                   4971: 
1.157     albertel 4972:     } else {
                   4973: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   4974: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   4975:     }
                   4976:     if ($stop) {
1.334     albertel 4977: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   4978: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   4979: 	    $r->print(' this error <br />');
                   4980: 
                   4981: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   4982: 	} else {
                   4983: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   4984: 	    $r->print(' using corrected info <br />');
                   4985: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   4986: 	    $r->print(" this scanline saving it for later.");
                   4987: 	}
1.157     albertel 4988:     }
1.352     albertel 4989:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 4990:     return '';
                   4991: }
                   4992: 
1.200     albertel 4993: sub scantron_remove_file {
1.192     albertel 4994:     my ($which)=@_;
1.257     albertel 4995:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4996:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4997:     my $file='scantron_';
1.200     albertel 4998:     if ($which eq 'corrected' || $which eq 'skipped') {
                   4999: 	$file.=$which.'_';
1.192     albertel 5000:     } else {
                   5001: 	return 'refused';
                   5002:     }
1.257     albertel 5003:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 5004:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   5005: }
                   5006: 
                   5007: sub scantron_remove_scan_data {
1.257     albertel 5008:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5009:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 5010:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   5011:     my @todelete;
1.257     albertel 5012:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 5013:     foreach my $key (@keys) {
                   5014: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 5015: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 5016: 		$key=~/remember_skipping/) {
                   5017: 		next;
                   5018: 	    }
1.192     albertel 5019: 	    push(@todelete,$key);
                   5020: 	}
                   5021:     }
1.200     albertel 5022:     my $result;
1.192     albertel 5023:     if (@todelete) {
1.200     albertel 5024: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 5025:     }
                   5026:     return $result;
                   5027: }
                   5028: 
1.157     albertel 5029: sub scantron_getfile {
1.200     albertel 5030:     #FIXME really would prefer a scantron directory
1.257     albertel 5031:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5032:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 5033:     my $lines;
                   5034:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5035: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 5036:     my %scanlines;
                   5037:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   5038:     my $temp=$scanlines{'orig'};
                   5039:     $scanlines{'count'}=$#$temp;
                   5040: 
                   5041:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5042: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 5043:     if ($lines eq '-1') {
                   5044: 	$scanlines{'corrected'}=[];
                   5045:     } else {
                   5046: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   5047:     }
                   5048:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 5049: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 5050:     if ($lines eq '-1') {
                   5051: 	$scanlines{'skipped'}=[];
                   5052:     } else {
                   5053: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5054:     }
1.175     albertel 5055:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5056:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5057:     my %scan_data = @tmp;
                   5058:     return (\%scanlines,\%scan_data);
                   5059: }
                   5060: 
                   5061: sub lonnet_putfile {
                   5062:     my ($contents,$filename)=@_;
1.257     albertel 5063:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5064:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5065:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5066:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5067: 
                   5068: }
                   5069: 
                   5070: sub scantron_putfile {
                   5071:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5072:     #FIXME really would prefer a scantron directory
1.257     albertel 5073:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5074:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5075:     if ($scanlines) {
                   5076: 	my $prefix='scantron_';
1.157     albertel 5077: # no need to update orig, shouldn't change
                   5078: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5079: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5080: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5081: 			$prefix.'corrected_'.
1.257     albertel 5082: 			$env{'form.scantron_selectfile'});
1.200     albertel 5083: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5084: 			$prefix.'skipped_'.
1.257     albertel 5085: 			$env{'form.scantron_selectfile'});
1.200     albertel 5086:     }
1.175     albertel 5087:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5088: }
                   5089: 
                   5090: sub scantron_get_line {
1.200     albertel 5091:     my ($scanlines,$scan_data,$i)=@_;
1.376     albertel 5092:     if (&should_be_skipped($scanlines,$scan_data,$i)) { return undef; }
                   5093:     #if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5094:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5095:     return $scanlines->{'orig'}[$i]; 
                   5096: }
                   5097: 
1.200     albertel 5098: sub get_todo_count {
                   5099:     my ($scanlines,$scan_data)=@_;
                   5100:     my $count=0;
                   5101:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5102: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5103: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5104: 	$count++;
                   5105:     }
                   5106:     return $count;
                   5107: }
                   5108: 
1.157     albertel 5109: sub scantron_put_line {
1.200     albertel 5110:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5111:     if ($skip) {
                   5112: 	$scanlines->{'skipped'}[$i]=$newline;
1.376     albertel 5113: 	&start_skipping($scan_data,$i);
1.157     albertel 5114: 	return;
                   5115:     }
                   5116:     $scanlines->{'corrected'}[$i]=$newline;
                   5117: }
                   5118: 
1.376     albertel 5119: sub scantron_clear_skip {
                   5120:     my ($scanlines,$scan_data,$i)=@_;
                   5121:     if (exists($scanlines->{'skipped'}[$i])) {
                   5122: 	undef($scanlines->{'skipped'}[$i]);
                   5123: 	return 1;
                   5124:     }
                   5125:     return 0;
                   5126: }
                   5127: 
1.334     albertel 5128: sub scantron_filter_not_exam {
                   5129:     my ($curres)=@_;
                   5130:     
                   5131:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5132: 	# if the user has asked to not have either hidden
                   5133: 	# or 'randomout' controlled resources to be graded
                   5134: 	# don't include them
                   5135: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5136: 	    && $curres->randomout) {
                   5137: 	    return 0;
                   5138: 	}
                   5139: 	return 1;
                   5140:     }
                   5141:     return 0;
                   5142: }
                   5143: 
                   5144: sub scantron_validate_sequence {
                   5145:     my ($r,$currentphase) = @_;
                   5146: 
                   5147:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5148:     my (undef,undef,$sequence)=
                   5149: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5150: 
                   5151:     my $map=$navmap->getResourceByUrl($sequence);
                   5152: 
                   5153:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5154:                                     value="ignore" />');
                   5155:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5156: 	my @resources=
                   5157: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5158: 	if (@resources) {
1.357     banghart 5159: 	    $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 5160: 	    return (1,$currentphase);
                   5161: 	}
                   5162:     }
                   5163: 
                   5164:     return (0,$currentphase+1);
                   5165: }
                   5166: 
1.157     albertel 5167: sub scantron_validate_ID {
                   5168:     my ($r,$currentphase) = @_;
                   5169:     
                   5170:     #get student info
                   5171:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5172:     my %idmap=&username_to_idmap($classlist);
                   5173: 
                   5174:     #get scantron line setup
1.257     albertel 5175:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5176:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5177: 
                   5178:     my %found=('ids'=>{},'usernames'=>{});
                   5179:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5180: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5181: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5182: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5183: 						 $scan_data);
                   5184: 	my $id=$$scan_record{'scantron.ID'};
                   5185: 	my $found;
                   5186: 	foreach my $checkid (keys(%idmap)) {
                   5187: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5188: 	}
                   5189: 	if ($found) {
                   5190: 	    my $username=$idmap{$found};
                   5191: 	    if ($found{'ids'}{$found}) {
                   5192: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5193: 					 $line,'duplicateID',$found);
1.194     albertel 5194: 		return(1,$currentphase);
1.157     albertel 5195: 	    } elsif ($found{'usernames'}{$username}) {
                   5196: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5197: 					 $line,'duplicateID',$username);
1.194     albertel 5198: 		return(1,$currentphase);
1.157     albertel 5199: 	    }
1.186     albertel 5200: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 5201: 	    $found{'ids'}{$found}++;
                   5202: 	    $found{'usernames'}{$username}++;
                   5203: 	} else {
                   5204: 	    if ($id =~ /^\s*$/) {
1.158     albertel 5205: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 5206: 		if (defined($username) && $found{'usernames'}{$username}) {
                   5207: 		    &scantron_get_correction($r,$i,$scan_record,
                   5208: 					     \%scantron_config,
                   5209: 					     $line,'duplicateID',$username);
1.194     albertel 5210: 		    return(1,$currentphase);
1.157     albertel 5211: 		} elsif (!defined($username)) {
                   5212: 		    &scantron_get_correction($r,$i,$scan_record,
                   5213: 					     \%scantron_config,
                   5214: 					     $line,'incorrectID');
1.194     albertel 5215: 		    return(1,$currentphase);
1.157     albertel 5216: 		}
                   5217: 		$found{'usernames'}{$username}++;
                   5218: 	    } else {
                   5219: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5220: 					 $line,'incorrectID');
1.194     albertel 5221: 		return(1,$currentphase);
1.157     albertel 5222: 	    }
                   5223: 	}
                   5224:     }
                   5225: 
                   5226:     return (0,$currentphase+1);
                   5227: }
                   5228: 
                   5229: sub scantron_get_correction {
                   5230:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   5231: 
                   5232: #FIXME in the case of a duplicated ID the previous line, probaly need
                   5233: #to show both the current line and the previous one and allow skipping
                   5234: #the previous one or the current one
                   5235: 
1.161     albertel 5236:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 5237:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 5238: 	$r->print(" for PaperID <tt>".
                   5239: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5240:     } else {
                   5241: 	$r->print(" in scanline $i <pre>".
                   5242: 		  $line."</pre> \n");
                   5243:     }
1.242     albertel 5244:     my $message="<p>The ID on the form is  <tt>".
                   5245: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5246: 	"The name on the paper is ".
                   5247: 	$$scan_record{'scantron.LastName'}.",".
                   5248: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5249: 
1.157     albertel 5250:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5251:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5252:     if ($error =~ /ID$/) {
1.186     albertel 5253: 	if ($error eq 'incorrectID') {
1.157     albertel 5254: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5255: 	} elsif ($error eq 'duplicateID') {
                   5256: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5257: 	}
1.242     albertel 5258: 	$r->print($message);
1.157     albertel 5259: 	$r->print("<p>How should I handle this? <br /> \n");
                   5260: 	$r->print("\n<ul><li> ");
                   5261: 	#FIXME it would be nice if this sent back the user ID and
                   5262: 	#could do partial userID matches
                   5263: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5264: 				       'scantron_username','scantron_domain'));
                   5265: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5266: 	$r->print("\n@".
1.257     albertel 5267: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5268: 
                   5269: 	$r->print('</li>');
1.186     albertel 5270:     } elsif ($error =~ /CODE$/) {
                   5271: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5272: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5273: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5274: 	    $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 5275: 	}
1.224     albertel 5276: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5277: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5278: 	$r->print($message);
1.186     albertel 5279: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5280: 	$r->print("\n<br /> ");
1.194     albertel 5281: 	my $i=0;
1.273     albertel 5282: 	if ($error eq 'incorrectCODE' 
                   5283: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5284: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5285: 	    if ($closest > 0) {
                   5286: 		foreach my $testcode (@{$closest}) {
                   5287: 		    my $checked='';
                   5288: 		    if (!$i) { $checked=' checked="on" '; }
                   5289: 		    $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' />");
                   5290: 		    $r->print("\n<br />");
                   5291: 		    $i++;
                   5292: 		}
1.194     albertel 5293: 	    }
                   5294: 	}
1.273     albertel 5295: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   5296: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   5297: 	    $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>");
                   5298: 	    $r->print("\n<br />");
                   5299: 	}
1.194     albertel 5300: 
1.188     albertel 5301: 	$r->print(<<ENDSCRIPT);
                   5302: <script type="text/javascript">
                   5303: function change_radio(field) {
1.190     albertel 5304:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5305:     var i;
                   5306:     for (i=0;i<slct.length;i++) {
                   5307:         if (slct[i].value==field) { slct[i].checked=true; }
                   5308:     }
                   5309: }
                   5310: </script>
                   5311: ENDSCRIPT
1.187     albertel 5312: 	my $href="/adm/pickcode?".
1.359     www      5313: 	   "form=".&escape("scantronupload").
                   5314: 	   "&scantron_format=".&escape($env{'form.scantron_format'}).
                   5315: 	   "&scantron_CODElist=".&escape($env{'form.scantron_CODElist'}).
                   5316: 	   "&curCODE=".&escape($$scan_record{'scantron.CODE'}).
                   5317: 	   "&scantron_selectfile=".&escape($env{'form.scantron_selectfile'});
1.332     albertel 5318: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   5319: 	    $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')\" />");
                   5320: 	    $r->print("\n<br />");
                   5321: 	}
1.272     albertel 5322: 	$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 5323: 	$r->print("\n<br /><br />");
1.157     albertel 5324:     } elsif ($error eq 'doublebubble') {
                   5325: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5326: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5327: 		  join(',',@{$arg}).'" />');
1.242     albertel 5328: 	$r->print($message);
1.157     albertel 5329: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5330: 	foreach my $question (@{$arg}) {
                   5331: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5332: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5333: 	}
                   5334:     } elsif ($error eq 'missingbubble') {
                   5335: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5336: 	$r->print($message);
1.157     albertel 5337: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5338: 	$r->print("Some questions have no scanned bubbles\n");
                   5339: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5340: 		  join(',',@{$arg}).'" />');
                   5341: 	foreach my $question (@{$arg}) {
                   5342: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5343: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5344: 	}
                   5345:     } else {
                   5346: 	$r->print("\n<ul>");
                   5347:     }
                   5348:     $r->print("\n</li></ul>");
                   5349: 
                   5350: }
                   5351: 
                   5352: sub scantron_bubble_selector {
                   5353:     my ($r,$scan_config,$quest,@selected)=@_;
                   5354:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5355: 
                   5356:     my $scmode=$$scan_config{'Qon'};
                   5357:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5358: 
1.157     albertel 5359:     my @alphabet=('A'..'Z');
                   5360:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5361:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5362: 	$r->print("\n".'<td align="center">');
1.157     albertel 5363: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5364: 	else { $r->print('&nbsp;'); }
                   5365: 	$r->print('</td>');
                   5366:     }
1.274     albertel 5367:     $r->print('</tr><tr>');
1.157     albertel 5368:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5369: 	$r->print("\n".
                   5370: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5371: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5372:     }
1.272     albertel 5373:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5374: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5375:     $r->print('</tr></table>');
                   5376: }
                   5377: 
1.194     albertel 5378: sub num_matches {
                   5379:     my ($orig,$code) = @_;
                   5380:     my @code=split(//,$code);
                   5381:     my @orig=split(//,$orig);
                   5382:     my $same=0;
                   5383:     for (my $i=0;$i<scalar(@code);$i++) {
                   5384: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5385:     }
                   5386:     return $same;
                   5387: }
                   5388: 
                   5389: sub scantron_get_closely_matching_CODEs {
                   5390:     my ($allcodes,$CODE)=@_;
                   5391:     my @CODEs;
                   5392:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5393: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5394:     }
                   5395: 
                   5396:     return ($#CODEs,$CODEs[-1]);
                   5397: }
                   5398: 
                   5399: sub get_codes {
1.280     foxr     5400:     my ($old_name, $cdom, $cnum) = @_;
                   5401:     if (!$old_name) {
                   5402: 	$old_name=$env{'form.scantron_CODElist'};
                   5403:     }
                   5404:     if (!$cdom) {
                   5405: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5406:     }
                   5407:     if (!$cnum) {
                   5408: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5409:     }
1.278     albertel 5410:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5411: 				    $cdom,$cnum);
                   5412:     my %allcodes;
                   5413:     if ($result{"type\0$old_name"} eq 'number') {
                   5414: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5415:     } else {
                   5416: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5417:     }
1.194     albertel 5418:     return %allcodes;
                   5419: }
                   5420: 
1.157     albertel 5421: sub scantron_validate_CODE {
                   5422:     my ($r,$currentphase) = @_;
1.257     albertel 5423:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5424:     if ($scantron_config{'CODElocation'} &&
                   5425: 	$scantron_config{'CODEstart'} &&
                   5426: 	$scantron_config{'CODElength'}) {
1.257     albertel 5427: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5428: 	    &FIXME_blow_up()
                   5429: 	}
                   5430:     } else {
                   5431: 	return (0,$currentphase+1);
                   5432:     }
                   5433:     
                   5434:     my %usedCODEs;
                   5435: 
1.194     albertel 5436:     my %allcodes=&get_codes();
1.186     albertel 5437: 
                   5438:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5439:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5440: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5441: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5442: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5443: 						 $scan_data);
                   5444: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5445: 	my $error=0;
1.224     albertel 5446: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5447: 	    &scantron_get_correction($r,$i,$scan_record,
                   5448: 				     \%scantron_config,
                   5449: 				     $line,'incorrectCODE',\%allcodes);
                   5450: 	    return(1,$currentphase);
                   5451: 	}
1.221     albertel 5452: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5453: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5454: 	    &scantron_get_correction($r,$i,$scan_record,
                   5455: 				     \%scantron_config,
1.194     albertel 5456: 				     $line,'incorrectCODE',\%allcodes);
                   5457: 	    return(1,$currentphase);
1.186     albertel 5458: 	}
1.214     albertel 5459: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5460: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5461: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5462: 	    &scantron_get_correction($r,$i,$scan_record,
                   5463: 				     \%scantron_config,
1.194     albertel 5464: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5465: 	    return(1,$currentphase);
1.186     albertel 5466: 	}
1.194     albertel 5467: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5468:     }
1.157     albertel 5469:     return (0,$currentphase+1);
                   5470: }
                   5471: 
                   5472: sub scantron_validate_doublebubble {
                   5473:     my ($r,$currentphase) = @_;
                   5474:     #get student info
                   5475:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5476:     my %idmap=&username_to_idmap($classlist);
                   5477: 
                   5478:     #get scantron line setup
1.257     albertel 5479:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5480:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5481:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5482: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5483: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5484: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5485: 						 $scan_data);
                   5486: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5487: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5488: 				 'doublebubble',
                   5489: 				 $$scan_record{'scantron.doubleerror'});
                   5490:     	return (1,$currentphase);
                   5491:     }
                   5492:     return (0,$currentphase+1);
                   5493: }
                   5494: 
1.330     albertel 5495: sub scantron_get_maxbubble {    
1.257     albertel 5496:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5497: 	$env{'form.scantron_maxbubble'}) {
                   5498: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5499:     }
1.330     albertel 5500: 
1.191     albertel 5501:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5502:     my (undef,undef,$sequence)=
1.257     albertel 5503: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 5504: 
1.191     albertel 5505:     my $map=$navmap->getResourceByUrl($sequence);
                   5506:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 5507: 
                   5508:     &Apache::lonxml::clear_problem_counter();
                   5509: 
1.191     albertel 5510:     foreach my $resource (@resources) {
1.330     albertel 5511: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   5512: 					('symb' => $resource->symb()));
1.191     albertel 5513:     }
                   5514:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 5515:     $env{'form.scantron_maxbubble'} =
                   5516: 	&Apache::lonxml::get_problem_counter()-1;
                   5517: 
1.257     albertel 5518:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5519: }
                   5520: 
1.157     albertel 5521: sub scantron_validate_missingbubbles {
                   5522:     my ($r,$currentphase) = @_;
                   5523:     #get student info
                   5524:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5525:     my %idmap=&username_to_idmap($classlist);
                   5526: 
                   5527:     #get scantron line setup
1.257     albertel 5528:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5529:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5530:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5531:     if (!$max_bubble) { $max_bubble=2**31; }
                   5532:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5533: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5534: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5535: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5536: 						 $scan_data);
                   5537: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5538: 	my @to_correct;
                   5539: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5540: 	    if ($missing > $max_bubble) { next; }
                   5541: 	    push(@to_correct,$missing);
                   5542: 	}
                   5543: 	if (@to_correct) {
                   5544: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5545: 				     $line,'missingbubble',\@to_correct);
                   5546: 	    return (1,$currentphase);
                   5547: 	}
                   5548: 
                   5549:     }
                   5550:     return (0,$currentphase+1);
                   5551: }
                   5552: 
1.82      albertel 5553: sub scantron_process_students {
1.75      albertel 5554:     my ($r) = @_;
1.257     albertel 5555:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5556:     my ($symb)=&get_symb($r);
1.81      albertel 5557:     if (!$symb) {return '';}
1.324     albertel 5558:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5559: 
1.257     albertel 5560:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5561:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5562:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5563:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5564:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5565:     my $map=$navmap->getResourceByUrl($sequence);
                   5566:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5567: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5568:     my $result= <<SCANTRONFORM;
1.81      albertel 5569: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5570:   <input type="hidden" name="command" value="scantron_configphase" />
                   5571:   $default_form_data
                   5572: SCANTRONFORM
1.82      albertel 5573:     $r->print($result);
                   5574: 
                   5575:     my @delayqueue;
1.140     albertel 5576:     my %completedstudents;
                   5577:     
1.200     albertel 5578:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5579:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5580:  				    'Scantron Progress',$count,
1.195     albertel 5581: 				    'inline',undef,'scantronupload');
1.140     albertel 5582:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5583: 					  'Processing first student');
                   5584:     my $start=&Time::HiRes::time();
1.158     albertel 5585:     my $i=-1;
1.200     albertel 5586:     my ($uname,$udom,$started);
1.157     albertel 5587:     while ($i<$scanlines->{'count'}) {
                   5588:  	($uname,$udom)=('','');
                   5589:  	$i++;
1.200     albertel 5590:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5591:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5592: 	if ($started) {
                   5593: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5594: 						     'last student');
                   5595: 	}
                   5596: 	$started=1;
1.157     albertel 5597:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5598:  						 $scan_data);
                   5599:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5600:  					      \%idmap,$i)) {
                   5601:   	    &scantron_add_delay(\@delayqueue,$line,
                   5602:  				'Unable to find a student that matches',1);
                   5603:  	    next;
                   5604:   	}
                   5605:  	if (exists $completedstudents{$uname}) {
                   5606:  	    &scantron_add_delay(\@delayqueue,$line,
                   5607:  				'Student '.$uname.' has multiple sheets',2);
                   5608:  	    next;
                   5609:  	}
                   5610:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 5611: 
                   5612: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 5613:   	&Apache::lonnet::appenv(%$scan_record);
1.376     albertel 5614: 
                   5615: 	if (&scantron_clear_skip($scanlines,$scan_data,$i)) {
                   5616: 	    &scantron_putfile($scanlines,$scan_data);
                   5617: 	}
1.161     albertel 5618: 	
                   5619: 	my $i=0;
1.83      albertel 5620: 	foreach my $resource (@resources) {
1.85      albertel 5621: 	    $i++;
1.193     albertel 5622: 	    my %form=('submitted'     =>'scantron',
                   5623: 		      'grade_target'  =>'grade',
                   5624: 		      'grade_username'=>$uname,
                   5625: 		      'grade_domain'  =>$udom,
1.257     albertel 5626: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5627: 		      'grade_symb'    =>$resource->symb());
                   5628: 	    if (exists($scan_record->{'scantron.CODE'}) &&
                   5629: 		$scan_record->{'scantron.CODE'}) {
                   5630: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5631: 	    } else {
                   5632: 		$form{'CODE'}='';
1.193     albertel 5633: 	    }
                   5634: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5635: 	    if ($result ne '') {
                   5636: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5637: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5638: 	    }
1.213     albertel 5639: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5640: 	}
1.140     albertel 5641: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5642: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5643:     } continue {
1.330     albertel 5644: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 5645: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5646:     }
1.140     albertel 5647:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5648: #    my $lasttime = &Time::HiRes::time()-$start;
                   5649: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5650: 
1.200     albertel 5651:     $r->print("</form>");
1.324     albertel 5652:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5653:     return '';
1.75      albertel 5654: }
1.157     albertel 5655: 
                   5656: sub scantron_upload_scantron_data {
                   5657:     my ($r)=@_;
1.257     albertel 5658:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5659:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5660: 							  'domainid',
                   5661: 							  'coursename');
1.257     albertel 5662:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5663: 						   'domainid');
1.324     albertel 5664:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5665:     $r->print(<<UPLOAD);
                   5666: <script type="text/javascript" language="javascript">
                   5667:     function checkUpload(formname) {
                   5668: 	if (formname.upfile.value == "") {
                   5669: 	    alert("Please use the browse button to select a file from your local directory.");
                   5670: 	    return false;
                   5671: 	}
                   5672: 	formname.submit();
                   5673:     }
                   5674: </script>
                   5675: 
                   5676: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5677: $default_form_data
1.181     albertel 5678: <table>
                   5679: <tr><td>$select_link </td></tr>
                   5680: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5681: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5682: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5683: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5684: </table>
1.157     albertel 5685: <input name='command' value='scantronupload_save' type='hidden' />
                   5686: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5687: </form>
                   5688: UPLOAD
                   5689:     return '';
                   5690: }
                   5691: 
                   5692: sub scantron_upload_scantron_data_save {
                   5693:     my($r)=@_;
1.324     albertel 5694:     my ($symb)=&get_symb($r,1);
1.182     albertel 5695:     my $doanotherupload=
                   5696: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5697: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5698: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5699: 	'</form>'."\n";
1.257     albertel 5700:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5701: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5702: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5703: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5704: 	if ($symb) {
1.324     albertel 5705: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5706: 	} else {
                   5707: 	    $r->print($doanotherupload);
                   5708: 	}
1.162     albertel 5709: 	return '';
                   5710:     }
1.257     albertel 5711:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5712:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5713:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5714:     #FIXME
                   5715:     #copied from lonnet::userfileupload()
                   5716:     #make that function able to target a specified course
                   5717:     # Replace Windows backslashes by forward slashes
                   5718:     $fname=~s/\\/\//g;
                   5719:     # Get rid of everything but the actual filename
                   5720:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5721:     # Replace spaces by underscores
                   5722:     $fname=~s/\s+/\_/g;
                   5723:     # Replace all other weird characters by nothing
                   5724:     $fname=~s/[^\w\.\-]//g;
                   5725:     # See if there is anything left
                   5726:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5727:     my $uploadedfile=$fname;
1.157     albertel 5728:     $fname='scantron_orig_'.$fname;
1.257     albertel 5729:     if (length($env{'form.upfile'}) < 2) {
                   5730: 	$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 5731:     } else {
1.275     albertel 5732: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5733: 	if ($result =~ m|^/uploaded/|) {
1.257     albertel 5734: 	    $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 5735: 	} else {
1.257     albertel 5736: 	    $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 5737: 	}
                   5738:     }
1.174     albertel 5739:     if ($symb) {
1.209     ng       5740: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5741:     } else {
1.182     albertel 5742: 	$r->print($doanotherupload);
1.174     albertel 5743:     }
1.157     albertel 5744:     return '';
                   5745: }
                   5746: 
1.202     albertel 5747: sub valid_file {
                   5748:     my ($requested_file)=@_;
                   5749:     foreach my $filename (sort(&scantron_filenames())) {
                   5750: 	if ($requested_file eq $filename) { return 1; }
                   5751:     }
                   5752:     return 0;
                   5753: }
                   5754: 
                   5755: sub scantron_download_scantron_data {
                   5756:     my ($r)=@_;
1.324     albertel 5757:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5758:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5759:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5760:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5761:     if (! &valid_file($file)) {
                   5762: 	$r->print(<<ERROR);
                   5763: 	<p>
                   5764: 	    The requested file name was invalid.
                   5765:         </p>
                   5766: ERROR
1.324     albertel 5767: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5768: 	return;
                   5769:     }
                   5770:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5771:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5772:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5773:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5774:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5775:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5776:     $r->print(<<DOWNLOAD);
                   5777:     <p>
                   5778: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5779:     </p>
                   5780:     <p>
                   5781: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5782:     </p>
                   5783:     <p>
                   5784: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5785:     </p>
                   5786: DOWNLOAD
1.324     albertel 5787:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5788:     return '';
                   5789: }
1.157     albertel 5790: 
1.75      albertel 5791: #-------- end of section for handling grading scantron forms -------
                   5792: #
                   5793: #-------------------------------------------------------------------
                   5794: 
1.72      ng       5795: #-------------------------- Menu interface -------------------------
                   5796: #
                   5797: #--- Show a Grading Menu button - Calls the next routine ---
                   5798: sub show_grading_menu_form {
1.324     albertel 5799:     my ($symb)=@_;
1.125     ng       5800:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5801: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5802: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5803: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5804: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5805: 	'</form>'."\n";
                   5806:     return $result;
                   5807: }
                   5808: 
1.77      ng       5809: # -- Retrieve choices for grading form
                   5810: sub savedState {
                   5811:     my %savedState = ();
1.257     albertel 5812:     if ($env{'form.saveState'}) {
                   5813: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5814: 	    my ($key,$value) = split(/=/,$_,2);
                   5815: 	    $savedState{$key} = $value;
                   5816: 	}
                   5817:     }
                   5818:     return \%savedState;
                   5819: }
1.76      ng       5820: 
1.72      ng       5821: #--- Displays the main menu page -------
                   5822: sub gradingmenu {
                   5823:     my ($request) = @_;
1.324     albertel 5824:     my ($symb)=&get_symb($request);
1.72      ng       5825:     if (!$symb) {return '';}
1.76      ng       5826:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5827: 
                   5828:     $request->print(<<GRADINGMENUJS);
                   5829: <script type="text/javascript" language="javascript">
1.116     ng       5830:     function checkChoice(formname,val,cmdx) {
                   5831: 	if (val <= 2) {
                   5832: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5833: 	    var cmdsave = cmd;
1.116     ng       5834: 	} else {
                   5835: 	    cmd = cmdx;
1.118     ng       5836: 	    cmdsave = 'submission';
1.116     ng       5837: 	}
                   5838: 	formname.command.value = cmd;
1.118     ng       5839: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5840: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5841: 	if (val < 5) formname.submit();
                   5842: 	if (val == 5) {
1.72      ng       5843: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5844: 	    formname.submit();
                   5845: 	}
1.238     albertel 5846: 	if (val < 7) formname.submit();
1.72      ng       5847:     }
                   5848: 
                   5849:     function checkReceiptNo(formname,nospace) {
                   5850: 	var receiptNo = formname.receipt.value;
                   5851: 	var checkOpt = false;
                   5852: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5853: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5854: 	if (checkOpt) {
                   5855: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5856: 	    formname.receipt.value = "";
                   5857: 	    formname.receipt.focus();
                   5858: 	    return false;
                   5859: 	}
                   5860: 	return true;
                   5861:     }
                   5862: </script>
                   5863: GRADINGMENUJS
1.118     ng       5864:     &commonJSfunctions($request);
                   5865:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
1.324     albertel 5866:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       5867:     $result.=$table;
1.76      ng       5868:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       5869:     my $savedState = &savedState();
1.118     ng       5870:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       5871:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       5872:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       5873:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       5874: 
                   5875:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   5876: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   5877: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   5878: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       5879: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       5880: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       5881: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       5882: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   5883: 
1.326     albertel 5884:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   5885: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       5886: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       5887: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   5888: 
1.326     albertel 5889:     $result.='<table width="100%" border="0">';
1.116     ng       5890:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 5891: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       5892:     if (ref($sections)) {
1.155     albertel 5893: 	foreach (sort (@$sections)) {
                   5894: 	    $result.='<option value="'.$_.'" '.
                   5895: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   5896: 	}
1.116     ng       5897:     }
1.238     albertel 5898:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       5899: 
1.167     sakharuk 5900:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       5901: 
1.116     ng       5902:     $result.='</td></tr>';
                   5903: 
1.288     albertel 5904:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       5905: 	'<input type="radio" name="radioChoice" value="submission" '.
1.326     albertel 5906: 	($saveCmd eq 'submission' ? 'checked' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 5907: 	'</label> <select name="submitonly">'.
1.145     albertel 5908: 	'<option value="yes" '.
1.326     albertel 5909: 	($saveSub eq 'yes' ? 'selected="on"' : '').' />'.&mt('with submissions').'</option>'.
1.301     albertel 5910: 	'<option value="queued" '.
1.326     albertel 5911: 	($saveSub eq 'queued' ? 'selected="on"' : '').' />'.&mt('in grading queue').'</option>'.
1.145     albertel 5912: 	'<option value="graded" '.
1.326     albertel 5913: 	($saveSub eq 'graded' ? 'selected="on"' : '').' />'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 5914: 	'<option value="incorrect" '.
1.326     albertel 5915: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').' />'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 5916: 	'<option value="all" '.
1.326     albertel 5917: 	($saveSub eq 'all' ? 'selected="on"' : '').' />'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       5918: 
1.116     ng       5919:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 5920: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.326     albertel 5921: 	($saveCmd eq 'viewgrades' ? 'checked' : '').' /> '.
1.288     albertel 5922: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       5923: 
1.118     ng       5924:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 5925: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.326     albertel 5926: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').' /> '.
1.288     albertel 5927: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       5928: 
1.116     ng       5929:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       5930: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       5931: 	'</td></tr></table>'."\n";
                   5932: 
                   5933:     $result.='</td><td valign="top">';
                   5934: 
1.326     albertel 5935:     $result.='<table width="100%" border="0">';
1.116     ng       5936:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      5937: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   5938: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       5939: 
1.75      albertel 5940:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       5941: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      5942: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 5943: 
1.257     albertel 5944:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       5945: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      5946: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   5947: 	    ' '.&mt('receipt').': '.
1.257     albertel 5948: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 5949: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       5950: 	    '</td></tr>'."\n";
                   5951:     } 
1.238     albertel 5952:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5953: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   5954: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 5955:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5956: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   5957: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       5958: 
1.116     ng       5959:     $result.='</form></td></tr></table>'."\n".
1.72      ng       5960: 	'</td></tr></table>'."\n".
                   5961: 	'</td></tr></table>'."\n";
1.44      ng       5962:     return $result;
1.2       albertel 5963: }
                   5964: 
1.285     albertel 5965: sub reset_perm {
                   5966:     undef(%perm);
                   5967: }
                   5968: 
                   5969: sub init_perm {
                   5970:     &reset_perm();
1.300     albertel 5971:     foreach my $test_perm ('vgr','mgr','opa') {
                   5972: 
                   5973: 	my $scope = $env{'request.course.id'};
                   5974: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   5975: 
                   5976: 	    $scope .= '/'.$env{'request.course.sec'};
                   5977: 	    if ( $perm{$test_perm}=
                   5978: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   5979: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   5980: 	    } else {
                   5981: 		delete($perm{$test_perm});
                   5982: 	    }
1.285     albertel 5983: 	}
                   5984:     }
                   5985: }
                   5986: 
1.1       albertel 5987: sub handler {
1.41      ng       5988:     my $request=$_[0];
1.102     albertel 5989: 
1.285     albertel 5990:     &reset_perm();
1.257     albertel 5991:     if ($env{'browser.mathml'}) {
1.141     www      5992: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       5993:     } else {
1.141     www      5994: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       5995:     }
                   5996:     $request->send_http_header;
1.44      ng       5997:     return '' if $request->header_only;
1.41      ng       5998:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 5999:     my $symb=&get_symb($request,1);
1.160     albertel 6000:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   6001:     my $command=$commands[0];
                   6002:     if ($#commands > 0) {
                   6003: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   6004:     }
1.353     albertel 6005:     $request->print(&Apache::loncommon::start_page('Grading'));
1.324     albertel 6006:     if ($symb eq '' && $command eq '') {
1.257     albertel 6007: 	if ($env{'user.adv'}) {
                   6008: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   6009: 		($env{'form.codethree'})) {
                   6010: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   6011: 		    $env{'form.codethree'};
1.41      ng       6012: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   6013: 		    &Apache::lonnet::checkin($token);
                   6014: 		if ($tsymb) {
1.137     albertel 6015: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       6016: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 6017: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   6018: 					  ('grade_username' => $tuname,
                   6019: 					   'grade_domain' => $tudom,
                   6020: 					   'grade_courseid' => $tcrsid,
                   6021: 					   'grade_symb' => $tsymb)));
1.41      ng       6022: 		    } else {
1.45      ng       6023: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 6024: 		    }
1.41      ng       6025: 		} else {
1.45      ng       6026: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       6027: 		}
1.14      www      6028: 	    } else {
1.41      ng       6029: 		$request->print(&Apache::lonxml::tokeninputfield());
                   6030: 	    }
                   6031: 	}
                   6032:     } else {
1.285     albertel 6033: 	&init_perm();
1.104     albertel 6034: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 6035: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 6036: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       6037: 	    &pickStudentPage($request);
1.103     albertel 6038: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       6039: 	    &displayPage($request);
1.104     albertel 6040: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       6041: 	    &updateGradeByPage($request);
1.104     albertel 6042: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       6043: 	    &processGroup($request);
1.104     albertel 6044: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       6045: 	    $request->print(&gradingmenu($request));
1.104     albertel 6046: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       6047: 	    $request->print(&viewgrades($request));
1.104     albertel 6048: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       6049: 	    $request->print(&processHandGrade($request));
1.106     albertel 6050: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       6051: 	    $request->print(&editgrades($request));
1.106     albertel 6052: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       6053: 	    $request->print(&verifyreceipt($request));
1.106     albertel 6054: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       6055: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 6056: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       6057: 	    $request->print(&csvupload($request));
1.106     albertel 6058: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       6059: 	    $request->print(&csvuploadmap($request));
1.246     albertel 6060: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 6061: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 6062: 		$request->print(&csvuploadoptions($request));
1.41      ng       6063: 	    } else {
1.257     albertel 6064: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   6065: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       6066: 		} else {
1.257     albertel 6067: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       6068: 		}
                   6069: 		$request->print(&csvuploadmap($request));
                   6070: 	    }
1.246     albertel 6071: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   6072: 	    $request->print(&csvuploadassign($request));
1.106     albertel 6073: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 6074: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 6075:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   6076:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 6077: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   6078: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 6079: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 6080: 	    $request->print(&scantron_process_students($request));
1.157     albertel 6081:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 6082:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6083: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 6084:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 6085:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 6086:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6087: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 6088:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 6089:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 6090: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 6091:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 6092: 	} elsif ($command) {
1.157     albertel 6093: 	    $request->print("Access Denied ($command)");
1.26      albertel 6094: 	}
1.2       albertel 6095:     }
1.353     albertel 6096:     $request->print(&Apache::loncommon::end_page());
1.44      ng       6097:     return '';
                   6098: }
                   6099: 
1.1       albertel 6100: 1;
                   6101: 
1.13      albertel 6102: __END__;

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