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

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

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