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

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

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