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

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

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