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

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

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