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

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

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