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

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

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