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

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

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