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

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

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