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

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

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