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

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

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