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

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

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