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

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

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