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

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

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