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

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

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