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

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

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