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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.329   ! albertel    4: # $Id: grades.pm,v 1.328 2006/03/07 02:50:15 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.326     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\\">");
1.326     albertel 1267:     pDoc.write("<font color=\\"green\\" size=+1>&nbsp;Compose Message for \"+fullname+\"</font><br /><br />");
1.76      ng       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;");
1.326     albertel 1302:     pDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       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\\">");
1.326     albertel 1371:     hDoc.write("<font color=\\"green\\" size=+1>&nbsp;Keyword Highlight Options</font><br /><br />");
1.76      ng       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;");
1.326     albertel 1395:     hDoc.write("<input type=\\"button\\" value=\\"Cancel\\" onClick=\\"self.close()\\"><br /><br />");
1.76      ng       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;
1.329   ! albertel 1500:     &Apache::lonxml::remember_problem_counter();
1.144     albertel 1501:     if ($mode eq 'both' or $mode eq 'text') {
                   1502: 	$rendered=&Apache::loncommon::get_student_view($symb,$uname,$udom,
1.257     albertel 1503: 					     $env{'request.course.id'});
1.144     albertel 1504:     }
1.58      albertel 1505:     if ($removeform) {
                   1506: 	$rendered=~s|<form(.*?)>||g;
                   1507: 	$rendered=~s|</form>||g;
                   1508: 	$rendered=~s|name="submit"|name="would_have_been_submit"|g;
                   1509:     }
1.144     albertel 1510:     my $companswer;
                   1511:     if ($mode eq 'both' or $mode eq 'answer') {
1.329   ! albertel 1512: 	&Apache::lonxml::restore_problem_counter();
1.144     albertel 1513: 	$companswer=&Apache::loncommon::get_student_answers($symb,$uname,$udom,
1.257     albertel 1514: 						    $env{'request.course.id'});
1.144     albertel 1515:     }
1.58      albertel 1516:     if ($removeform) {
                   1517: 	$companswer=~s|<form(.*?)>||g;
                   1518: 	$companswer=~s|</form>||g;
1.144     albertel 1519: 	$companswer=~s|name="submit"|name="would_have_been_submit"|g;
1.58      albertel 1520:     }
                   1521:     my $result.='<table border="0" width="100%"><tr><td bgcolor="#777777">';
1.71      ng       1522:     $result.='<table border="0" width="100%">';
1.144     albertel 1523:     if ($viewon) {
                   1524: 	$result.='<tr><td bgcolor="#e6ffff"><b> ';
                   1525: 	if ($mode eq 'both' or $mode eq 'text') {
                   1526: 	    $result.='View of the problem - ';
                   1527: 	} else {
                   1528: 	    $result.='Correct answer: ';
                   1529: 	}
1.257     albertel 1530: 	$result.=$env{'form.fullname'}.'</b></td></tr>';
1.144     albertel 1531:     }
                   1532:     if ($mode eq 'both') {
                   1533: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered.'<br />';
                   1534: 	$result.='<b>Correct answer:</b><br />'.$companswer;
                   1535:     } elsif ($mode eq 'text') {
                   1536: 	$result.='<tr><td bgcolor="#ffffff">'.$rendered;
                   1537:     } elsif ($mode eq 'answer') {
                   1538: 	$result.='<tr><td bgcolor="#ffffff">'.$companswer;
                   1539:     }
1.58      albertel 1540:     $result.='</td></tr></table>';
                   1541:     $result.='</td></tr></table><br />';
1.71      ng       1542:     return $result;
1.58      albertel 1543: }
                   1544: 
1.44      ng       1545: # --------------------------- show submissions of a student, option to grade 
                   1546: sub submission {
                   1547:     my ($request,$counter,$total) = @_;
                   1548: 
1.257     albertel 1549:     my ($uname,$udom)     = ($env{'form.student'},$env{'form.userdom'});
                   1550:     $udom = ($udom eq '' ? $env{'user.domain'} : $udom); #has form.userdom changed for a student?
                   1551:     my $usec = &Apache::lonnet::getsection($udom,$uname,$env{'request.course.id'});
                   1552:     $env{'form.fullname'} = &Apache::loncommon::plainname($uname,$udom,'lastname') if $env{'form.fullname'} eq '';
1.41      ng       1553: 
1.324     albertel 1554:     my $symb = &get_symb($request); 
                   1555:     if ($symb eq '') { $request->print("Unable to handle ambiguous references:."); return ''; }
1.104     albertel 1556: 
                   1557:     if (!&canview($usec)) {
1.116     ng       1558: 	$request->print('<font color="red">Unable to view requested student.('.
1.222     albertel 1559: 			$uname.'@'.$udom.' in section '.$usec.' in course id '.
1.257     albertel 1560: 			$env{'request.course.id'}.')</font>');
1.324     albertel 1561: 	$request->print(&show_grading_menu_form($symb));
1.104     albertel 1562: 	return;
                   1563:     }
                   1564: 
1.257     albertel 1565:     if (!$env{'form.lastSub'}) { $env{'form.lastSub'} = 'datesub'; }
                   1566:     if (!$env{'form.vProb'}) { $env{'form.vProb'} = 'yes'; }
                   1567:     if (!$env{'form.vAns'}) { $env{'form.vAns'} = 'yes'; }
                   1568:     my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.122     ng       1569:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   1570: 	'/check.gif" height="16" border="0" />';
1.41      ng       1571: 
                   1572:     # header info
                   1573:     if ($counter == 0) {
                   1574: 	&sub_page_js($request);
1.257     albertel 1575: 	&sub_page_kw_js($request) if ($env{'form.handgrade'} eq 'yes');
                   1576: 	$env{'form.probTitle'} = $env{'form.probTitle'} eq '' ? 
                   1577: 	    &Apache::lonnet::gettitle($symb) : $env{'form.probTitle'};
1.76      ng       1578: 
1.45      ng       1579: 	$request->print('<h3>&nbsp;<font color="#339933">Submission Record</font></h3>'."\n".
1.257     albertel 1580: 			'<font size=+1>&nbsp;<b>Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n");
1.118     ng       1581: 
1.257     albertel 1582: 	if ($env{'form.handgrade'} eq 'no') {
1.118     ng       1583: 	    my $checkMark='<br /><br />&nbsp;<b>Note:</b> Part(s) graded correct by the computer is marked with a '.
                   1584: 		$checkIcon.' symbol.'."\n";
                   1585: 	    $request->print($checkMark);
                   1586: 	}
1.41      ng       1587: 
1.44      ng       1588: 	# option to display problem, only once else it cause problems 
                   1589:         # with the form later since the problem has a form.
1.257     albertel 1590: 	if ($env{'form.vProb'} eq 'yes' or $env{'form.vAns'} eq 'yes') {
1.144     albertel 1591: 	    my $mode;
1.257     albertel 1592: 	    if ($env{'form.vProb'} eq 'yes' && $env{'form.vAns'} eq 'yes') {
1.144     albertel 1593: 		$mode='both';
1.257     albertel 1594: 	    } elsif ($env{'form.vProb'} eq 'yes') {
1.144     albertel 1595: 		$mode='text';
1.257     albertel 1596: 	    } elsif ($env{'form.vAns'} eq 'yes') {
1.144     albertel 1597: 		$mode='answer';
                   1598: 	    }
1.329   ! albertel 1599: 	    &Apache::lonxml::clear_problem_counter();
1.144     albertel 1600: 	    $request->print(&show_problem($request,$symb,$uname,$udom,0,1,$mode));
1.41      ng       1601: 	}
                   1602: 	
1.44      ng       1603: 	# kwclr is the only variable that is guaranteed to be non blank 
                   1604:         # if this subroutine has been called once.
1.41      ng       1605: 	my %keyhash = ();
1.257     albertel 1606: 	if ($env{'form.kwclr'} eq '' && $env{'form.handgrade'} eq 'yes') {
1.41      ng       1607: 	    %keyhash = &Apache::lonnet::dump('nohist_handgrade',
1.257     albertel 1608: 					     $env{'course.'.$env{'request.course.id'}.'.domain'},
                   1609: 					     $env{'course.'.$env{'request.course.id'}.'.num'});
1.41      ng       1610: 
1.257     albertel 1611: 	    my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
                   1612: 	    $env{'form.keywords'} = $keyhash{$symb.'_keywords'} ne '' ? $keyhash{$symb.'_keywords'} : '';
                   1613: 	    $env{'form.kwclr'}    = $keyhash{$loginuser.'_kwclr'} ne '' ? $keyhash{$loginuser.'_kwclr'} : 'red';
                   1614: 	    $env{'form.kwsize'}   = $keyhash{$loginuser.'_kwsize'} ne '' ? $keyhash{$loginuser.'_kwsize'} : '0';
                   1615: 	    $env{'form.kwstyle'}  = $keyhash{$loginuser.'_kwstyle'} ne '' ? $keyhash{$loginuser.'_kwstyle'} : '';
                   1616: 	    $env{'form.msgsub'}   = $keyhash{$symb.'_subject'} ne '' ? 
                   1617: 		$keyhash{$symb.'_subject'} : $env{'form.probTitle'};
                   1618: 	    $env{'form.savemsgN'} = $keyhash{$symb.'_savemsgN'} ne '' ? $keyhash{$symb.'_savemsgN'} : '0';
1.41      ng       1619: 	}
1.257     albertel 1620: 	my $overRideScore = $env{'form.overRideScore'} eq '' ? 'no' : $env{'form.overRideScore'};
1.44      ng       1621: 
1.303     banghart 1622: 	$request->print('<form action="/adm/grades" method="post" name="SCORE" enctype="multipart/form-data">'."\n".
1.41      ng       1623: 			'<input type="hidden" name="command"    value="handgrade" />'."\n".
1.257     albertel 1624: 			'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
                   1625: 			'<input type="hidden" name="Status"     value="'.$env{'form.Status'}.'" />'."\n".
1.120     ng       1626: 			'<input type="hidden" name="overRideScore" value="'.$overRideScore.'" />'."\n".
1.257     albertel 1627: 			'<input type="hidden" name="probTitle"  value="'.$env{'form.probTitle'}.'" />'."\n".
1.41      ng       1628: 			'<input type="hidden" name="refresh"    value="off" />'."\n".
1.120     ng       1629: 			'<input type="hidden" name="studentNo"  value="" />'."\n".
                   1630: 			'<input type="hidden" name="gradeOpt"   value="" />'."\n".
1.41      ng       1631: 			'<input type="hidden" name="symb"       value="'.$symb.'" />'."\n".
1.257     albertel 1632: 			'<input type="hidden" name="showgrading" value="'.$env{'form.showgrading'}.'" />'."\n".
                   1633: 			'<input type="hidden" name="vProb"      value="'.$env{'form.vProb'}.'" />'."\n".
                   1634: 			'<input type="hidden" name="vAns"       value="'.$env{'form.vAns'}.'" />'."\n".
                   1635: 			'<input type="hidden" name="lastSub"    value="'.$env{'form.lastSub'}.'" />'."\n".
1.326     albertel 1636: 			'<input type="hidden" name="section"    value="'.$env{'form.section'}.'" />'."\n".
                   1637: 			'<input type="hidden" name="submitonly" value="'.$env{'form.submitonly'}.'" />'."\n".
                   1638: 			'<input type="hidden" name="handgrade"  value="'.$env{'form.handgrade'}.'" />'."\n".
1.41      ng       1639: 			'<input type="hidden" name="NCT"'.
1.257     albertel 1640: 			' value="'.($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : $total+1).'" />'."\n");
                   1641: 	if ($env{'form.handgrade'} eq 'yes') {
                   1642: 	    $request->print('<input type="hidden" name="keywords" value="'.$env{'form.keywords'}.'" />'."\n".
                   1643: 			    '<input type="hidden" name="kwclr"    value="'.$env{'form.kwclr'}.'" />'."\n".
                   1644: 			    '<input type="hidden" name="kwsize"   value="'.$env{'form.kwsize'}.'" />'."\n".
                   1645: 			    '<input type="hidden" name="kwstyle"  value="'.$env{'form.kwstyle'}.'" />'."\n".
                   1646: 			    '<input type="hidden" name="msgsub"   value="'.$env{'form.msgsub'}.'" />'."\n".
1.123     ng       1647: 			    '<input type="hidden" name="shownSub" value="0" />'."\n".
1.257     albertel 1648: 			    '<input type="hidden" name="savemsgN" value="'.$env{'form.savemsgN'}.'" />'."\n");
1.154     albertel 1649: 	    foreach my $partid (&Apache::loncommon::get_env_multiple('form.vPart')) {
                   1650: 		$request->print('<input type="hidden" name="vPart" value="'.$partid.'" />'."\n");
                   1651: 	    }
1.123     ng       1652: 	}
1.41      ng       1653: 	
                   1654: 	my ($cts,$prnmsg) = (1,'');
1.257     albertel 1655: 	while ($cts <= $env{'form.savemsgN'}) {
1.41      ng       1656: 	    $prnmsg.='<input type="hidden" name="savemsg'.$cts.'" value="'.
1.123     ng       1657: 		(!exists($keyhash{$symb.'_savemsg'.$cts}) ? 
1.257     albertel 1658: 		 &Apache::lonfeedback::clear_out_html($env{'form.savemsg'.$cts}) :
1.80      ng       1659: 		 &Apache::lonfeedback::clear_out_html($keyhash{$symb.'_savemsg'.$cts})).
1.123     ng       1660: 		'" />'."\n".
                   1661: 		'<input type="hidden" name="shownOnce'.$cts.'" value="0" />'."\n";
1.41      ng       1662: 	    $cts++;
                   1663: 	}
                   1664: 	$request->print($prnmsg);
1.32      ng       1665: 
1.257     albertel 1666: 	if ($env{'form.handgrade'} eq 'yes' && $env{'form.showgrading'} eq 'yes') {
1.88      www      1667: #
                   1668: # Print out the keyword options line
                   1669: #
1.41      ng       1670: 	    $request->print(<<KEYWORDS);
1.38      ng       1671: &nbsp;<b>Keyword Options:</b>&nbsp;
1.122     ng       1672: <a href="javascript:keywords(document.SCORE)"; TARGET=_self>List</a>&nbsp; &nbsp;
1.38      ng       1673: <a href="#" onMouseDown="javascript:getSel(); return false"
                   1674:  CLASS="page">Paste Selection to List</a>&nbsp; &nbsp;
                   1675: <a href="javascript:kwhighlight()"; TARGET=_self>Highlight Attribute</a><br /><br />
                   1676: KEYWORDS
1.88      www      1677: #
                   1678: # Load the other essays for similarity check
                   1679: #
1.324     albertel 1680:             my (undef,undef,$essayurl) = &Apache::lonnet::decode_symb($symb);
1.88      www      1681: 	    my ($adom,$aname,$apath)=($essayurl=~/^(\w+)\/(\w+)\/(.*)$/);
                   1682: 	    $apath=&Apache::lonnet::escape($apath);
                   1683: 	    $apath=~s/\W/\_/gs;
                   1684: 	    %oldessays=&Apache::lonnet::dump('nohist_essay_'.$apath,$adom,$aname);
1.41      ng       1685:         }
                   1686:     }
1.44      ng       1687: 
1.257     albertel 1688:     if ($env{'form.vProb'} eq 'all' or $env{'form.vAns'} eq 'all') {
1.71      ng       1689: 	$request->print('<br /><br /><br />') if ($counter > 0);
1.144     albertel 1690: 	my $mode;
1.257     albertel 1691: 	if ($env{'form.vProb'} eq 'all' && $env{'form.vAns'} eq 'all') {
1.144     albertel 1692: 	    $mode='both';
1.257     albertel 1693: 	} elsif ($env{'form.vProb'} eq 'all' ) {
1.144     albertel 1694: 	    $mode='text';
1.257     albertel 1695: 	} elsif ($env{'form.vAns'} eq 'all') {
1.144     albertel 1696: 	    $mode='answer';
                   1697: 	}
1.329   ! albertel 1698: 	&Apache::lonxml::clear_problem_counter();
1.144     albertel 1699: 	$request->print(&show_problem($request,$symb,$uname,$udom,1,1,$mode));
1.58      albertel 1700:     }
1.144     albertel 1701: 
1.257     albertel 1702:     my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 1703:     my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.41      ng       1704: 
1.44      ng       1705:     # Display student info
1.41      ng       1706:     $request->print(($counter == 0 ? '' : '<br />'));
1.326     albertel 1707:     my $result='<table border="0" width="100%"><tr><td bgcolor="#777777">'."\n".
                   1708: 	'<table border="0" width="100%"><tr bgcolor="#edffff"><td>'."\n";
1.44      ng       1709: 
1.257     albertel 1710:     $result.='<b>Fullname: </b>'.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).'<br />'."\n";
1.45      ng       1711:     $result.='<input type="hidden" name="name'.$counter.
1.257     albertel 1712: 	'" value="'.$env{'form.fullname'}.'" />'."\n";
1.41      ng       1713: 
1.118     ng       1714:     # If any part of the problem is an essay-response (handgraded), then check for collaborators
1.45      ng       1715:     my @col_fullnames;
1.56      matthew  1716:     my ($classlist,$fullname);
1.257     albertel 1717:     if ($env{'form.handgrade'} eq 'yes') {
1.80      ng       1718: 	($classlist,undef,$fullname) = &getclasslist('all','0');
1.41      ng       1719: 	for (keys (%$handgrade)) {
1.44      ng       1720: 	    my $ncol = &Apache::lonnet::EXT('resource.'.$_.
1.57      matthew  1721: 					    '.maxcollaborators',
                   1722:                                             $symb,$udom,$uname);
                   1723: 	    next if ($ncol <= 0);
                   1724:             s/\_/\./g;
                   1725:             next if ($record{'resource.'.$_.'.collaborators'} eq '');
1.86      ng       1726:             my @goodcollaborators = ();
                   1727:             my @badcollaborators  = ();
                   1728: 	    foreach (split(/,?\s+/,$record{'resource.'.$_.'.collaborators'})) { 
                   1729: 		$_ =~ s/[\$\^\(\)]//g;
                   1730: 		next if ($_ eq '');
1.80      ng       1731: 		my ($co_name,$co_dom) = split /\@|:/,$_;
1.86      ng       1732: 		$co_dom = $udom if (! defined($co_dom) || $co_dom =~ /^domain$/i);
1.80      ng       1733: 		next if ($co_name eq $uname && $co_dom eq $udom);
1.86      ng       1734: 		# Doing this grep allows 'fuzzy' specification
                   1735: 		my @Matches = grep /^$co_name:$co_dom$/i,keys %$classlist;
                   1736: 		if (! scalar(@Matches)) {
                   1737: 		    push @badcollaborators,$_;
                   1738: 		} else {
                   1739: 		    push @goodcollaborators, @Matches;
                   1740: 		}
1.80      ng       1741: 	    }
1.86      ng       1742:             if (scalar(@goodcollaborators) != 0) {
1.57      matthew  1743:                 $result.='<b>Collaborators: </b>';
1.86      ng       1744:                 foreach (@goodcollaborators) {
                   1745: 		    my ($lastname,$givenn) = split(/,/,$$fullname{$_});
                   1746: 		    push @col_fullnames, $givenn.' '.$lastname;
                   1747: 		    $result.=$$fullname{$_}.'&nbsp; &nbsp; &nbsp;';
                   1748: 		}
1.57      matthew  1749:                 $result.='<br />'."\n";
1.150     albertel 1750: 		my ($part)=split(/\./,$_);
1.86      ng       1751: 		$result.='<input type="hidden" name="collaborator'.$counter.
1.150     albertel 1752: 		    '" value="'.$part.':'.(join ':',@goodcollaborators).'" />'.
                   1753: 		    "\n";
1.86      ng       1754: 	    }
                   1755: 	    if (scalar(@badcollaborators) > 0) {
                   1756: 		$result.='<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1757: 		$result.='This student has submitted ';
                   1758: 		$result.=(scalar(@badcollaborators) == 1) ? 'an invalid collaborator' : 'invalid collaborators';
                   1759: 		$result .= ': '.join(', ',@badcollaborators);
                   1760: 		$result .= '</td></tr></table>';
                   1761: 	    }         
                   1762: 	    if (scalar(@badcollaborators > $ncol)) {
                   1763: 		$result .= '<table border="0"><tr bgcolor="#ffbbbb"><td>';
                   1764: 		$result .= 'This student has submitted too many '.
                   1765: 		    'collaborators.  Maximum is '.$ncol.'.';
                   1766: 		$result .= '</td></tr></table>';
                   1767: 	    }
1.41      ng       1768: 	}
                   1769:     }
1.44      ng       1770:     $request->print($result."\n");
1.33      ng       1771: 
1.44      ng       1772:     # print student answer/submission
                   1773:     # Options are (1) Handgaded submission only
                   1774:     #             (2) Last submission, includes submission that is not handgraded 
                   1775:     #                  (for multi-response type part)
                   1776:     #             (3) Last submission plus the parts info
                   1777:     #             (4) The whole record for this student
1.257     albertel 1778:     if ($env{'form.lastSub'} =~ /^(lastonly|hdgrade)$/) {
1.151     albertel 1779: 	my ($string,$timestamp)= &get_last_submission(\%record);
                   1780: 	my $lastsubonly=''.
                   1781: 	    ($$timestamp eq '' ? '' : '<b>Date Submitted:</b> '.
                   1782: 	     $$timestamp)."</td></tr>\n";
                   1783: 	if ($$timestamp eq '') {
                   1784: 	    $lastsubonly.='<tr><td bgcolor="#ffffe6">'.$$string[0]; 
                   1785: 	} else {
                   1786: 	    my %seenparts;
                   1787: 	    for my $part (sort keys(%$handgrade)) {
                   1788: 		my ($partid,$respid) = split(/_/,$part);
1.324     albertel 1789: 		my $display_part=&get_display_part($partid,$symb);
1.257     albertel 1790: 		if ($env{"form.$uname:$udom:$partid:submitted_by"}) {
1.151     albertel 1791: 		    if (exists($seenparts{$partid})) { next; }
                   1792: 		    $seenparts{$partid}=1;
1.207     albertel 1793: 		    my $submitby='<b>Part:</b> '.$display_part.
                   1794: 			' <b>Collaborative submission by:</b> '.
1.151     albertel 1795: 			'<a href="javascript:viewSubmitter(\''.
1.257     albertel 1796: 			$env{"form.$uname:$udom:$partid:submitted_by"}.
1.151     albertel 1797: 			'\')"; TARGET=_self>'.
1.257     albertel 1798: 			$$fullname{$env{"form.$uname:$udom:$partid:submitted_by"}}.'</a><br />';
1.151     albertel 1799: 		    $request->print($submitby);
                   1800: 		    next;
                   1801: 		}
                   1802: 		my $responsetype = $responseType->{$partid}->{$respid};
                   1803: 		if (!exists($record{"resource.$partid.$respid.submission"})) {
1.207     albertel 1804: 		    $lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1805: 			$display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1806: 			' )</font>&nbsp; &nbsp;'.
                   1807: 			'<font color="red">Nothing submitted - no attempts</font><br /><br />';
                   1808: 		    next;
                   1809: 		}
                   1810: 		foreach (@$string) {
                   1811: 		    my ($partid,$respid) = /^resource\.([^\.]*)\.([^\.]*)\.submission/;
                   1812: 		    if ($part ne ($partid.'_'.$respid)) { next; }
                   1813: 		    my ($ressub,$subval) = split(/:/,$_,2);
                   1814: 		    # Similarity check
                   1815: 		    my $similar='';
1.257     albertel 1816: 		    if($env{'form.checkPlag'}){
1.151     albertel 1817: 			my ($oname,$odom,$ocrsid,$oessay,$osim)=
                   1818: 			    &most_similar($uname,$udom,$subval);
                   1819: 			if ($osim) {
                   1820: 			    $osim=int($osim*100.0);
                   1821: 			    $similar="<hr /><h3><font color=\"#FF0000\">Essay".
                   1822: 				" is $osim% similar to an essay by ".
                   1823: 				&Apache::loncommon::plainname($oname,$odom).
                   1824: 				'</font></h3><blockquote><i>'.
                   1825: 				&keywords_highlight($oessay).
                   1826: 				'</i></blockquote><hr />';
                   1827: 			}
1.150     albertel 1828: 		    }
1.151     albertel 1829: 		    my $order=&get_order($partid,$respid,$symb,$uname,$udom);
1.257     albertel 1830: 		    if ($env{'form.lastSub'} eq 'lastonly' || 
                   1831: 			($env{'form.lastSub'} eq 'hdgrade' && 
1.151     albertel 1832: 			 $$handgrade{$part} eq 'yes')) {
1.324     albertel 1833: 			my $display_part=&get_display_part($partid,$symb);
1.207     albertel 1834: 			$lastsubonly.='<tr><td bgcolor="#ffffe6"><b>Part:</b> '.
                   1835: 			    $display_part.' <font color="#999999">( ID '.$respid.
1.151     albertel 1836: 			    ' )</font>&nbsp; &nbsp;';
1.313     banghart 1837: 			my $files=&get_submitted_files($udom,$uname,$partid,$respid,\%record);
                   1838: 			if (@$files) {
1.232     albertel 1839: 			    $lastsubonly.='<br /><font color="red" size="1">Like all files provided by users, this file may contain virusses</font><br />';
1.303     banghart 1840: 			    my $file_counter = 0;
1.313     banghart 1841: 			    foreach my $file (@$files) {
1.303     banghart 1842: 			        $file_counter ++;
1.232     albertel 1843: 				&Apache::lonnet::allowuploaded('/adm/grades',$file);
1.314     albertel 1844: 				$lastsubonly.='<br /><a href="'.$file.'" target="lonGRDs"><img src="'.&Apache::loncommon::icon($file).'" border="0"> '.$file.'</a>';
1.232     albertel 1845: 			    }
1.236     albertel 1846: 			    $lastsubonly.='<br />';
1.41      ng       1847: 			}
1.151     albertel 1848: 			$lastsubonly.='<b>Submitted Answer: </b>'.
                   1849: 			    &cleanRecord($subval,$responsetype,$symb,$partid,
                   1850: 					 $respid,\%record,$order);
                   1851: 			if ($similar) {$lastsubonly.="<br /><br />$similar\n";}
1.41      ng       1852: 		    }
                   1853: 		}
                   1854: 	    }
1.151     albertel 1855: 	}
                   1856: 	$lastsubonly.='</td></tr><tr bgcolor="#ffffff"><td>'."\n";
                   1857: 	$request->print($lastsubonly);
1.257     albertel 1858:     } elsif ($env{'form.lastSub'} eq 'datesub') {
1.324     albertel 1859: 	my (undef,$responseType,undef,$parts) = &showResourceInfo($symb);
1.148     albertel 1860: 	$request->print(&displaySubByDates($symb,\%record,$parts,$responseType,$checkIcon,$uname,$udom));
1.257     albertel 1861:     } elsif ($env{'form.lastSub'} =~ /^(last|all)$/) {
1.41      ng       1862: 	$request->print(&Apache::loncommon::get_previous_attempt($symb,$uname,$udom,
1.257     albertel 1863: 								 $env{'request.course.id'},
1.44      ng       1864: 								 $last,'.submission',
                   1865: 								 'Apache::grades::keywords_highlight'));
1.41      ng       1866:     }
1.120     ng       1867: 
1.121     ng       1868:     $request->print('<input type="hidden" name="unamedom'.$counter.'" value="'.$uname.':'
                   1869: 	.$udom.'" />'."\n");
1.41      ng       1870:     
1.44      ng       1871:     # return if view submission with no grading option
1.257     albertel 1872:     if ($env{'form.showgrading'} eq '' || (!&canmodify($usec))) {
1.120     ng       1873: 	my $toGrade.='<input type="button" value="Grade Student" '.
1.121     ng       1874: 	    'onClick="javascript:checksubmit(this.form,\'Grade Student\',\''
                   1875: 	    .$counter.'\');" TARGET=_self> &nbsp;'."\n" if (&canmodify($usec));
1.169     albertel 1876: 	$toGrade.='</td></tr></table></td></tr></table>'."\n";
1.257     albertel 1877: 	if (($env{'form.command'} eq 'submission') || 
                   1878: 	    ($env{'form.command'} eq 'processGroup' && $counter == $total)) {
1.324     albertel 1879: 	    $toGrade.='</form>'.&show_grading_menu_form($symb); 
1.169     albertel 1880: 	}
1.180     albertel 1881: 	$request->print($toGrade);
1.41      ng       1882: 	return;
1.180     albertel 1883:     } else {
                   1884: 	$request->print('</td></tr></table></td></tr></table>'."\n");
1.41      ng       1885:     }
1.33      ng       1886: 
1.121     ng       1887:     # essay grading message center
1.257     albertel 1888:     if ($env{'form.handgrade'} eq 'yes') {
                   1889: 	my ($lastname,$givenn) = split(/,/,$env{'form.fullname'});
1.118     ng       1890: 	my $msgfor = $givenn.' '.$lastname;
                   1891: 	if (scalar(@col_fullnames) > 0) {
                   1892: 	    my $lastone = pop @col_fullnames;
                   1893: 	    $msgfor .= ', '.(join ', ',@col_fullnames).' and '.$lastone.'.';
                   1894: 	}
                   1895: 	$msgfor =~ s/\'/\\'/g; #' stupid emacs - no! javascript
1.121     ng       1896: 	$result='<input type="hidden" name="includemsg'.$counter.'" value="" />'."\n".
                   1897: 	    '<input type="hidden" name="newmsg'.$counter.'" value="" />'."\n";
                   1898: 	$result.='&nbsp;<a href="javascript:msgCenter(document.SCORE,'.$counter.
1.118     ng       1899: 	    ',\''.$msgfor.'\')"; TARGET=_self>'.
1.298     www      1900: 	    &mt('Compose message to student').(scalar(@col_fullnames) >= 1 ? 's' : '').'</a> ('.
                   1901: 	    &mt('incl. grades').' <input type="checkbox" name="withgrades'.$counter.'" />)'.
1.118     ng       1902: 	    '<img src="'.$request->dir_config('lonIconsURL').
                   1903: 	    '/mailbkgrd.gif" width="14" height="10" name="mailicon'.$counter.'" />'."\n".
1.298     www      1904: 	    '<br />&nbsp;('.
                   1905: 	    &mt('Message will be sent when you click on Save & Next below.').")\n";
1.121     ng       1906: 	$request->print($result);
1.118     ng       1907:     }
1.300     albertel 1908:     if ($perm{'vgr'}) {
1.297     www      1909: 	$request->print('<br />'.
1.300     albertel 1910: 	    &Apache::loncommon::track_student_link(&mt('View recent activity'),
                   1911: 						   $uname,$udom,'check'));
1.297     www      1912:     }
1.300     albertel 1913:     if ($perm{'opa'}) {
1.297     www      1914: 	$request->print('<br />'.
1.300     albertel 1915: 	    &Apache::loncommon::pprmlink(&mt('Set/Change parameters'),
                   1916: 					 $uname,$udom,$symb,'check'));
1.297     www      1917:     }
1.41      ng       1918: 
                   1919:     my %seen = ();
                   1920:     my @partlist;
1.129     ng       1921:     my @gradePartRespid;
1.322     albertel 1922:     for my $part_resp (sort(keys(%$handgrade))) {
1.317     banghart 1923: 	my ($partid,$respid) = split(/_/, $part_resp);
1.322     albertel 1924: 	next if ($seen{$partid} > 0);
1.41      ng       1925: 	$seen{$partid}++;
1.317     banghart 1926: 	next if ($$handgrade{$part_resp} =~ /:no$/ && $env{'form.lastSub'} =~ /^(hdgrade)$/);
1.41      ng       1927: 	push @partlist,$partid;
1.129     ng       1928: 	push @gradePartRespid,$partid.'.'.$respid;
1.322     albertel 1929: 	$request->print(&gradeBox($request,$symb,$uname,$udom,$counter,$partid,\%record));
1.41      ng       1930:     }
1.45      ng       1931:     $result='<input type="hidden" name="partlist'.$counter.
                   1932: 	'" value="'.(join ":",@partlist).'" />'."\n";
1.129     ng       1933:     $result.='<input type="hidden" name="gradePartRespid'.
                   1934: 	'" value="'.(join ":",@gradePartRespid).'" />'."\n" if ($counter == 0);
1.45      ng       1935:     my $ctr = 0;
                   1936:     while ($ctr < scalar(@partlist)) {
                   1937: 	$result.='<input type="hidden" name="partid'.$counter.'_'.$ctr.'" value="'.
                   1938: 	    $partlist[$ctr].'" />'."\n";
                   1939: 	$ctr++;
                   1940:     }
                   1941:     $request->print($result.'</td></tr></table></td></tr></table>'."\n");
1.41      ng       1942: 
                   1943:     # print end of form
                   1944:     if ($counter == $total) {
1.297     www      1945: 	my $endform='<table border="0"><tr><td>'."\n";
1.119     ng       1946: 	$endform.='<input type="button" value="Save & Next" '.
                   1947: 	    'onClick="javascript:checksubmit(this.form,\'Save & Next\','.
                   1948: 	    $total.','.scalar(@partlist).');" TARGET=_self> &nbsp;'."\n";
                   1949: 	my $ntstu ='<select name="NTSTU">'.
                   1950: 	    '<option>1</option><option>2</option>'.
                   1951: 	    '<option>3</option><option>5</option>'.
                   1952: 	    '<option>7</option><option>10</option></select>'."\n";
1.257     albertel 1953: 	my $nsel = ($env{'form.NTSTU'} ne '' ? $env{'form.NTSTU'} : '1');
1.119     ng       1954: 	$ntstu =~ s/<option>$nsel</<option selected="on">$nsel</;
                   1955: 	$endform.=$ntstu.'student(s) &nbsp;&nbsp;';
1.126     ng       1956: 	$endform.='<input type="button" value="Previous" '.
                   1957: 	    'onClick="javascript:checksubmit(this.form,\'Previous\');" TARGET=_self> &nbsp;'."\n".
                   1958: 	    '<input type="button" value="Next" '.
                   1959: 	    'onClick="javascript:checksubmit(this.form,\'Next\');" TARGET=_self> &nbsp;';
                   1960: 	$endform.='(Next and Previous (student) do not save the scores.)'."\n" ;
1.45      ng       1961: 	$endform.='</td><tr></table></form>';
1.324     albertel 1962: 	$endform.=&show_grading_menu_form($symb);
1.41      ng       1963: 	$request->print($endform);
                   1964:     }
                   1965:     return '';
1.38      ng       1966: }
                   1967: 
1.44      ng       1968: #--- Retrieve the last submission for all the parts
1.38      ng       1969: sub get_last_submission {
1.119     ng       1970:     my ($returnhash)=@_;
1.46      ng       1971:     my (@string,$timestamp);
1.119     ng       1972:     if ($$returnhash{'version'}) {
1.46      ng       1973: 	my %lasthash=();
                   1974: 	my ($version);
1.119     ng       1975: 	for ($version=1;$version<=$$returnhash{'version'};$version++) {
                   1976: 	    foreach (sort(split(/\:/,$$returnhash{$version.':keys'}))) {
                   1977: 		$lasthash{$_}=$$returnhash{$version.':'.$_};
                   1978: 		   $timestamp = scalar(localtime($$returnhash{$version.':timestamp'}));
1.46      ng       1979: 	    }
                   1980: 	}
                   1981: 	foreach ((keys %lasthash)) {
                   1982: 	    if ($_ =~ /\.submission$/) {
                   1983: 		my ($partid,$foo) = split(/submission$/,$_);
                   1984: 		my $draft  = $lasthash{$partid.'awarddetail'} eq 'DRAFT' ?
                   1985: 		    '<font color="red">Draft Copy</font> ' : '';
                   1986: 		push @string, (join(':',$_,$draft.$lasthash{$_}));
1.41      ng       1987: 	    }
                   1988: 	}
                   1989:     }
1.125     ng       1990:     @string = $string[0] eq '' ? '<font color="red">Nothing submitted - no attempts.</font>' : @string;
1.46      ng       1991:     return \@string,\$timestamp;
1.38      ng       1992: }
1.35      ng       1993: 
1.44      ng       1994: #--- High light keywords, with style choosen by user.
1.38      ng       1995: sub keywords_highlight {
1.44      ng       1996:     my $string    = shift;
1.257     albertel 1997:     my $size      = $env{'form.kwsize'} eq '0' ? '' : 'size='.$env{'form.kwsize'};
                   1998:     my $styleon   = $env{'form.kwstyle'} eq ''  ? '' : $env{'form.kwstyle'};
1.41      ng       1999:     (my $styleoff = $styleon) =~ s/\</\<\//;
1.257     albertel 2000:     my @keylist   = split(/[,\s+]/,$env{'form.keywords'});
1.41      ng       2001:     foreach (@keylist) {
1.257     albertel 2002: 	$string =~ s/\b\Q$_\E(\b|\.)/<font color\=$env{'form.kwclr'} $size\>$styleon$_$styleoff<\/font>/gi;
1.41      ng       2003:     }
                   2004:     return $string;
1.38      ng       2005: }
1.36      ng       2006: 
1.44      ng       2007: #--- Called from submission routine
1.38      ng       2008: sub processHandGrade {
1.41      ng       2009:     my ($request) = shift;
1.324     albertel 2010:     my $symb   = &get_symb($request);
                   2011:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.257     albertel 2012:     my $button = $env{'form.gradeOpt'};
                   2013:     my $ngrade = $env{'form.NCT'};
                   2014:     my $ntstu  = $env{'form.NTSTU'};
1.301     albertel 2015:     my $cdom   = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2016:     my $cnum   = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2017: 
1.44      ng       2018:     if ($button eq 'Save & Next') {
                   2019: 	my $ctr = 0;
                   2020: 	while ($ctr < $ngrade) {
1.257     albertel 2021: 	    my ($uname,$udom) = split(/:/,$env{'form.unamedom'.$ctr});
1.324     albertel 2022: 	    my ($errorflag,$pts,$wgt) = &saveHandGrade($request,$symb,$uname,$udom,$ctr);
1.71      ng       2023: 	    if ($errorflag eq 'no_score') {
                   2024: 		$ctr++;
                   2025: 		next;
                   2026: 	    }
1.104     albertel 2027: 	    if ($errorflag eq 'not_allowed') {
                   2028: 		$request->print("<font color=\"red\">Not allowed to modify grades for $uname:$udom</font>");
                   2029: 		$ctr++;
                   2030: 		next;
                   2031: 	    }
1.257     albertel 2032: 	    my $includemsg = $env{'form.includemsg'.$ctr};
1.44      ng       2033: 	    my ($subject,$message,$msgstatus) = ('','','');
1.62      albertel 2034: 	    if ($includemsg =~ /savemsg|newmsg\Q$ctr\E/) {
1.298     www      2035: 		$subject = $env{'form.msgsub'} if ($includemsg =~ /msgsub/);
1.295     www      2036: 		unless ($subject=~/\w/) { $subject=&mt('Grading Feedback'); }
1.44      ng       2037: 		my (@msgnum) = split(/,/,$includemsg);
                   2038: 		foreach (@msgnum) {
1.257     albertel 2039: 		    $message.=$env{'form.'.$_} if ($_ =~ /savemsg|newmsg/ && $_ ne '');
1.44      ng       2040: 		}
1.80      ng       2041: 		$message =&Apache::lonfeedback::clear_out_html($message);
1.298     www      2042: 		if ($env{'form.withgrades'.$ctr}) {
                   2043: 		    $message.="\n\nPoint".($pts > 1 ? 's':'').' awarded = '.$pts.' out of '.$wgt;
                   2044: 		    $message.=" for <a href=\"".
1.80      ng       2045: 		    &Apache::lonnet::clutter($url).
1.257     albertel 2046: 		    "?symb=$symb\">$env{'form.probTitle'}</a>";
1.298     www      2047: 		}
1.324     albertel 2048: 		$msgstatus = &Apache::lonmsg::user_normal_msg($uname,$udom,
                   2049: 							      $subject.' ['.
                   2050: 							      &Apache::lonnet::declutter($url).']',$message);
1.296     www      2051: 		$request->print('<br />'.&mt('Sending message to [_1]@[_2]',$uname,$udom).': '.
                   2052: 				$msgstatus);
1.44      ng       2053: 	    }
1.257     albertel 2054: 	    if ($env{'form.collaborator'.$ctr}) {
1.155     albertel 2055: 		my @collabstrs=&Apache::loncommon::get_env_multiple("form.collaborator$ctr");
1.150     albertel 2056: 		foreach my $collabstr (@collabstrs) {
                   2057: 		    my ($part,@collaborators) = split(/:/,$collabstr);
1.310     banghart 2058: 		    foreach my $collaborator (@collaborators) {
1.150     albertel 2059: 			my ($errorflag,$pts,$wgt) = 
1.324     albertel 2060: 			    &saveHandGrade($request,$symb,$collaborator,$udom,$ctr,
1.257     albertel 2061: 					   $env{'form.unamedom'.$ctr},$part);
1.150     albertel 2062: 			if ($errorflag eq 'not_allowed') {
1.310     banghart 2063: 			    $request->print("<font color=\"red\">Not allowed to modify grades for $collaborator:$udom</font>");
1.150     albertel 2064: 			    next;
                   2065: 			} else {
                   2066: 			    if ($message ne '') {
1.310     banghart 2067: 				$msgstatus = &Apache::lonmsg::user_normal_msg($collaborator,$udom,$env{'form.msgsub'},$message);
1.150     albertel 2068: 			    }
1.104     albertel 2069: 			}
1.44      ng       2070: 		    }
                   2071: 		}
                   2072: 	    }
                   2073: 	    $ctr++;
                   2074: 	}
                   2075:     }
                   2076: 
1.257     albertel 2077:     if ($env{'form.handgrade'} eq 'yes') {
1.119     ng       2078: 	# Keywords sorted in alphabatical order
1.257     albertel 2079: 	my $loginuser = $env{'user.name'}.':'.$env{'user.domain'};
1.119     ng       2080: 	my %keyhash = ();
1.257     albertel 2081: 	$env{'form.keywords'}           =~ s/,\s{0,}|\s+/ /g;
                   2082: 	$env{'form.keywords'}           =~ s/^\s+|\s+$//;
                   2083: 	my (@keywords) = sort(split(/\s+/,$env{'form.keywords'}));
                   2084: 	$env{'form.keywords'} = join(' ',@keywords);
                   2085: 	$keyhash{$symb.'_keywords'}     = $env{'form.keywords'};
                   2086: 	$keyhash{$symb.'_subject'}      = $env{'form.msgsub'};
                   2087: 	$keyhash{$loginuser.'_kwclr'}   = $env{'form.kwclr'};
                   2088: 	$keyhash{$loginuser.'_kwsize'}  = $env{'form.kwsize'};
                   2089: 	$keyhash{$loginuser.'_kwstyle'} = $env{'form.kwstyle'};
1.119     ng       2090: 
                   2091: 	# message center - Order of message gets changed. Blank line is eliminated.
1.257     albertel 2092: 	# New messages are saved in env for the next student.
1.119     ng       2093: 	# All messages are saved in nohist_handgrade.db
                   2094: 	my ($ctr,$idx) = (1,1);
1.257     albertel 2095: 	while ($ctr <= $env{'form.savemsgN'}) {
                   2096: 	    if ($env{'form.savemsg'.$ctr} ne '') {
                   2097: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.savemsg'.$ctr};
1.119     ng       2098: 		$idx++;
                   2099: 	    }
                   2100: 	    $ctr++;
1.41      ng       2101: 	}
1.119     ng       2102: 	$ctr = 0;
                   2103: 	while ($ctr < $ngrade) {
1.257     albertel 2104: 	    if ($env{'form.newmsg'.$ctr} ne '') {
                   2105: 		$keyhash{$symb.'_savemsg'.$idx} = $env{'form.newmsg'.$ctr};
                   2106: 		$env{'form.savemsg'.$idx} = $env{'form.newmsg'.$ctr};
1.119     ng       2107: 		$idx++;
                   2108: 	    }
                   2109: 	    $ctr++;
1.41      ng       2110: 	}
1.257     albertel 2111: 	$env{'form.savemsgN'} = --$idx;
                   2112: 	$keyhash{$symb.'_savemsgN'} = $env{'form.savemsgN'};
1.119     ng       2113: 	my $putresult = &Apache::lonnet::put
1.301     albertel 2114: 	    ('nohist_handgrade',\%keyhash,$cdom,$cnum);
1.41      ng       2115:     }
1.44      ng       2116:     # Called by Save & Refresh from Highlight Attribute Window
1.257     albertel 2117:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
                   2118:     if ($env{'form.refresh'} eq 'on') {
1.86      ng       2119: 	my ($ctr,$total) = (0,0);
                   2120: 	while ($ctr < $ngrade) {
1.257     albertel 2121: 	    $total++ if  $env{'form.unamedom'.$ctr} ne '';
1.86      ng       2122: 	    $ctr++;
                   2123: 	}
1.257     albertel 2124: 	$env{'form.NTSTU'}=$ngrade;
1.86      ng       2125: 	$ctr = 0;
                   2126: 	while ($ctr < $total) {
1.257     albertel 2127: 	    my $processUser = $env{'form.unamedom'.$ctr};
                   2128: 	    ($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2129: 	    $env{'form.fullname'} = $$fullname{$processUser};
1.86      ng       2130: 	    &submission($request,$ctr,$total-1);
1.41      ng       2131: 	    $ctr++;
                   2132: 	}
                   2133: 	return '';
                   2134:     }
1.36      ng       2135: 
1.121     ng       2136: # Go directly to grade student - from submission or link from chart page
1.120     ng       2137:     if ($button eq 'Grade Student') {
1.324     albertel 2138: 	(undef,undef,$env{'form.handgrade'},undef,undef) = &showResourceInfo($symb);
1.257     albertel 2139: 	my $processUser = $env{'form.unamedom'.$env{'form.studentNo'}};
                   2140: 	($env{'form.student'},$env{'form.userdom'}) = split(/:/,$processUser);
                   2141: 	$env{'form.fullname'} = $$fullname{$processUser};
1.120     ng       2142: 	&submission($request,0,0);
                   2143: 	return '';
                   2144:     }
                   2145: 
1.44      ng       2146:     # Get the next/previous one or group of students
1.257     albertel 2147:     my $firststu = $env{'form.unamedom0'};
                   2148:     my $laststu = $env{'form.unamedom'.($ngrade-1)};
1.119     ng       2149:     my $ctr = 2;
1.41      ng       2150:     while ($laststu eq '') {
1.257     albertel 2151: 	$laststu  = $env{'form.unamedom'.($ngrade-$ctr)};
1.41      ng       2152: 	$ctr++;
                   2153: 	$laststu = $firststu if ($ctr > $ngrade);
                   2154:     }
1.44      ng       2155: 
1.41      ng       2156:     my (@parsedlist,@nextlist);
                   2157:     my ($nextflg) = 0;
1.294     albertel 2158:     foreach (sort 
                   2159: 	     {
                   2160: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2161: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2162: 		 }
                   2163: 		 return $a cmp $b;
                   2164: 	     } (keys(%$fullname))) {
1.41      ng       2165: 	if ($nextflg == 1 && $button =~ /Next$/) {
                   2166: 	    push @parsedlist,$_;
                   2167: 	}
                   2168: 	$nextflg = 1 if ($_ eq $laststu);
                   2169: 	if ($button eq 'Previous') {
                   2170: 	    last if ($_ eq $firststu);
                   2171: 	    push @parsedlist,$_;
                   2172: 	}
                   2173:     }
                   2174:     $ctr = 0;
                   2175:     @parsedlist = reverse @parsedlist if ($button eq 'Previous');
1.324     albertel 2176:     my ($partlist) = &response_type($symb);
1.41      ng       2177:     foreach my $student (@parsedlist) {
1.257     albertel 2178: 	my $submitonly=$env{'form.submitonly'};
1.41      ng       2179: 	my ($uname,$udom) = split(/:/,$student);
1.301     albertel 2180: 	
                   2181: 	if ($submitonly eq 'queued') {
                   2182: 	    my %queue_status = 
                   2183: 		&Apache::bridgetask::get_student_status($symb,$cdom,$cnum,
                   2184: 							$udom,$uname);
                   2185: 	    next if (!defined($queue_status{'gradingqueue'}));
                   2186: 	}
                   2187: 
1.156     albertel 2188: 	if ($submitonly =~ /^(yes|graded|incorrect)$/) {
1.257     albertel 2189: #	    my %record = &Apache::lonnet::restore($symb,$env{'request.course.id'},$udom,$uname);
1.324     albertel 2190: 	    my %status=&student_gradeStatus($symb,$udom,$uname,$partlist);
1.145     albertel 2191: 	    my $submitted = 0;
1.248     albertel 2192: 	    my $ungraded = 0;
                   2193: 	    my $incorrect = 0;
1.145     albertel 2194: 	    foreach (keys(%status)) {
                   2195: 		$submitted = 1 if ($status{$_} ne 'nothing');
1.248     albertel 2196: 		$ungraded = 1 if ($status{$_} =~ /^ungraded/);
                   2197: 		$incorrect = 1 if ($status{$_} =~ /^incorrect/);
1.145     albertel 2198: 		my ($foo,$partid,$foo1) = split(/\./,$_);
                   2199: 		if ($status{'resource.'.$partid.'.submitted_by'} ne '') {
                   2200: 		    $submitted = 0;
                   2201: 		}
1.41      ng       2202: 	    }
1.156     albertel 2203: 	    next if (!$submitted && ($submitonly eq 'yes' ||
                   2204: 				     $submitonly eq 'incorrect' ||
                   2205: 				     $submitonly eq 'graded'));
1.248     albertel 2206: 	    next if (!$ungraded && ($submitonly eq 'graded'));
                   2207: 	    next if (!$incorrect && $submitonly eq 'incorrect');
1.41      ng       2208: 	}
                   2209: 	push @nextlist,$student if ($ctr < $ntstu);
1.129     ng       2210: 	last if ($ctr == $ntstu);
1.41      ng       2211: 	$ctr++;
                   2212:     }
1.36      ng       2213: 
1.41      ng       2214:     $ctr = 0;
                   2215:     my $total = scalar(@nextlist)-1;
1.39      ng       2216: 
1.41      ng       2217:     foreach (sort @nextlist) {
                   2218: 	my ($uname,$udom,$submitter) = split(/:/);
1.257     albertel 2219: 	$env{'form.student'}  = $uname;
                   2220: 	$env{'form.userdom'}  = $udom;
                   2221: 	$env{'form.fullname'} = $$fullname{$_};
1.41      ng       2222: 	&submission($request,$ctr,$total);
                   2223: 	$ctr++;
                   2224:     }
                   2225:     if ($total < 0) {
                   2226: 	my $the_end = '<h3><font color="red">LON-CAPA User Message</font></h3><br />'."\n";
                   2227: 	$the_end.='<b>Message: </b> No more students for this section or class.<br /><br />'."\n";
                   2228: 	$the_end.='Click on the button below to return to the grading menu.<br /><br />'."\n";
1.324     albertel 2229: 	$the_end.=&show_grading_menu_form($symb);
1.41      ng       2230: 	$request->print($the_end);
                   2231:     }
                   2232:     return '';
1.38      ng       2233: }
1.36      ng       2234: 
1.44      ng       2235: #---- Save the score and award for each student, if changed
1.38      ng       2236: sub saveHandGrade {
1.324     albertel 2237:     my ($request,$symb,$stuname,$domain,$newflg,$submitter,$part) = @_;
1.262     banghart 2238:     my @v_flag;
1.104     albertel 2239:     my $usec = &Apache::lonnet::getsection($domain,$stuname,
1.257     albertel 2240: 					   $env{'request.course.id'});
1.104     albertel 2241:     if (!&canmodify($usec)) { return('not_allowed'); }
1.257     albertel 2242:     my %record     = &Apache::lonnet::restore($symb,$env{'request.course.id'},$domain,$stuname);
1.251     banghart 2243:     my @parts_graded;
1.77      ng       2244:     my %newrecord  = ();
                   2245:     my ($pts,$wgt) = ('','');
1.269     raeburn  2246:     my %aggregate = ();
                   2247:     my $aggregateflag = 0;
1.301     albertel 2248: 
                   2249:     my @parts = split(/:/,$env{'form.partlist'.$newflg});
                   2250:     foreach my $new_part (@parts) {
1.150     albertel 2251: 	#collaborator may vary for different parts
1.259     banghart 2252: 	if ($submitter && $new_part ne $part) { next; }
                   2253: 	my $dropMenu = $env{'form.GD_SEL'.$newflg.'_'.$new_part};
1.125     ng       2254: 	if ($dropMenu eq 'excused') {
1.259     banghart 2255: 	    if ($record{'resource.'.$new_part.'.solved'} ne 'excused') {
                   2256: 		$newrecord{'resource.'.$new_part.'.solved'} = 'excused';
                   2257: 		if (exists($record{'resource.'.$new_part.'.awarded'})) {
                   2258: 		    $newrecord{'resource.'.$new_part.'.awarded'} = '';
1.58      albertel 2259: 		}
1.259     banghart 2260: 	    $newrecord{'resource.'.$new_part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.58      albertel 2261: 	    }
1.125     ng       2262: 	} elsif ($dropMenu eq 'reset status'
1.259     banghart 2263: 		 && exists($record{'resource.'.$new_part.'.solved'})) { #don't bother if no old records -> no attempts
1.197     albertel 2264: 	    foreach my $key (keys (%record)) {
1.259     banghart 2265: 		if ($key=~/^resource\.\Q$new_part\E\./) { $newrecord{$key} = ''; }
1.197     albertel 2266: 	    }
1.259     banghart 2267: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2268: 		"$env{'user.name'}:$env{'user.domain'}";
1.270     albertel 2269:             my $totaltries = $record{'resource.'.$part.'.tries'};
                   2270: 
                   2271:             my %last_resets = &get_last_resets($symb,$env{'request.course.id'},
                   2272: 					       [$new_part]);
                   2273:             my $aggtries =$totaltries;
1.269     raeburn  2274:             if ($last_resets{$new_part}) {
1.270     albertel 2275:                 $aggtries = &get_num_tries(\%record,$last_resets{$new_part},
                   2276: 					   $new_part);
1.269     raeburn  2277:             }
1.270     albertel 2278: 
                   2279:             my $solvedstatus = $record{'resource.'.$new_part.'.solved'};
1.269     raeburn  2280:             if ($aggtries > 0) {
1.327     albertel 2281:                 &decrement_aggs($symb,$new_part,\%aggregate,$aggtries,$totaltries,$solvedstatus);
1.269     raeburn  2282:                 $aggregateflag = 1;
                   2283:             }
1.125     ng       2284: 	} elsif ($dropMenu eq '') {
1.259     banghart 2285: 	    $pts = ($env{'form.GD_BOX'.$newflg.'_'.$new_part} ne '' ? 
                   2286: 		    $env{'form.GD_BOX'.$newflg.'_'.$new_part} : 
                   2287: 		    $env{'form.RADVAL'.$newflg.'_'.$new_part});
                   2288: 	    if ($pts eq '' && $env{'form.GD_SEL'.$newflg.'_'.$new_part} eq '') {
1.153     albertel 2289: 		next;
                   2290: 	    }
1.259     banghart 2291: 	    $wgt = $env{'form.WGT'.$newflg.'_'.$new_part} eq '' ? 1 : 
                   2292: 		$env{'form.WGT'.$newflg.'_'.$new_part};
1.41      ng       2293: 	    my $partial= $pts/$wgt;
1.259     banghart 2294: 	    if ($partial eq $record{'resource.'.$new_part.'.awarded'}) {
1.153     albertel 2295: 		#do not update score for part if not changed.
                   2296: 		next;
1.251     banghart 2297: 	    } else {
1.259     banghart 2298: 	        push @parts_graded, $new_part;
1.153     albertel 2299: 	    }
1.259     banghart 2300: 	    if ($record{'resource.'.$new_part.'.awarded'} ne $partial) {
                   2301: 		$newrecord{'resource.'.$new_part.'.awarded'}  = $partial;
1.153     albertel 2302: 	    }
1.259     banghart 2303: 	    my $reckey = 'resource.'.$new_part.'.solved';
1.41      ng       2304: 	    if ($partial == 0) {
1.153     albertel 2305: 		if ($record{$reckey} ne 'incorrect_by_override') {
                   2306: 		    $newrecord{$reckey} = 'incorrect_by_override';
                   2307: 		}
1.41      ng       2308: 	    } else {
1.153     albertel 2309: 		if ($record{$reckey} ne 'correct_by_override') {
                   2310: 		    $newrecord{$reckey} = 'correct_by_override';
                   2311: 		}
                   2312: 	    }	    
                   2313: 	    if ($submitter && 
1.259     banghart 2314: 		($record{'resource.'.$new_part.'.submitted_by'} ne $submitter)) {
                   2315: 		$newrecord{'resource.'.$new_part.'.submitted_by'} = $submitter;
1.41      ng       2316: 	    }
1.259     banghart 2317: 	    $newrecord{'resource.'.$new_part.'.regrader'}=
1.257     albertel 2318: 		"$env{'user.name'}:$env{'user.domain'}";
1.41      ng       2319: 	}
1.324     albertel 2320: 	my ($partlist,$handgrade,$responseType) = &response_type($symb);
1.322     albertel 2321: 	foreach my $part_resp (sort(keys(%$handgrade))) {
1.321     banghart 2322: 	    my ($part_id, $resp_id) = split(/_/,$part_resp);
1.323     banghart 2323:             if (($env{'form.'.$newflg.'_'.$part_resp.'_returndoc1'}) && ($new_part == $part_id)) {
1.321     banghart 2324:                 # if multiple files are uploaded names will be 'returndoc2','returndoc3'
                   2325:                 my $file_counter = 1;
1.323     banghart 2326:                 while ($env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter}) {
                   2327:                     my $fname=$env{'form.'.$newflg.'_'.$part_resp.'_returndoc'.$file_counter.'.filename'};
1.321     banghart 2328:                     $newrecord{"resource.$new_part.$resp_id.handback"} = $env{'form.returndocorig'.$file_counter};
1.328     banghart 2329:                     # set the filename to match the submitted file name
                   2330:                     $env{'form.'.$newflg.'_'.$part_resp.'_returndoc1.filename'} = $env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter};
                   2331:                     my $result=&Apache::lonnet::userfileupload($newflg.'_'.$part_resp.'_returndoc'.$file_counter,'',
                   2332: 	        	 'portfolio',undef,undef,undef,$stuname,$domain);
                   2333:                    if ($result !~ m|^/uploaded/|) {
                   2334:                         $request->print('<font color="red"> An errror occured ('.$result.
                   2335: 	                    ') while trying to upload '.&display_file().'</font><br />');
                   2336: 	                # $request->print(&done('Back'));
                   2337: 	            }
1.321     banghart 2338:                     $request->print("<br />".$fname." will be the uploaded file name");
1.323     banghart 2339:                     $request->print("<font color=\"red\">Will upload document</font>".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.321     banghart 2340:                     $file_counter++;
                   2341:                 }
1.310     banghart 2342:             }
                   2343:         }
                   2344: 	
1.259     banghart 2345: 	# unless problem has been graded, set flag to version the submitted files
1.305     banghart 2346: 	unless ($record{'resource.'.$new_part.'.solved'} =~ /^correct_/  || 
                   2347: 	        $record{'resource.'.$new_part.'.solved'} eq 'incorrect_by_override' ||
                   2348: 	        $dropMenu eq 'reset status')
                   2349: 	   {
1.262     banghart 2350: 	    push (@v_flag,$new_part);
1.259     banghart 2351: 	}
1.41      ng       2352:     }
1.301     albertel 2353:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   2354:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   2355: 
1.44      ng       2356:     if (scalar(keys(%newrecord)) > 0) {
1.263     banghart 2357:         if (scalar(@v_flag)) {
                   2358:             &version_portfiles(\%record, \@parts_graded, $env{'request.course.id'}, $symb, $domain, $stuname, \@v_flag);
1.259     banghart 2359:         }
1.44      ng       2360: 	&Apache::lonnet::cstore(\%newrecord,$symb,
1.257     albertel 2361: 				$env{'request.course.id'},$domain,$stuname);
1.301     albertel 2362: 	
                   2363: 	my @ungraded_parts;
                   2364: 	foreach my $part (@parts) {
                   2365: 	    if ( !defined($record{'resource.'.$part.'.awarded'})
                   2366: 		 && !defined($newrecord{'resource.'.$part.'.awarded'}) ) {
                   2367: 		push(@ungraded_parts, $part);
                   2368: 	    }
                   2369: 	}
                   2370: 	if ( !@ungraded_parts ) {
                   2371: 	    &Apache::bridgetask::remove_from_queue('gradingqueue',$symb,$cdom,
                   2372: 						   $cnum,$domain,$stuname);
                   2373: 	}
1.41      ng       2374:     }
1.269     raeburn  2375:     if ($aggregateflag) {
                   2376:         &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 2377: 			      $cdom,$cnum);
1.269     raeburn  2378:     }
1.301     albertel 2379:     return ('',$pts,$wgt);
1.36      ng       2380: }
1.322     albertel 2381: 
1.313     banghart 2382: sub get_submitted_files {
                   2383:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2384:     my @files;
                   2385:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2386:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2387:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2388:     	    push(@files,$file_url.$file);
                   2389:         }
                   2390:     }
                   2391:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2392:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2393:     }
                   2394:     return (\@files);
                   2395: }
1.322     albertel 2396: 
1.269     raeburn  2397: # ----------- Provides number of tries since last reset.
                   2398: sub get_num_tries {
                   2399:     my ($record,$last_reset,$part) = @_;
                   2400:     my $timestamp = '';
                   2401:     my $num_tries = 0;
                   2402:     if ($$record{'version'}) {
                   2403:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2404:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2405:                 $timestamp = $$record{$version.':timestamp'};
                   2406:                 if ($timestamp > $last_reset) {
                   2407:                     $num_tries ++;
                   2408:                 } else {
                   2409:                     last;
                   2410:                 }
                   2411:             }
                   2412:         }
                   2413:     }
                   2414:     return $num_tries;
                   2415: }
                   2416: 
                   2417: # ----------- Determine decrements required in aggregate totals 
                   2418: sub decrement_aggs {
                   2419:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2420:     my %decrement = (
                   2421:                         attempts => 0,
                   2422:                         users => 0,
                   2423:                         correct => 0
                   2424:                     );
                   2425:     $decrement{'attempts'} = $aggtries;
                   2426:     if ($solvedstatus =~ /^correct/) {
                   2427:         $decrement{'correct'} = 1;
                   2428:     }
                   2429:     if ($aggtries == $totaltries) {
                   2430:         $decrement{'users'} = 1;
                   2431:     }
                   2432:     foreach my $type (keys (%decrement)) {
                   2433:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2434:     }
                   2435:     return;
                   2436: }
                   2437: 
                   2438: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2439: sub get_last_resets {
1.270     albertel 2440:     my ($symb,$courseid,$partids) =@_;
                   2441:     my %last_resets;
1.269     raeburn  2442:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2443:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2444:     my @keys;
                   2445:     foreach my $part (@{$partids}) {
                   2446: 	push(@keys,"$symb\0$part\0resettime");
                   2447:     }
                   2448:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2449: 				     $cdom,$cname);
                   2450:     foreach my $part (@{$partids}) {
                   2451: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2452:     }
1.270     albertel 2453:     return %last_resets;
1.269     raeburn  2454: }
                   2455: 
1.251     banghart 2456: # ----------- Handles creating versions for portfolio files as answers
                   2457: sub version_portfiles {
1.306     banghart 2458:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2459:     my $version_parts = join('|',@$v_flag);
1.255     banghart 2460:     my $parts = join('|', @$parts_graded);
1.252     banghart 2461:     my $portfolio_root = &Apache::loncommon::propath($domain,
1.306     banghart 2462: 						 $stu_name).
1.252     banghart 2463: 						'/userfiles/portfolio';
1.277     albertel 2464:     foreach my $key (keys(%$record)) {
1.259     banghart 2465:         my $new_portfiles;
1.263     banghart 2466:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.259     banghart 2467:             my @v_portfiles;
1.255     banghart 2468:             my @portfiles = split(/,/,$$record{$key});
1.252     banghart 2469:             foreach my $file (@portfiles) {
1.306     banghart 2470:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2471:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
1.252     banghart 2472:                 my $version = 0;
1.304     albertel 2473: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2474: 		    &file_name_version_ext($answer_file);
1.306     banghart 2475:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.307     banghart 2476:                 $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2477:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2478:                 if ($new_answer ne 'problem getting file') {
1.304     albertel 2479:                     push(@v_portfiles, $directory.$new_answer);
1.306     banghart 2480:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
                   2481:                         ['/portfolio'.$directory.$new_answer],
                   2482:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2483:                 }
1.306     banghart 2484:                 
1.252     banghart 2485:             }
1.261     albertel 2486:             $$record{$key} = join(',',@v_portfiles);
1.251     banghart 2487:         }
                   2488:     } 
1.259     banghart 2489:     return 'ok';   
1.305     banghart 2490: }
                   2491: 
1.307     banghart 2492: sub get_next_version {
                   2493:     my ($answer_name, $answer_ext, $dir_list);
                   2494:     my $version;
                   2495:     foreach my $row (@$dir_list) {
                   2496:         my ($file) = split(/\&/,$row,2);
                   2497:         my ($file_name,$file_version,$file_ext) =
                   2498: 	    &file_name_version_ext($file);
                   2499:         if (($file_name eq $answer_name) && 
                   2500: 	    ($file_ext eq $answer_ext)) {
                   2501:                 # gets here if filename and extension match, regardless of version
                   2502:                 if ($file_version ne '') {
                   2503:                 # a versioned file is found  so save it for later
                   2504:                 if ($file_version > $version) {
                   2505: 		    $version = $file_version;
                   2506: 	        }
                   2507:             }
                   2508:         }
                   2509:     } 
                   2510:     $version ++;
                   2511:     return($version);
                   2512: }
                   2513: 
1.305     banghart 2514: sub version_selected_portfile {
1.306     banghart 2515:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2516:     my ($answer_name,$answer_ver,$answer_ext) =
                   2517:         &file_name_version_ext($file_name);
                   2518:     my $new_answer;
                   2519:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2520:     if($env{'form.copy'} eq '-1') {
                   2521:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2522:         $new_answer = 'problem getting file';
                   2523:     } else {
                   2524:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2525:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2526:                             $stu_name,$domain,'copy',
                   2527: 		        '/portfolio'.$directory.$new_answer);
                   2528:     }    
                   2529:     return ($new_answer);
1.251     banghart 2530: }
                   2531: 
1.304     albertel 2532: sub file_name_version_ext {
                   2533:     my ($file)=@_;
                   2534:     my @file_parts = split(/\./, $file);
                   2535:     my ($name,$version,$ext);
                   2536:     if (@file_parts > 1) {
                   2537: 	$ext=pop(@file_parts);
                   2538: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2539: 	    $version=pop(@file_parts);
                   2540: 	}
                   2541: 	$name=join('.',@file_parts);
                   2542:     } else {
                   2543: 	$name=join('.',@file_parts);
                   2544:     }
                   2545:     return($name,$version,$ext);
                   2546: }
                   2547: 
1.44      ng       2548: #--------------------------------------------------------------------------------------
                   2549: #
                   2550: #-------------------------- Next few routines handles grading by section or whole class
                   2551: #
                   2552: #--- Javascript to handle grading by section or whole class
1.42      ng       2553: sub viewgrades_js {
                   2554:     my ($request) = shift;
                   2555: 
1.41      ng       2556:     $request->print(<<VIEWJAVASCRIPT);
                   2557: <script type="text/javascript" language="javascript">
1.45      ng       2558:    function writePoint(partid,weight,point) {
1.125     ng       2559: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2560: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2561: 	if (point == "textval") {
1.125     ng       2562: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2563: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2564: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2565: 		var resetbox = false;
                   2566: 		for (var i=0; i<radioButton.length; i++) {
                   2567: 		    if (radioButton[i].checked) {
                   2568: 			textbox.value = i;
                   2569: 			resetbox = true;
                   2570: 		    }
                   2571: 		}
                   2572: 		if (!resetbox) {
                   2573: 		    textbox.value = "";
                   2574: 		}
                   2575: 		return;
                   2576: 	    }
1.109     matthew  2577: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2578: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2579: 				   ") greater than the weight for the part. Accept?");
                   2580: 		if (resp == false) {
                   2581: 		    textbox.value = "";
                   2582: 		    return;
                   2583: 		}
                   2584: 	    }
1.42      ng       2585: 	    for (var i=0; i<radioButton.length; i++) {
                   2586: 		radioButton[i].checked=false;
1.109     matthew  2587: 		if (parseFloat(point) == i) {
1.42      ng       2588: 		    radioButton[i].checked=true;
                   2589: 		}
                   2590: 	    }
1.41      ng       2591: 
1.42      ng       2592: 	} else {
1.125     ng       2593: 	    textbox.value = parseFloat(point);
1.42      ng       2594: 	}
1.41      ng       2595: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2596: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2597: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2598: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2599: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2600: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2601: 	    if (saveval != "correct") {
                   2602: 		scorename.value = point;
1.43      ng       2603: 		if (selname[0].selected != true) {
                   2604: 		    selname[0].selected = true;
                   2605: 		}
1.42      ng       2606: 	    }
                   2607: 	}
1.125     ng       2608: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2609:     }
                   2610: 
                   2611:     function writeRadText(partid,weight) {
1.125     ng       2612: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2613: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2614:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2615: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2616: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2617: 	    for (var i=0; i<radioButton.length; i++) {
                   2618: 		radioButton[i].checked=false;
                   2619: 
                   2620: 	    }
                   2621: 	    textbox.value = "";
                   2622: 
                   2623: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2624: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2625: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2626: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2627: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2628: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2629: 		if ((saveval != "correct") || override) {
1.42      ng       2630: 		    scorename.value = "";
1.125     ng       2631: 		    if (selval[1].selected) {
                   2632: 			selname[1].selected = true;
                   2633: 		    } else {
                   2634: 			selname[2].selected = true;
                   2635: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2636: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2637: 		    }
1.42      ng       2638: 		}
                   2639: 	    }
1.43      ng       2640: 	} else {
                   2641: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2642: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2643: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2644: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2645: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2646: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2647: 		if ((saveval != "correct") || override) {
1.125     ng       2648: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2649: 		    selname[0].selected = true;
                   2650: 		}
                   2651: 	    }
                   2652: 	}	    
1.42      ng       2653:     }
                   2654: 
                   2655:     function changeSelect(partid,user) {
1.125     ng       2656: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2657: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2658: 	var point  = textbox.value;
1.125     ng       2659: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2660: 
1.109     matthew  2661: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2662: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2663: 	    textbox.value = "";
                   2664: 	    return;
                   2665: 	}
1.109     matthew  2666: 	if (parseFloat(point) > parseFloat(weight)) {
                   2667: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2668: 			       ") greater than the weight of the part. Accept?");
                   2669: 	    if (resp == false) {
                   2670: 		textbox.value = "";
                   2671: 		return;
                   2672: 	    }
                   2673: 	}
1.42      ng       2674: 	selval[0].selected = true;
                   2675:     }
                   2676: 
                   2677:     function changeOneScore(partid,user) {
1.125     ng       2678: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2679: 	if (selval[1].selected || selval[2].selected) {
                   2680: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2681: 	    if (selval[2].selected) {
                   2682: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2683: 	    }
1.269     raeburn  2684:         }
1.42      ng       2685:     }
                   2686: 
                   2687:     function resetEntry(numpart) {
                   2688: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2689: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2690: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2691: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2692: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2693: 	    for (var i=0; i<radioButton.length; i++) {
                   2694: 		radioButton[i].checked=false;
                   2695: 
                   2696: 	    }
                   2697: 	    textbox.value = "";
                   2698: 	    selval[0].selected = true;
                   2699: 
                   2700: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2701: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2702: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2703: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2704: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2705: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2706: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2707: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2708: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2709: 		if (saveselval == "excused") {
1.43      ng       2710: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2711: 		} else {
1.43      ng       2712: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2713: 		}
                   2714: 	    }
1.41      ng       2715: 	}
1.42      ng       2716:     }
                   2717: 
1.41      ng       2718: </script>
                   2719: VIEWJAVASCRIPT
1.42      ng       2720: }
                   2721: 
1.44      ng       2722: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2723: sub viewgrades {
                   2724:     my ($request) = shift;
                   2725:     &viewgrades_js($request);
1.41      ng       2726: 
1.324     albertel 2727:     my ($symb) = &get_symb($request);
1.168     albertel 2728:     #need to make sure we have the correct data for later EXT calls, 
                   2729:     #thus invalidate the cache
                   2730:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2731:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2732:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2733:     &Apache::lonnet::clear_EXT_cache_status();
                   2734: 
1.167     sakharuk 2735:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
1.257     albertel 2736:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
1.41      ng       2737: 
                   2738:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2739:     $result.=&jscriptNform($symb);
1.41      ng       2740: 
1.44      ng       2741:     #beginning of class grading form
1.41      ng       2742:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2743: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2744: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2745: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2746: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2747: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2748: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2749: 
1.126     ng       2750:     my $sectionClass;
1.257     albertel 2751:     if ($env{'form.section'} eq 'all') {
1.126     ng       2752: 	$sectionClass='Class </h3>';
1.257     albertel 2753:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2754: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2755:     } else {
1.257     albertel 2756: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2757:     }
1.126     ng       2758:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2759:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2760: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2761:     #radio buttons/text box for assigning points for a section or class.
                   2762:     #handles different parts of a problem
1.324     albertel 2763:     my ($partlist,$handgrade) = &response_type($symb);
1.42      ng       2764:     my %weight = ();
                   2765:     my $ctsparts = 0;
1.41      ng       2766:     $result.='<table border="0">';
1.45      ng       2767:     my %seen = ();
1.42      ng       2768:     for (sort keys(%$handgrade)) {
1.54      albertel 2769: 	my ($partid,$respid) = split (/_/,$_,2);
1.45      ng       2770: 	next if $seen{$partid};
                   2771: 	$seen{$partid}++;
1.147     albertel 2772: 	my $handgrade=$$handgrade{$_};
1.42      ng       2773: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2774: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   2775: 
1.44      ng       2776: 	$result.='<input type="hidden" name="partid_'.
                   2777: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   2778: 	$result.='<input type="hidden" name="weight_'.
                   2779: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 2780: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 2781: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       2782: 	$result.='<table border="0"><tr>';  
1.41      ng       2783: 	my $ctr = 0;
1.42      ng       2784: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 2785: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 2786: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 2787: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       2788: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   2789: 	    $ctr++;
                   2790: 	}
                   2791: 	$result.='</tr></table>';
1.44      ng       2792: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 2793: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   2794: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       2795: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   2796: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 2797: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 2798: 		$weight{$partid}.')"> '.
1.42      ng       2799: 	    '<option selected="on"> </option>'.
1.125     ng       2800: 	    '<option>excused</option>'.
1.265     www      2801: 	    '<option>reset status</option></select></td>'.
1.266     albertel 2802:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       2803: 	$ctsparts++;
1.41      ng       2804:     }
1.52      albertel 2805:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   2806: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.42      ng       2807:     $result.='<input type="button" value="Reset" '.
1.111     ng       2808: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       2809: 
1.44      ng       2810:     #table listing all the students in a section/class
                   2811:     #header of table
1.126     ng       2812:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       2813:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       2814: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       2815: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 2816:     my (@parts) = sort(&getpartlist($symb));
                   2817:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  2818:     my @partids = ();
1.41      ng       2819:     foreach my $part (@parts) {
                   2820: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       2821: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       2822: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 2823: 	my ($partid) = &split_part_type($part);
1.269     raeburn  2824:         push(@partids, $partid);
1.324     albertel 2825: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       2826: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 2827: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   2828: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       2829: 	    next;
1.207     albertel 2830: 	} else {
                   2831: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       2832: 	}
1.53      albertel 2833: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 2834: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       2835:     }
                   2836:     $result.='</tr>';
1.44      ng       2837: 
1.270     albertel 2838:     my %last_resets = 
                   2839: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  2840: 
1.41      ng       2841:     #get info for each student
1.44      ng       2842:     #list all the students - with points and grade status
1.257     albertel 2843:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       2844:     my $ctr = 0;
1.294     albertel 2845:     foreach (sort 
                   2846: 	     {
                   2847: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2848: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2849: 		 }
                   2850: 		 return $a cmp $b;
                   2851: 	     } (keys(%$fullname))) {
1.126     ng       2852: 	$ctr++;
1.324     albertel 2853: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  2854: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       2855:     }
                   2856:     $result.='</table></td></tr></table>';
                   2857:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       2858:     $result.='<input type="button" value="Save" '.
1.45      ng       2859: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 2860:     if (scalar(%$fullname) eq 0) {
                   2861: 	my $colspan=3+scalar(@parts);
1.257     albertel 2862: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
                   2863: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
1.96      albertel 2864:     }
1.324     albertel 2865:     $result.=&show_grading_menu_form($symb);
1.41      ng       2866:     return $result;
                   2867: }
                   2868: 
1.44      ng       2869: #--- call by previous routine to display each student
1.41      ng       2870: sub viewstudentgrade {
1.324     albertel 2871:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       2872:     my ($uname,$udom) = split(/:/,$student);
                   2873:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  2874:     my %aggregates = (); 
1.233     albertel 2875:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   2876: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   2877: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       2878: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       2879: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.257     albertel 2880: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
1.281     albertel 2881:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 2882:     foreach my $apart (@$parts) {
                   2883: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       2884: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 2885:         $result.='<td align="center">';
1.269     raeburn  2886:         my ($aggtries,$totaltries);
                   2887:         unless (exists($aggregates{$part})) {
1.270     albertel 2888: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   2889: 
                   2890: 	    $aggtries = $totaltries;
1.269     raeburn  2891:             if ($$last_resets{$part}) {  
1.270     albertel 2892:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   2893: 					   $part);
                   2894:             }
1.269     raeburn  2895:             $result.='<input type="hidden" name="'.
                   2896:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   2897:             $result.='<input type="hidden" name="'.
                   2898:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   2899:             $aggregates{$part} = 1;
                   2900:         }
1.41      ng       2901: 	if ($type eq 'awarded') {
1.320     albertel 2902: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       2903: 	    $result.='<input type="hidden" name="'.
1.89      albertel 2904: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 2905: 	    $result.='<input type="text" name="'.
1.89      albertel 2906: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   2907: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       2908: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       2909: 	} elsif ($type eq 'solved') {
                   2910: 	    my ($status,$foo)=split(/_/,$score,2);
                   2911: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 2912: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 2913: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 2914: 	    $result.='&nbsp;<select name="'.
1.89      albertel 2915: 		'GD_'.$student.'_'.$part.'_solved" '.
                   2916: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       2917: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   2918: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   2919: 	    $result.='<option>reset status</option>';
1.126     ng       2920: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       2921: 	} else {
                   2922: 	    $result.='<input type="hidden" name="'.
                   2923: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   2924: 		    "\n";
1.233     albertel 2925: 	    $result.='<input type="text" name="'.
1.122     ng       2926: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   2927: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       2928: 	}
                   2929:     }
                   2930:     $result.='</tr>';
                   2931:     return $result;
1.38      ng       2932: }
                   2933: 
1.44      ng       2934: #--- change scores for all the students in a section/class
                   2935: #    record does not get update if unchanged
1.38      ng       2936: sub editgrades {
1.41      ng       2937:     my ($request) = @_;
                   2938: 
1.324     albertel 2939:     my $symb=&get_symb($request);
1.45      ng       2940:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
1.257     albertel 2941:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
                   2942:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
1.126     ng       2943: 
1.44      ng       2944:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       2945:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   2946: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   2947: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       2948: 
                   2949:     my %scoreptr = (
                   2950: 		    'correct'  =>'correct_by_override',
                   2951: 		    'incorrect'=>'incorrect_by_override',
                   2952: 		    'excused'  =>'excused',
                   2953: 		    'ungraded' =>'ungraded_attempted',
                   2954: 		    'nothing'  => '',
                   2955: 		    );
1.257     albertel 2956:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       2957: 
1.44      ng       2958:     my (@partid);
                   2959:     my %weight = ();
1.54      albertel 2960:     my %columns = ();
1.44      ng       2961:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 2962: 
1.324     albertel 2963:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 2964:     my $header;
1.257     albertel 2965:     while ($ctr < $env{'form.totalparts'}) {
                   2966: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       2967: 	push @partid,$partid;
1.257     albertel 2968: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       2969: 	$ctr++;
1.54      albertel 2970:     }
1.324     albertel 2971:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 2972:     foreach my $partid (@partid) {
                   2973: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   2974: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   2975: 	$columns{$partid}=2;
                   2976: 	foreach my $stores (@parts) {
                   2977: 	    my ($part,$type) = &split_part_type($stores);
                   2978: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   2979: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   2980: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   2981: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       2982: 	    $display =~ s/Number of Attempts/Tries/;
                   2983: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   2984: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 2985: 	    $columns{$partid}+=2;
                   2986: 	}
                   2987:     }
                   2988:     foreach my $partid (@partid) {
1.324     albertel 2989: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 2990: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 2991: 	    '" align="center"><b>Part:</b> '.$display_part.
                   2992: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 2993: 
1.44      ng       2994:     }
                   2995:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 2996:     $result .= $header;
1.44      ng       2997:     $result .= '</tr>'."\n";
1.93      albertel 2998:     my $noupdate;
1.126     ng       2999:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3000:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3001: 	my $line;
1.257     albertel 3002: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3003: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3004: 	my %newrecord;
                   3005: 	my $updateflag = 0;
1.281     albertel 3006: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3007: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3008: 	if (!&canmodify($usec)) {
1.126     ng       3009: 	    my $numcols=scalar(@partid)*4+2;
1.105     albertel 3010: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
                   3011: 	    next;
                   3012: 	}
1.269     raeburn  3013:         my %aggregate = ();
                   3014:         my $aggregateflag = 0;
1.281     albertel 3015: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3016: 	foreach (@partid) {
1.257     albertel 3017: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3018: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3019: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3020: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3021: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3022: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3023: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3024: 	    my $score;
                   3025: 	    if ($partial eq '') {
1.257     albertel 3026: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3027: 	    } elsif ($partial > 0) {
                   3028: 		$score = 'correct_by_override';
                   3029: 	    } elsif ($partial == 0) {
                   3030: 		$score = 'incorrect_by_override';
                   3031: 	    }
1.257     albertel 3032: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3033: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3034: 
1.292     albertel 3035: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3036: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3037: 	    if ($dropMenu eq 'reset status' &&
                   3038: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3039: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3040: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3041: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3042: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3043: 		$updateflag = 1;
1.269     raeburn  3044:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3045:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3046:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3047:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3048:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3049:                     $aggregateflag = 1;
                   3050:                 }
1.139     albertel 3051: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3052: 		$updateflag = 1;
                   3053: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3054: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3055: 		$rec_update++;
1.125     ng       3056: 	    }
                   3057: 
1.93      albertel 3058: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3059: 		'<td align="center">'.$awarded.
                   3060: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3061: 
1.54      albertel 3062: 
                   3063: 	    my $partid=$_;
                   3064: 	    foreach my $stores (@parts) {
                   3065: 		my ($part,$type) = &split_part_type($stores);
                   3066: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3067: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3068: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3069: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3070: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3071: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3072: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3073: 		    $updateflag=1;
                   3074: 		}
1.93      albertel 3075: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3076: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3077: 	    }
1.44      ng       3078: 	}
1.93      albertel 3079: 	$line.='</tr>'."\n";
1.301     albertel 3080: 
                   3081: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3082: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3083: 
1.44      ng       3084: 	if ($updateflag) {
                   3085: 	    $count++;
1.257     albertel 3086: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3087: 				    $udom,$uname);
1.301     albertel 3088: 
                   3089: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3090: 					      $cnum,$udom,$uname)) {
                   3091: 		# need to figure out if should be in queue.
                   3092: 		my %record =  
                   3093: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3094: 					     $udom,$uname);
                   3095: 		my $all_graded = 1;
                   3096: 		my $none_graded = 1;
                   3097: 		foreach my $part (@parts) {
                   3098: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3099: 			$all_graded = 0;
                   3100: 		    } else {
                   3101: 			$none_graded = 0;
                   3102: 		    }
                   3103: 		}
                   3104: 
                   3105: 		if ($all_graded || $none_graded) {
                   3106: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3107: 							   $symb,$cdom,$cnum,
                   3108: 							   $udom,$uname);
                   3109: 		}
                   3110: 	    }
                   3111: 
1.126     ng       3112: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3113: 	    $updateCtr++;
1.93      albertel 3114: 	} else {
1.126     ng       3115: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3116: 	    $noupdateCtr++;
1.44      ng       3117: 	}
1.269     raeburn  3118:         if ($aggregateflag) {
                   3119:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3120: 				  $cdom,$cnum);
1.269     raeburn  3121:         }
1.93      albertel 3122:     }
                   3123:     if ($noupdate) {
1.126     ng       3124: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3125: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3126: 	$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       3127:     }
1.72      ng       3128:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3129: 	&show_grading_menu_form ($symb);
1.125     ng       3130:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3131: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3132: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3133:     return $title.$msg.$result;
1.5       albertel 3134: }
1.54      albertel 3135: 
                   3136: sub split_part_type {
                   3137:     my ($partstr) = @_;
                   3138:     my ($temp,@allparts)=split(/_/,$partstr);
                   3139:     my $type=pop(@allparts);
                   3140:     my $part=join('.',@allparts);
                   3141:     return ($part,$type);
                   3142: }
                   3143: 
1.44      ng       3144: #------------- end of section for handling grading by section/class ---------
                   3145: #
                   3146: #----------------------------------------------------------------------------
                   3147: 
1.5       albertel 3148: 
1.44      ng       3149: #----------------------------------------------------------------------------
                   3150: #
                   3151: #-------------------------- Next few routines handles grading by csv upload
                   3152: #
                   3153: #--- Javascript to handle csv upload
1.27      albertel 3154: sub csvupload_javascript_reverse_associate {
1.246     albertel 3155:     my $error1=&mt('You need to specify the username or ID');
                   3156:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3157:   return(<<ENDPICK);
                   3158:   function verify(vf) {
                   3159:     var foundsomething=0;
                   3160:     var founduname=0;
1.243     albertel 3161:     var foundID=0;
1.27      albertel 3162:     for (i=0;i<=vf.nfields.value;i++) {
                   3163:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3164:       if (i==0 && tw!=0) { foundID=1; }
                   3165:       if (i==1 && tw!=0) { founduname=1; }
                   3166:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3167:     }
1.246     albertel 3168:     if (founduname==0 && foundID==0) {
                   3169: 	alert('$error1');
                   3170: 	return;
1.27      albertel 3171:     }
                   3172:     if (foundsomething==0) {
1.246     albertel 3173: 	alert('$error2');
                   3174: 	return;
1.27      albertel 3175:     }
                   3176:     vf.submit();
                   3177:   }
                   3178:   function flip(vf,tf) {
                   3179:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3180:     var i;
                   3181:     for (i=0;i<=vf.nfields.value;i++) {
                   3182:       //can not pick the same destination field for both name and domain
                   3183:       if (((i ==0)||(i ==1)) && 
                   3184:           ((tf==0)||(tf==1)) && 
                   3185:           (i!=tf) &&
                   3186:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3187:         eval('vf.f'+i+'.selectedIndex=0;')
                   3188:       }
                   3189:     }
                   3190:   }
                   3191: ENDPICK
                   3192: }
                   3193: 
                   3194: sub csvupload_javascript_forward_associate {
1.246     albertel 3195:     my $error1=&mt('You need to specify the username or ID');
                   3196:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3197:   return(<<ENDPICK);
                   3198:   function verify(vf) {
                   3199:     var foundsomething=0;
                   3200:     var founduname=0;
1.243     albertel 3201:     var foundID=0;
1.27      albertel 3202:     for (i=0;i<=vf.nfields.value;i++) {
                   3203:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3204:       if (tw==1) { foundID=1; }
                   3205:       if (tw==2) { founduname=1; }
                   3206:       if (tw>3) { foundsomething=1; }
1.27      albertel 3207:     }
1.246     albertel 3208:     if (founduname==0 && foundID==0) {
                   3209: 	alert('$error1');
                   3210: 	return;
1.27      albertel 3211:     }
                   3212:     if (foundsomething==0) {
1.246     albertel 3213: 	alert('$error2');
                   3214: 	return;
1.27      albertel 3215:     }
                   3216:     vf.submit();
                   3217:   }
                   3218:   function flip(vf,tf) {
                   3219:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3220:     var i;
                   3221:     //can not pick the same destination field twice
                   3222:     for (i=0;i<=vf.nfields.value;i++) {
                   3223:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3224:         eval('vf.f'+i+'.selectedIndex=0;')
                   3225:       }
                   3226:     }
                   3227:   }
                   3228: ENDPICK
                   3229: }
                   3230: 
1.26      albertel 3231: sub csvuploadmap_header {
1.324     albertel 3232:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3233:     my $javascript;
1.257     albertel 3234:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3235: 	$javascript=&csvupload_javascript_reverse_associate();
                   3236:     } else {
                   3237: 	$javascript=&csvupload_javascript_forward_associate();
                   3238:     }
1.45      ng       3239: 
1.324     albertel 3240:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3241:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3242:     my $ignore=&mt('Ignore First Line');
1.41      ng       3243:     $request->print(<<ENDPICK);
1.26      albertel 3244: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.45      ng       3245: <h3><font color="#339933">Uploading Class Grades</font></h3>
                   3246: $result
1.326     albertel 3247: <hr />
1.26      albertel 3248: <h3>Identify fields</h3>
                   3249: Total number of records found in file: $distotal <hr />
                   3250: Enter as many fields as you can. The system will inform you and bring you back
                   3251: to this page if the data selected is insufficient to run your class.<hr />
                   3252: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3253: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3254: <input type="hidden" name="associate"  value="" />
                   3255: <input type="hidden" name="phase"      value="three" />
                   3256: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3257: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3258: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3259: <input type="hidden" name="upfile_associate" 
1.257     albertel 3260:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3261: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3262: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3263: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3264: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3265: <hr />
                   3266: <script type="text/javascript" language="Javascript">
                   3267: $javascript
                   3268: </script>
                   3269: ENDPICK
1.118     ng       3270:     return '';
1.26      albertel 3271: 
                   3272: }
                   3273: 
                   3274: sub csvupload_fields {
1.324     albertel 3275:     my ($symb) = @_;
                   3276:     my (@parts) = &getpartlist($symb);
1.243     albertel 3277:     my @fields=(['ID','Student ID'],
                   3278: 		['username','Student Username'],
                   3279: 		['domain','Student Domain']);
1.324     albertel 3280:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3281:     foreach my $part (sort(@parts)) {
                   3282: 	my @datum;
                   3283: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3284: 	my $name=$part;
                   3285: 	if  (!$display) { $display = $name; }
                   3286: 	@datum=($name,$display);
1.244     albertel 3287: 	if ($name=~/^stores_(.*)_awarded/) {
                   3288: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3289: 	}
1.41      ng       3290: 	push(@fields,\@datum);
                   3291:     }
                   3292:     return (@fields);
1.26      albertel 3293: }
                   3294: 
                   3295: sub csvuploadmap_footer {
1.41      ng       3296:     my ($request,$i,$keyfields) =@_;
                   3297:     $request->print(<<ENDPICK);
1.26      albertel 3298: </table>
                   3299: <input type="hidden" name="nfields" value="$i" />
                   3300: <input type="hidden" name="keyfields" value="$keyfields" />
                   3301: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3302: </form>
                   3303: ENDPICK
                   3304: }
                   3305: 
1.283     albertel 3306: sub checkforfile_js {
1.86      ng       3307:     my $result =<<CSVFORMJS;
                   3308: <script type="text/javascript" language="javascript">
                   3309:     function checkUpload(formname) {
                   3310: 	if (formname.upfile.value == "") {
                   3311: 	    alert("Please use the browse button to select a file from your local directory.");
                   3312: 	    return false;
                   3313: 	}
                   3314: 	formname.submit();
                   3315:     }
                   3316:     </script>
                   3317: CSVFORMJS
1.283     albertel 3318:     return $result;
                   3319: }
                   3320: 
                   3321: sub upcsvScores_form {
                   3322:     my ($request) = shift;
1.324     albertel 3323:     my ($symb)=&get_symb($request);
1.283     albertel 3324:     if (!$symb) {return '';}
                   3325:     my $result=&checkforfile_js();
1.257     albertel 3326:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3327:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3328:     $result.=$table;
1.326     albertel 3329:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3330:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.118     ng       3331:     $result.='&nbsp;<b>Specify a file containing the class scores for current resource'.
1.86      ng       3332: 	'.</b></td></tr>'."\n";
                   3333:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
                   3334:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3335:     my $ignore=&mt('Ignore First Line');
1.86      ng       3336:     $result.=<<ENDUPFORM;
1.106     albertel 3337: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3338: <input type="hidden" name="symb" value="$symb" />
                   3339: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3340: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3341: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3342: $upfile_select
                   3343: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
1.283     albertel 3344: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3345: </form>
                   3346: ENDUPFORM
                   3347:     $result.='</td></tr></table>'."\n";
                   3348:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3349:     $result.=&show_grading_menu_form($symb);
1.86      ng       3350:     return $result;
                   3351: }
                   3352: 
                   3353: 
1.26      albertel 3354: sub csvuploadmap {
1.41      ng       3355:     my ($request)= @_;
1.324     albertel 3356:     my ($symb)=&get_symb($request);
1.41      ng       3357:     if (!$symb) {return '';}
1.72      ng       3358: 
1.41      ng       3359:     my $datatoken;
1.257     albertel 3360:     if (!$env{'form.datatoken'}) {
1.41      ng       3361: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3362:     } else {
1.257     albertel 3363: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3364: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3365:     }
1.41      ng       3366:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3367:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3368:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3369:     my ($i,$keyfields);
                   3370:     if (@records) {
1.324     albertel 3371: 	my @fields=&csvupload_fields($symb);
1.45      ng       3372: 
1.257     albertel 3373: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3374: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3375: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3376: 							  \@fields);
                   3377: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3378: 	    chop($keyfields);
                   3379: 	} else {
                   3380: 	    unshift(@fields,['none','']);
                   3381: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3382: 							    \@fields);
1.311     banghart 3383:             foreach my $rec (@records) {
                   3384:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3385:                 if (%temp) {
                   3386:                     $keyfields=join(',',sort(keys(%temp)));
                   3387:                     last;
                   3388:                 }
                   3389:             }
1.41      ng       3390: 	}
                   3391:     }
                   3392:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3393:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3394: 
1.41      ng       3395:     return '';
1.27      albertel 3396: }
                   3397: 
1.246     albertel 3398: sub csvuploadoptions {
1.41      ng       3399:     my ($request)= @_;
1.324     albertel 3400:     my ($symb)=&get_symb($request);
1.257     albertel 3401:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3402:     my $ignore=&mt('Ignore First Line');
                   3403:     $request->print(<<ENDPICK);
                   3404: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3405: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
                   3406: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3407: <!--
1.246     albertel 3408: <p>
                   3409: <label>
                   3410:    <input type="checkbox" name="show_full_results" />
                   3411:    Show a table of all changes
                   3412: </label>
                   3413: </p>
1.302     albertel 3414: -->
1.246     albertel 3415: <p>
                   3416: <label>
                   3417:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3418:    Overwrite any existing score
                   3419: </label>
                   3420: </p>
                   3421: ENDPICK
                   3422:     my %fields=&get_fields();
                   3423:     if (!defined($fields{'domain'})) {
1.257     albertel 3424: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3425: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3426:     }
1.257     albertel 3427:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3428: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3429: 	my $cleankey=$1;
                   3430: 	if ($cleankey eq 'command') { next; }
                   3431: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3432: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3433:     }
                   3434:     # FIXME do a check for any duplicated user ids...
                   3435:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3436:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3437: <hr /></form>'."\n");
1.324     albertel 3438:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3439:     return '';
                   3440: }
                   3441: 
                   3442: sub get_fields {
                   3443:     my %fields;
1.257     albertel 3444:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3445:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3446: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3447: 	    if ($env{'form.f'.$i} ne 'none') {
                   3448: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3449: 	    }
                   3450: 	} else {
1.257     albertel 3451: 	    if ($env{'form.f'.$i} ne 'none') {
                   3452: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3453: 	    }
                   3454: 	}
1.27      albertel 3455:     }
1.246     albertel 3456:     return %fields;
                   3457: }
                   3458: 
                   3459: sub csvuploadassign {
                   3460:     my ($request)= @_;
1.324     albertel 3461:     my ($symb)=&get_symb($request);
1.246     albertel 3462:     if (!$symb) {return '';}
                   3463:     &Apache::loncommon::load_tmp_file($request);
                   3464:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3465:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3466:     my %fields=&get_fields();
1.41      ng       3467:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3468:     my $courseid=$env{'request.course.id'};
1.97      albertel 3469:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3470:     my @notallowed;
1.41      ng       3471:     my @skipped;
                   3472:     my $countdone=0;
                   3473:     foreach my $grade (@gradedata) {
                   3474: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3475: 	my $domain;
                   3476: 	if ($entries{$fields{'domain'}}) {
                   3477: 	    $domain=$entries{$fields{'domain'}};
                   3478: 	} else {
1.257     albertel 3479: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3480: 	}
1.243     albertel 3481: 	$domain=~s/\s//g;
1.41      ng       3482: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3483: 	$username=~s/\s//g;
1.243     albertel 3484: 	if (!$username) {
                   3485: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3486: 	    $id=~s/\s//g;
1.243     albertel 3487: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3488: 	    $username=$ids{$id};
                   3489: 	}
1.41      ng       3490: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3491: 	    my $id=$entries{$fields{'ID'}};
                   3492: 	    $id=~s/\s//g;
                   3493: 	    if ($id) {
                   3494: 		push(@skipped,"$id:$domain");
                   3495: 	    } else {
                   3496: 		push(@skipped,"$username:$domain");
                   3497: 	    }
1.41      ng       3498: 	    next;
                   3499: 	}
1.108     albertel 3500: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3501: 	if (!&canmodify($usec)) {
                   3502: 	    push(@notallowed,"$username:$domain");
                   3503: 	    next;
                   3504: 	}
1.244     albertel 3505: 	my %points;
1.41      ng       3506: 	my %grades;
                   3507: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3508: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3509: 		$dest eq 'domain') { next; }
                   3510: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3511: 	    if ($dest=~/stores_(.*)_points/) {
                   3512: 		my $part=$1;
                   3513: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3514: 					      $symb,$domain,$username);
1.247     albertel 3515: 		$entries{$fields{$dest}}=~s/\s//g;
1.244     albertel 3516: 		my $pcr=$entries{$fields{$dest}} / $wgt;
                   3517: 		my $award='correct_by_override';
                   3518: 		$grades{"resource.$part.awarded"}=$pcr;
                   3519: 		$grades{"resource.$part.solved"}=$award;
                   3520: 		$points{$part}=1;
                   3521: 	    } else {
                   3522: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3523: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3524: 		my $store_key=$dest;
                   3525: 		$store_key=~s/^stores/resource/;
                   3526: 		$store_key=~s/_/\./g;
                   3527: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3528: 	    }
1.41      ng       3529: 	}
1.244     albertel 3530: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
1.257     albertel 3531: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3532: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3533: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3534: 					   $env{'request.course.id'},
                   3535: 					   $domain,$username);
                   3536: 	if ($result eq 'ok') {
                   3537: 	    $request->print('.');
                   3538: 	} else {
                   3539: 	    $request->print("<p>
                   3540:                               <font color='red'>
                   3541:                                  Failed to store student $username\@$domain.
                   3542:                                  Message when trying to store was ($result)
                   3543:                               </font>
                   3544:                              </p>" );
                   3545: 	}
1.41      ng       3546: 	$request->rflush();
                   3547: 	$countdone++;
                   3548:     }
                   3549:     $request->print("<br />Stored $countdone students\n");
                   3550:     if (@skipped) {
1.325     www      3551: 	$request->print('<p><font size="+1"><b>Skipped Students</b></font></p>');
1.106     albertel 3552: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3553:     }
                   3554:     if (@notallowed) {
                   3555: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
                   3556: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3557:     }
1.106     albertel 3558:     $request->print("<br />\n");
1.324     albertel 3559:     $request->print(&show_grading_menu_form($symb));
1.41      ng       3560:     return '';
1.26      albertel 3561: }
1.44      ng       3562: #------------- end of section for handling csv file upload ---------
                   3563: #
                   3564: #-------------------------------------------------------------------
                   3565: #
1.122     ng       3566: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3567: #
                   3568: #--- Select a page/sequence and a student to grade
1.68      ng       3569: sub pickStudentPage {
                   3570:     my ($request) = shift;
                   3571: 
                   3572:     $request->print(<<LISTJAVASCRIPT);
                   3573: <script type="text/javascript" language="javascript">
                   3574: 
                   3575: function checkPickOne(formname) {
1.76      ng       3576:     if (radioSelection(formname.student) == null) {
1.68      ng       3577: 	alert("Please select the student you wish to grade.");
                   3578: 	return;
                   3579:     }
1.125     ng       3580:     ptr = pullDownSelection(formname.selectpage);
                   3581:     formname.page.value = formname["page"+ptr].value;
                   3582:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3583:     formname.submit();
                   3584: }
                   3585: 
                   3586: </script>
                   3587: LISTJAVASCRIPT
1.118     ng       3588:     &commonJSfunctions($request);
1.324     albertel 3589:     my ($symb) = &get_symb($request);
1.257     albertel 3590:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3591:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3592:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3593: 
                   3594:     my $result='<h3><font color="#339933">&nbsp;'.
                   3595: 	'Manual Grading by Page or Sequence</font></h3>';
                   3596: 
1.80      ng       3597:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3598:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3599:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3600:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3601: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3602: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3603:     my $ctr=0;
1.68      ng       3604:     foreach (@$titles) {
                   3605: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3606: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3607: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3608: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3609: 	$ctr++;
1.68      ng       3610:     }
1.326     albertel 3611:     $result.= '</select>'."<br />\n";
1.70      ng       3612:     $ctr=0;
                   3613:     foreach (@$titles) {
                   3614: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3615: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3616: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3617: 	$ctr++;
                   3618:     }
1.72      ng       3619:     $result.='<input type="hidden" name="page" />'."\n".
                   3620: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3621: 
1.288     albertel 3622:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                   3623: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3624: 
1.71      ng       3625:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3626: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
                   3627: 	'<label><input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions</label>'."\n".
                   3628: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3629: 
1.68      ng       3630:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3631: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3632: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3633: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3634: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3635: 
1.80      ng       3636:     $result.='&nbsp;<input type="button" '.
1.126     ng       3637: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3638: 
1.68      ng       3639:     $request->print($result);
                   3640: 
1.326     albertel 3641:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3642: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3643: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3644: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3645: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3646: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3647: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3648:  
1.76      ng       3649:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3650:     my $ptr = 1;
1.294     albertel 3651:     foreach my $student (sort 
                   3652: 			 {
                   3653: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3654: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3655: 			     }
                   3656: 			     return $a cmp $b;
                   3657: 			 } (keys(%$fullname))) {
1.68      ng       3658: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3659: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3660: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3661: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3662: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3663: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3664: 	$ptr++;
                   3665:     }
1.126     ng       3666:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
1.68      ng       3667:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
1.126     ng       3668:     $studentTable.='<input type="button" '.
                   3669: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3670: 
1.324     albertel 3671:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3672:     $request->print($studentTable);
                   3673: 
                   3674:     return '';
                   3675: }
                   3676: 
                   3677: sub getSymbMap {
1.74      albertel 3678:     my ($request) = @_;
1.132     bowersj2 3679:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3680: 
                   3681:     my %symbx = ();
                   3682:     my @titles = ();
1.117     bowersj2 3683:     my $minder = 0;
                   3684: 
                   3685:     # Gather every sequence that has problems.
1.240     albertel 3686:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3687: 					       1,0,1);
1.117     bowersj2 3688:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3689: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.117     bowersj2 3690: 	    my $title = $minder.'.'.$sequence->compTitle();
                   3691: 	    push @titles, $title; # minder in case two titles are identical
                   3692: 	    $symbx{$title} = $sequence->symb();
                   3693: 	    $minder++;
1.241     albertel 3694: 	}
1.68      ng       3695:     }
                   3696:     return \@titles,\%symbx;
                   3697: }
                   3698: 
1.72      ng       3699: #
                   3700: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3701: sub displayPage {
                   3702:     my ($request) = shift;
                   3703: 
1.324     albertel 3704:     my ($symb) = &get_symb($request);
1.257     albertel 3705:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3706:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3707:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3708:     my $pageTitle = $env{'form.page'};
1.103     albertel 3709:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3710:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3711:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3712: 
                   3713:     #need to make sure we have the correct data for later EXT calls, 
                   3714:     #thus invalidate the cache
                   3715:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3716:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3717:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3718:     &Apache::lonnet::clear_EXT_cache_status();
                   3719: 
1.103     albertel 3720:     if (!&canview($usec)) {
1.257     albertel 3721: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
1.324     albertel 3722: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3723: 	return;
                   3724:     }
1.257     albertel 3725:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3726:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3727: 	'</h3>'."\n";
1.71      ng       3728:     &sub_page_js($request);
                   3729:     $request->print($result);
                   3730: 
1.132     bowersj2 3731:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3732:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3733:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3734:     if (!$map) {
                   3735: 	$request->print('<font color="red">Unable to view requested sequence. ('.$resUrl.')</font>');
1.324     albertel 3736: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3737: 	return; 
                   3738:     }
1.68      ng       3739:     my $iterator = $navmap->getIterator($map->map_start(),
                   3740: 					$map->map_finish());
                   3741: 
1.71      ng       3742:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3743: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3744: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3745: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3746: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3747: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       3748: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       3749: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3750: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3751: 
                   3752:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   3753: 	'/check.gif" height="16" border="0" />';
                   3754: 
1.118     ng       3755:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   3756: 	' symbol.'."\n".
1.71      ng       3757: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3758: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       3759: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 3760: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       3761: 
1.329   ! albertel 3762:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 3763:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       3764:     $iterator->next(); # skip the first BEGIN_MAP
                   3765:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 3766:     while ($depth > 0) {
1.68      ng       3767:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3768:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       3769: 
1.235     albertel 3770:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3771: 	    my $parts = $curRes->parts();
1.68      ng       3772:             my $title = $curRes->compTitle();
1.71      ng       3773: 	    my $symbx = $curRes->symb();
1.196     albertel 3774: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 3775: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       3776: 	    $studentTable.='<td valign="top">';
1.257     albertel 3777: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 3778: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   3779: 					     undef,'both');
1.71      ng       3780: 	    } else {
1.257     albertel 3781: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'});
1.80      ng       3782: 		$companswer =~ s|<form(.*?)>||g;
                   3783: 		$companswer =~ s|</form>||g;
1.71      ng       3784: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       3785: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 3786: #		    $request->print('match='.$1."<br />\n");
1.71      ng       3787: #		}
1.116     ng       3788: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 3789: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       3790: 	    }
                   3791: 
1.257     albertel 3792: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       3793: 
1.257     albertel 3794: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       3795: 		if ($record{'version'} eq '') {
                   3796: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
                   3797: 		} else {
1.116     ng       3798: 		    my %responseType = ();
                   3799: 		    foreach my $partid (@{$parts}) {
1.147     albertel 3800: 			my @responseIds =$curRes->responseIds($partid);
                   3801: 			my @responseType =$curRes->responseType($partid);
                   3802: 			my %responseIds;
                   3803: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   3804: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   3805: 			}
                   3806: 			$responseType{$partid} = \%responseIds;
1.116     ng       3807: 		    }
1.148     albertel 3808: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 3809: 
1.71      ng       3810: 		}
1.257     albertel 3811: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   3812: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       3813: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 3814: 									$env{'request.course.id'},
1.71      ng       3815: 									'','.submission');
                   3816:  
                   3817: 	    }
1.103     albertel 3818: 	    if (&canmodify($usec)) {
                   3819: 		foreach my $partid (@{$parts}) {
                   3820: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   3821: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   3822: 		    $question++;
                   3823: 		}
1.196     albertel 3824: 		$prob++;
1.71      ng       3825: 	    }
                   3826: 	    $studentTable.='</td></tr>';
1.68      ng       3827: 
1.103     albertel 3828: 	}
1.68      ng       3829:         $curRes = $iterator->next();
                   3830:     }
                   3831: 
1.71      ng       3832:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
1.125     ng       3833: 	'<input type="button" value="Save" '.
1.71      ng       3834: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
                   3835: 	'</form>'."\n";
1.324     albertel 3836:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       3837:     $request->print($studentTable);
                   3838: 
                   3839:     return '';
1.119     ng       3840: }
                   3841: 
                   3842: sub displaySubByDates {
1.148     albertel 3843:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 3844:     my $isCODE=0;
                   3845:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       3846:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   3847: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   3848: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 3849: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       3850: 	'<td><b>Submission</b></td>'.
                   3851: 	'<td><b>Status&nbsp;</b></td></tr>';
                   3852:     my ($version);
                   3853:     my %mark;
1.148     albertel 3854:     my %orders;
1.119     ng       3855:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 3856:     if (!exists($$record{'1:timestamp'})) {
                   3857: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
                   3858:     }
1.119     ng       3859:     for ($version=1;$version<=$$record{'version'};$version++) {
                   3860: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
                   3861: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 3862: 	if ($isCODE) {
                   3863: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   3864: 	}
1.119     ng       3865: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   3866: 	my @displaySub = ();
                   3867: 	foreach my $partid (@{$parts}) {
1.147     albertel 3868: 	    my @matchKey = sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys);
1.122     ng       3869: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 3870: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 3871: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 3872: 		if (exists($$record{$version.':'.$matchKey}) &&
                   3873: 		    $$record{$version.':'.$matchKey} ne '') {
1.147     albertel 3874: 		    my ($responseId)=($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/);
1.207     albertel 3875: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.147     albertel 3876: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
1.207     albertel 3877: 			$responseId.')</font>&nbsp;<b>';
1.147     albertel 3878: 		    if ($$record{"$version:resource.$partid.tries"} eq '') {
                   3879: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   3880: 		    } else {
                   3881: 			$displaySub[0].='Trial&nbsp;'.
                   3882: 			    $$record{"$version:resource.$partid.tries"};
                   3883: 		    }
                   3884: 		    my $responseType=$responseType->{$partid}->{$responseId};
1.148     albertel 3885: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   3886: 		    if (!exists($orders{$partid}->{$responseId})) {
                   3887: 			$orders{$partid}->{$responseId}=
                   3888: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   3889: 		    }
1.147     albertel 3890: 		    $displaySub[0].='</b>&nbsp; '.
1.148     albertel 3891: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:").'<br />';
1.147     albertel 3892: 		}
                   3893: 	    }
                   3894: 	    if (exists $$record{"$version:resource.$partid.award"}) {
1.207     albertel 3895: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.147     albertel 3896: 		    lc($$record{"$version:resource.$partid.award"}).' '.
                   3897: 		    $mark{$$record{"$version:resource.$partid.solved"}}.
                   3898: 		    '<br />';
                   3899: 	    }
                   3900: 	    if (exists $$record{"$version:resource.$partid.regrader"}) {
                   3901: 		$displaySub[2].=$$record{"$version:resource.$partid.regrader"}.
1.207     albertel 3902: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 3903: 	    }
                   3904: 	}
                   3905: 	# needed because old essay regrader has not parts info
                   3906: 	if (exists $$record{"$version:resource.regrader"}) {
                   3907: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   3908: 	}
                   3909: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   3910: 	if ($displaySub[2]) {
                   3911: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   3912: 	}
                   3913: 	$studentTable.='&nbsp;</td></tr>';
                   3914:     
1.119     ng       3915:     }
                   3916:     $studentTable.='</table></td></tr></table>';
                   3917:     return $studentTable;
1.71      ng       3918: }
                   3919: 
                   3920: sub updateGradeByPage {
                   3921:     my ($request) = shift;
                   3922: 
1.257     albertel 3923:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3924:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3925:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3926:     my $pageTitle = $env{'form.page'};
1.103     albertel 3927:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3928:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3929:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 3930:     if (!&canmodify($usec)) {
1.257     albertel 3931: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
1.324     albertel 3932: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 3933: 	return;
                   3934:     }
1.257     albertel 3935:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3936:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       3937: 	'</h3>'."\n";
1.70      ng       3938: 
1.68      ng       3939:     $request->print($result);
                   3940: 
1.132     bowersj2 3941:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3942:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       3943:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3944:     if (!$map) {
                   3945: 	$request->print('<font color="red">Unable to grade requested sequence. ('.$resUrl.')</font>');
1.324     albertel 3946: 	my ($symb)=&get_symb($request);
                   3947: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3948: 	return; 
                   3949:     }
1.71      ng       3950:     my $iterator = $navmap->getIterator($map->map_start(),
                   3951: 					$map->map_finish());
1.70      ng       3952: 
1.71      ng       3953:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       3954: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       3955: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       3956: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   3957: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   3958: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   3959: 
                   3960:     $iterator->next(); # skip the first BEGIN_MAP
                   3961:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 3962:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 3963:     while ($depth > 0) {
1.71      ng       3964:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3965:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       3966: 
                   3967:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3968: 	    my $parts = $curRes->parts();
1.71      ng       3969:             my $title = $curRes->compTitle();
                   3970: 	    my $symbx = $curRes->symb();
1.196     albertel 3971: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 3972: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       3973: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   3974: 
                   3975: 	    my %newrecord=();
                   3976: 	    my @displayPts=();
1.269     raeburn  3977:             my %aggregate = ();
                   3978:             my $aggregateflag = 0;
1.71      ng       3979: 	    foreach my $partid (@{$parts}) {
1.257     albertel 3980: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   3981: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       3982: 
1.257     albertel 3983: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   3984: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       3985: 		my $partial = $newpts/$wgt;
                   3986: 		my $score;
                   3987: 		if ($partial > 0) {
                   3988: 		    $score = 'correct_by_override';
1.125     ng       3989: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       3990: 		    $score = 'incorrect_by_override';
                   3991: 		}
1.257     albertel 3992: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       3993: 		if ($dropMenu eq 'excused') {
1.71      ng       3994: 		    $partial = '';
                   3995: 		    $score = 'excused';
1.125     ng       3996: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 3997: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       3998: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   3999: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4000: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4001: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4002: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4003: 		    $changeflag++;
                   4004: 		    $newpts = '';
1.269     raeburn  4005:                     
                   4006:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4007:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4008:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4009:                     if ($aggtries > 0) {
                   4010:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4011:                         $aggregateflag = 1;
                   4012:                     }
1.71      ng       4013: 		}
1.324     albertel 4014: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4015: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4016: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4017: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4018: 		    '&nbsp;<br />';
1.207     albertel 4019: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4020: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4021: 		    '&nbsp;<br />';
1.71      ng       4022: 
                   4023: 		$question++;
1.125     ng       4024: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
                   4025: 
1.71      ng       4026: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4027: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4028: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4029: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4030: 
                   4031: 		$changeflag++;
                   4032: 	    }
                   4033: 	    if (scalar(keys(%newrecord)) > 0) {
1.257     albertel 4034: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4035: 					$udom,$uname);
                   4036: 	    }
1.269     raeburn  4037:             if ($aggregateflag) {
                   4038:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4039:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4040:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4041:             }
1.125     ng       4042: 
1.71      ng       4043: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4044: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4045: 		'</tr>';
1.68      ng       4046: 
1.196     albertel 4047: 	    $prob++;
1.68      ng       4048: 	}
1.71      ng       4049:         $curRes = $iterator->next();
1.68      ng       4050:     }
1.98      albertel 4051: 
1.71      ng       4052:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4053:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4054:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4055: 		  'The scores were changed for '.
                   4056: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4057:     $request->print($grademsg.$studentTable);
1.68      ng       4058: 
1.70      ng       4059:     return '';
                   4060: }
                   4061: 
1.72      ng       4062: #-------- end of section for handling grading by page/sequence ---------
                   4063: #
                   4064: #-------------------------------------------------------------------
                   4065: 
1.75      albertel 4066: #--------------------Scantron Grading-----------------------------------
                   4067: #
                   4068: #------ start of section for handling grading by page/sequence ---------
                   4069: 
1.81      albertel 4070: sub defaultFormData {
1.324     albertel 4071:     my ($symb)=@_;
1.81      albertel 4072:     return '
                   4073:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4074:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4075:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4076: }
                   4077: 
1.75      albertel 4078: sub getSequenceDropDown {
                   4079:     my ($request,$symb)=@_;
                   4080:     my $result='<select name="selectpage">'."\n";
                   4081:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4082:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4083:     my $ctr=0;
                   4084:     foreach (@$titles) {
                   4085: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4086: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   4087: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   4088: 	    '>'.$showtitle.'</option>'."\n";
                   4089: 	$ctr++;
                   4090:     }
                   4091:     $result.= '</select>';
                   4092:     return $result;
                   4093: }
                   4094: 
1.202     albertel 4095: sub scantron_filenames {
1.257     albertel 4096:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4097:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4098:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.162     albertel 4099: 				    &Apache::loncommon::propath($cdom,$cname));
1.202     albertel 4100:     my @possiblenames;
1.201     albertel 4101:     foreach my $filename (sort(@files)) {
1.157     albertel 4102: 	($filename)=split(/&/,$filename);
                   4103: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4104: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4105: 	push(@possiblenames,$filename);
                   4106:     }
                   4107:     return @possiblenames;
                   4108: }
                   4109: 
                   4110: sub scantron_uploads {
1.209     ng       4111:     my ($file2grade) = @_;
1.202     albertel 4112:     my $result=	'<select name="scantron_selectfile">';
                   4113:     $result.="<option></option>";
                   4114:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       4115: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 4116:     }
                   4117:     $result.="</select>";
                   4118:     return $result;
                   4119: }
                   4120: 
1.82      albertel 4121: sub scantron_scantab {
                   4122:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4123:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4124:     $result.='<option></option>'."\n";
1.82      albertel 4125:     foreach my $line (<$fh>) {
                   4126: 	my ($name,$descrip)=split(/:/,$line);
                   4127: 	if ($name =~ /^\#/) { next; }
                   4128: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4129:     }
                   4130:     $result.='</select>'."\n";
                   4131: 
                   4132:     return $result;
                   4133: }
                   4134: 
1.186     albertel 4135: sub scantron_CODElist {
1.257     albertel 4136:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4137:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4138:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4139:     my $namechoice='<option></option>';
1.225     albertel 4140:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4141: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4142: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4143: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4144:     }
                   4145:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4146:     return $namechoice;
                   4147: }
                   4148: 
                   4149: sub scantron_CODEunique {
                   4150:     my $result='<nobr>
1.272     albertel 4151:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4152:                         value="yes" checked="checked" /> Yes </label>
1.186     albertel 4153:                 </nobr>
                   4154:                 <nobr>
1.272     albertel 4155:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4156:                         value="no" /> No </label>
1.186     albertel 4157:                 </nobr>';
                   4158:     return $result;
                   4159: }
                   4160: 
1.75      albertel 4161: sub scantron_selectphase {
1.209     ng       4162:     my ($r,$file2grade) = @_;
1.324     albertel 4163:     my ($symb)=&get_symb($r);
1.75      albertel 4164:     if (!$symb) {return '';}
                   4165:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4166:     my $default_form_data=&defaultFormData($symb);
                   4167:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4168:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4169:     my $format_selector=&scantron_scantab();
1.186     albertel 4170:     my $CODE_selector=&scantron_CODElist();
                   4171:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4172:     my $result;
1.157     albertel 4173:     #FIXME allow instructor to be able to download the scantron file
                   4174:     # and to upload it,
1.75      albertel 4175:     $result.= <<SCANTRONFORM;
1.162     albertel 4176:     <table width="100%" border="0">
1.75      albertel 4177:     <tr>
1.226     albertel 4178:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4179:       <td bgcolor="#777777">
1.203     albertel 4180:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4181:         $default_form_data
1.75      albertel 4182:         <table width="100%" border="0">
                   4183:           <tr bgcolor="#e6ffff">
1.174     albertel 4184:             <td colspan="2">
                   4185:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4186:             </td>
                   4187:           </tr>
                   4188:           <tr bgcolor="#ffffe6">
1.174     albertel 4189:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4190:           </tr>
                   4191:           <tr bgcolor="#ffffe6">
1.174     albertel 4192:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4193:           </tr>
1.82      albertel 4194:           <tr bgcolor="#ffffe6">
1.174     albertel 4195:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4196:           </tr>
1.157     albertel 4197:           <tr bgcolor="#ffffe6">
1.186     albertel 4198:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4199:           </tr>
                   4200:           <tr bgcolor="#ffffe6">
                   4201:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4202:           </tr>
                   4203:           <tr bgcolor="#ffffe6">
1.187     albertel 4204: 	    <td> Options: </td>
                   4205:             <td>
1.272     albertel 4206: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
                   4207:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label>
1.187     albertel 4208: 	    </td>
                   4209:           </tr>
                   4210:           <tr bgcolor="#ffffe6">
1.174     albertel 4211:             <td colspan="2">
1.265     www      4212:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4213:             </td>
                   4214:           </tr>
                   4215:         </table>
1.226     albertel 4216:        </td>
                   4217:      </form>
1.162     albertel 4218:     </tr>
                   4219: SCANTRONFORM
                   4220:    
                   4221:     $r->print($result);
                   4222: 
1.257     albertel 4223:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4224:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4225: 
                   4226:         $r->print(<<SCANTRONFORM);
                   4227:     <tr>
                   4228:       <td bgcolor="#777777">
                   4229:         <table width="100%" border="0">
                   4230:           <tr bgcolor="#e6ffff">
                   4231:             <td>
1.174     albertel 4232:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4233:             </td>
                   4234:           </tr>
                   4235:           <tr bgcolor="#ffffe6">
                   4236:             <td>
                   4237: SCANTRONFORM
1.324     albertel 4238:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4239:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4240:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4241:     $r->print(<<UPLOAD);
                   4242:               <script type="text/javascript" language="javascript">
                   4243:     function checkUpload(formname) {
                   4244: 	if (formname.upfile.value == "") {
                   4245: 	    alert("Please use the browse button to select a file from your local directory.");
                   4246: 	    return false;
                   4247: 	}
                   4248: 	formname.submit();
                   4249:     }
                   4250:               </script>
                   4251: 
                   4252:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4253:                 $default_form_data
                   4254:                 <input name='courseid' type='hidden' value='$cnum' />
                   4255:                 <input name='domainid' type='hidden' value='$cdom' />
                   4256:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4257:                 File to upload:<input type="file" name="upfile" size="50" />
                   4258:                 <br />
                   4259:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4260:               </form>
                   4261: UPLOAD
1.162     albertel 4262: 
                   4263:         $r->print(<<SCANTRONFORM);
                   4264:             </td>
                   4265:           </tr>
1.75      albertel 4266:         </table>
                   4267:       </td>
                   4268:     </tr>
1.162     albertel 4269: SCANTRONFORM
                   4270:     }
1.187     albertel 4271:     $r->print(<<SCANTRONFORM);
                   4272:     <tr>
1.226     albertel 4273:       <form action='/adm/grades' name='scantron_download'>
                   4274:         <td bgcolor="#777777">
1.187     albertel 4275:           <input type="hidden" name="command" value="scantron_download" />
                   4276:           <table width="100%" border="0">
                   4277:             <tr bgcolor="#e6ffff">
                   4278:               <td colspan="2">
                   4279:                 &nbsp;<b>Download a scoring office file</b>
                   4280:               </td>
                   4281:             </tr>
                   4282:             <tr bgcolor="#ffffe6">
                   4283:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4284:             </tr>
                   4285:             <tr bgcolor="#ffffe6">
                   4286:               <td colspan="2">
1.293     www      4287:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4288:               </td>
                   4289:             </tr>
                   4290:           </table>
1.226     albertel 4291:         </td>
                   4292:       </form>
1.187     albertel 4293:     </tr>
                   4294: SCANTRONFORM
1.162     albertel 4295: 
                   4296:     $r->print(<<SCANTRONFORM);
1.75      albertel 4297:   </table>
1.81      albertel 4298: $grading_menu_button
1.75      albertel 4299: SCANTRONFORM
                   4300: 
1.162     albertel 4301:     return
1.75      albertel 4302: }
                   4303: 
1.82      albertel 4304: sub get_scantron_config {
                   4305:     my ($which) = @_;
                   4306:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4307:     my %config;
1.157     albertel 4308:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4309:     foreach my $line (<$fh>) {
                   4310: 	my ($name,$descrip)=split(/:/,$line);
                   4311: 	if ($name ne $which ) { next; }
                   4312: 	chomp($line);
                   4313: 	my @config=split(/:/,$line);
                   4314: 	$config{'name'}=$config[0];
                   4315: 	$config{'description'}=$config[1];
                   4316: 	$config{'CODElocation'}=$config[2];
                   4317: 	$config{'CODEstart'}=$config[3];
                   4318: 	$config{'CODElength'}=$config[4];
                   4319: 	$config{'IDstart'}=$config[5];
                   4320: 	$config{'IDlength'}=$config[6];
                   4321: 	$config{'Qstart'}=$config[7];
                   4322: 	$config{'Qlength'}=$config[8];
                   4323: 	$config{'Qoff'}=$config[9];
                   4324: 	$config{'Qon'}=$config[10];
1.157     albertel 4325: 	$config{'PaperID'}=$config[11];
                   4326: 	$config{'PaperIDlength'}=$config[12];
                   4327: 	$config{'FirstName'}=$config[13];
                   4328: 	$config{'FirstNamelength'}=$config[14];
                   4329: 	$config{'LastName'}=$config[15];
                   4330: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4331: 	last;
                   4332:     }
                   4333:     return %config;
                   4334: }
                   4335: 
                   4336: sub username_to_idmap {
                   4337:     my ($classlist)= @_;
                   4338:     my %idmap;
                   4339:     foreach my $student (keys(%$classlist)) {
                   4340: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4341: 	    $student;
                   4342:     }
                   4343:     return %idmap;
                   4344: }
                   4345: 
1.157     albertel 4346: sub scantron_fixup_scanline {
                   4347:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4348:     if ($field eq 'ID') {
                   4349: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4350: 	    return ($line,1,'New value too large');
1.157     albertel 4351: 	}
                   4352: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4353: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4354: 				     $args->{'newid'});
                   4355: 	}
                   4356: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4357: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4358: 	if ($args->{'newid'}=~/^\s*$/) {
                   4359: 	    &scan_data($scan_data,"$whichline.user",
                   4360: 		       $args->{'username'}.':'.$args->{'domain'});
                   4361: 	}
1.186     albertel 4362:     } elsif ($field eq 'CODE') {
1.192     albertel 4363: 	if ($args->{'CODE_ignore_dup'}) {
                   4364: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4365: 	}
                   4366: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4367: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4368: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4369: 		return ($line,1,'New CODE value too large');
                   4370: 	    }
                   4371: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4372: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4373: 	    }
                   4374: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4375: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4376: 	}
1.157     albertel 4377:     } elsif ($field eq 'answer') {
                   4378: 	my $length=$scantron_config->{'Qlength'};
                   4379: 	my $off=$scantron_config->{'Qoff'};
                   4380: 	my $on=$scantron_config->{'Qon'};
                   4381: 	my $answer=${off}x$length;
                   4382: 	if ($args->{'response'} eq 'none') {
                   4383: 	    &scan_data($scan_data,
                   4384: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4385: 	} else {
1.274     albertel 4386: 	    if ($on eq 'letter') {
                   4387: 		my @alphabet=('A'..'Z');
                   4388: 		$answer=$alphabet[$args->{'response'}];
                   4389: 	    } elsif ($on eq 'number') {
                   4390: 		$answer=$args->{'response'}+1;
                   4391: 	    } else {
                   4392: 		substr($answer,$args->{'response'},1)=$on;
                   4393: 	    }
1.157     albertel 4394: 	    &scan_data($scan_data,
                   4395: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4396: 	}
                   4397: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4398: 	substr($line,$where-1,$length)=$answer;
                   4399:     }
                   4400:     return $line;
                   4401: }
                   4402: 
                   4403: sub scan_data {
                   4404:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4405:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4406:     if (defined($value)) {
                   4407: 	$scan_data->{$filename.'_'.$key} = $value;
                   4408:     }
                   4409:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4410:     return $scan_data->{$filename.'_'.$key};
                   4411: }
                   4412: 
1.82      albertel 4413: sub scantron_parse_scanline {
1.194     albertel 4414:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4415:     my %record;
                   4416:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4417:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4418:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4419: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4420: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4421: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4422: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4423: 	    $record{'scantron.CODE'}=substr($data,
                   4424: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4425: 					    $$scantron_config{'CODElength'});
1.191     albertel 4426: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4427: 		$record{'scantron.useCODE'}=1;
                   4428: 	    }
1.192     albertel 4429: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4430: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4431: 	    }
1.82      albertel 4432: 	} else {
                   4433: 	    #FIXME interpret first N questions
                   4434: 	}
                   4435:     }
1.83      albertel 4436:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4437: 				  $$scantron_config{'IDlength'});
1.157     albertel 4438:     $record{'scantron.PaperID'}=
                   4439: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4440: 	       $$scantron_config{'PaperIDlength'});
                   4441:     $record{'scantron.FirstName'}=
                   4442: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4443: 	       $$scantron_config{'FirstNamelength'});
                   4444:     $record{'scantron.LastName'}=
                   4445: 	substr($data,$$scantron_config{'LastName'}-1,
                   4446: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4447:     if ($justHeader) { return \%record; }
                   4448: 
1.82      albertel 4449:     my @alphabet=('A'..'Z');
                   4450:     my $questnum=0;
                   4451:     while ($questions) {
                   4452: 	$questnum++;
                   4453: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4454: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4455: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4456: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.274     albertel 4457: 	    if ($currentquest eq '?') {
                   4458: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4459: 		$record{"scantron.$questnum.answer"}='';
                   4460: 	    } elsif (!$currentquest 
                   4461: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4462: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4463: 		$record{"scantron.$questnum.answer"}='';
                   4464: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4465: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4466: 		}
                   4467: 	    } else {
                   4468: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4469: 	    }
                   4470: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.274     albertel 4471: 	    if ($currentquest eq '?') {
                   4472: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4473: 		$record{"scantron.$questnum.answer"}='';
                   4474: 		} elsif (!$currentquest 
                   4475: 			 || $currentquest eq $$scantron_config{'Qoff'} 
                   4476: 			 || $currentquest !~ /^\d$/) {
1.239     albertel 4477: 		$record{"scantron.$questnum.answer"}='';
                   4478: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4479: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4480: 		}
                   4481: 	    } else {
                   4482: 		$record{"scantron.$questnum.answer"}=
                   4483: 		    $alphabet[$currentquest-1];
                   4484: 	    }
1.82      albertel 4485: 	} else {
1.239     albertel 4486: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4487: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4488: 		$record{"scantron.$questnum.answer"}='';
                   4489: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4490: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4491: 		}
                   4492: 	    } else {
                   4493: 		$record{"scantron.$questnum.answer"}=
                   4494: 		    $alphabet[length($array[0])];
                   4495: 	    }
                   4496: 	    if (scalar(@array) gt 2) {
                   4497: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4498: 		my @ans=@array;
                   4499: 		my $i=length($ans[0]);shift(@ans);
                   4500: 		while ($#ans) {
                   4501: 		    $i+=length($ans[0])+1;
                   4502: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4503: 		    shift(@ans);
                   4504: 		}
                   4505: 	    }
1.82      albertel 4506: 	}
                   4507:     }
1.83      albertel 4508:     $record{'scantron.maxquest'}=$questnum;
                   4509:     return \%record;
1.82      albertel 4510: }
                   4511: 
                   4512: sub scantron_add_delay {
1.140     albertel 4513:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4514:     push(@$delayqueue,
                   4515: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4516: 	  'ecode' => $errorcode }
                   4517: 	 );
1.82      albertel 4518: }
                   4519: 
                   4520: sub scantron_find_student {
1.157     albertel 4521:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4522:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4523:     if ($scanID =~ /^\s*$/) {
                   4524:  	return &scan_data($scan_data,"$line.user");
                   4525:     }
1.83      albertel 4526:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4527:  	if (lc($id) eq lc($scanID)) {
                   4528:  	    return $$idmap{$id};
                   4529:  	}
1.83      albertel 4530:     }
                   4531:     return undef;
                   4532: }
                   4533: 
                   4534: sub scantron_filter {
                   4535:     my ($curres)=@_;
1.215     albertel 4536:                         # randomout is dysfunctional at best for this purpose
                   4537:     if (ref($curres) && $curres->is_problem()) { #&& !$curres->randomout) {
1.83      albertel 4538: 	return 1;
                   4539:     }
                   4540:     return 0;
1.82      albertel 4541: }
                   4542: 
1.157     albertel 4543: sub scantron_process_corrections {
                   4544:     my ($r) = @_;
1.257     albertel 4545:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4546:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4547:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4548:     my $which=$env{'form.scantron_line'};
1.200     albertel 4549:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4550:     my ($skip,$err,$errmsg);
1.257     albertel 4551:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4552: 	$skip=1;
1.257     albertel 4553:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4554: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4555: 	    $env{'form.scantron_domain'};
1.157     albertel 4556: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4557: 	($line,$err,$errmsg)=
                   4558: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4559: 				     'ID',{'newid'=>$newid,
1.257     albertel 4560: 				    'username'=>$env{'form.scantron_username'},
                   4561: 				    'domain'=>$env{'form.scantron_domain'}});
                   4562:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4563: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4564: 	my $newCODE;
1.192     albertel 4565: 	my %args;
1.190     albertel 4566: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4567: 	    $newCODE='use_unfound';
1.190     albertel 4568: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4569: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4570: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4571: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4572: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4573: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4574: 	}
1.257     albertel 4575: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4576: 	    $args{'CODE_ignore_dup'}=1;
                   4577: 	}
                   4578: 	$args{'CODE'}=$newCODE;
1.186     albertel 4579: 	($line,$err,$errmsg)=
                   4580: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4581: 				     'CODE',\%args);
1.257     albertel 4582:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4583: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4584: 	    ($line,$err,$errmsg)=
                   4585: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4586: 					 $which,'answer',
                   4587: 					 { 'question'=>$question,
1.257     albertel 4588: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4589: 	    if ($err) { last; }
                   4590: 	}
                   4591:     }
                   4592:     if ($err) {
1.287     albertel 4593: 	$r->print("<font color='red'>Unable to accept last correction, an error occurred :$errmsg:</font>");
1.157     albertel 4594:     } else {
1.200     albertel 4595: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4596: 	&scantron_putfile($scanlines,$scan_data);
                   4597:     }
                   4598: }
                   4599: 
1.200     albertel 4600: sub reset_skipping_status {
                   4601:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4602:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4603:     &scantron_putfile(undef,$scan_data);
                   4604: }
                   4605: 
                   4606: sub allow_skipping {
                   4607:     my ($scan_data,$i)=@_;
                   4608:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4609:     delete($remembered{$i});
                   4610:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4611: }
                   4612: 
                   4613: sub should_be_skipped {
                   4614:     my ($scan_data,$i)=@_;
1.257     albertel 4615:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4616: 	# not redoing old skips
                   4617: 	return 0;
                   4618:     }
                   4619:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4620:     if (exists($remembered{$i})) { return 0; }
                   4621:     return 1;
                   4622: }
                   4623: 
                   4624: sub remember_current_skipped {
                   4625:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4626:     my %to_remember;
                   4627:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4628: 	if ($scanlines->{'skipped'}[$i]) {
                   4629: 	    $to_remember{$i}=1;
                   4630: 	}
                   4631:     }
                   4632:     &Apache::lonnet::logthis('remembering '.join(':',%to_remember));
                   4633:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4634:     &scantron_putfile(undef,$scan_data);
                   4635: }
                   4636: 
                   4637: sub check_for_error {
                   4638:     my ($r,$result)=@_;
                   4639:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4640: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4641:     }
                   4642: }
1.157     albertel 4643: 
1.203     albertel 4644: sub scantron_warning_screen {
                   4645:     my ($button_text)=@_;
1.257     albertel 4646:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4647:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   4648:     my $CODElist="a";
                   4649:     if ($scantron_config{'CODElocation'} &&
                   4650: 	$scantron_config{'CODEstart'} &&
                   4651: 	$scantron_config{'CODElength'}) {
                   4652: 	$CODElist=$env{'form.scantron_CODElist'};
                   4653: 	if ($CODElist eq '') { $CODElist='<font color="red">None</font>'; }
                   4654: 	$CODElist=
                   4655: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
                   4656: 	    $CODElist.'</tt></td></tr>';
                   4657:     }
1.203     albertel 4658:     return (<<STUFF);
                   4659: <p>
                   4660: <font color="red">Please double check the information
                   4661:                  below before clicking on '$button_text'</font>
                   4662: </p>
                   4663: <table>
1.284     albertel 4664: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4665: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4666: $CODElist
1.203     albertel 4667: </table>
                   4668: </font>
                   4669: <br />
                   4670: <p> If this information is correct, please click on '$button_text'.</p>
                   4671: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4672: 
                   4673: <br />
                   4674: STUFF
                   4675: }
                   4676: 
                   4677: sub scantron_do_warning {
                   4678:     my ($r)=@_;
1.324     albertel 4679:     my ($symb)=&get_symb($r);
1.203     albertel 4680:     if (!$symb) {return '';}
1.324     albertel 4681:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 4682:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 4683:     if ( $env{'form.selectpage'} eq '' ||
                   4684: 	 $env{'form.scantron_selectfile'} eq '' ||
                   4685: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 4686: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 4687: 	if ( $env{'form.selectpage'} eq '') {
1.237     albertel 4688: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
                   4689: 	} 
1.257     albertel 4690: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.237     albertel 4691: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
                   4692: 	} 
1.257     albertel 4693: 	if ( $env{'form.scantron_format'} eq '') {
1.237     albertel 4694: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
                   4695: 	} 
                   4696:     } else {
1.265     www      4697: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 4698: 	$r->print(<<STUFF);
1.203     albertel 4699: $warning
1.265     www      4700: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 4701: <input type="hidden" name="command" value="scantron_validate" />
                   4702: STUFF
1.237     albertel 4703:     }
1.324     albertel 4704:     $r->print("</form><br />".&show_grading_menu_form($symb)."</body></html>");
1.203     albertel 4705:     return '';
                   4706: }
                   4707: 
                   4708: sub scantron_form_start {
                   4709:     my ($max_bubble)=@_;
                   4710:     my $result= <<SCANTRONFORM;
                   4711: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 4712:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   4713:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   4714:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 4715:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 4716:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   4717:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   4718:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   4719:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.203     albertel 4720: SCANTRONFORM
                   4721:     return $result;
                   4722: }
                   4723: 
1.157     albertel 4724: sub scantron_validate_file {
                   4725:     my ($r) = @_;
1.324     albertel 4726:     my ($symb)=&get_symb($r);
1.157     albertel 4727:     if (!$symb) {return '';}
1.324     albertel 4728:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 4729:     
                   4730:     # do the detection of only doing skipped records first befroe we delete
                   4731:     # them  when doing the corrections reset
1.257     albertel 4732:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 4733: 	&reset_skipping_status();
                   4734:     }
1.257     albertel 4735:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 4736: 	&remember_current_skipped();
                   4737: 	&scantron_remove_file('skipped');
1.257     albertel 4738: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 4739:     }
                   4740: 
1.257     albertel 4741:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 4742: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   4743: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   4744: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 4745: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 4746:     }
1.200     albertel 4747: 
1.257     albertel 4748:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 4749: 	&scantron_process_corrections($r);
                   4750:     }
1.191     albertel 4751:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 4752:     #get the student pick code ready
                   4753:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.203     albertel 4754:     my $max_bubble=&scantron_get_maxbubble($r);
                   4755:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 4756:     $r->print($result);
                   4757:     
                   4758:     my @validate_phases=( 'ID',
                   4759: 			  'CODE',
                   4760: 			  'doublebubble',
                   4761: 			  'missingbubbles');
1.257     albertel 4762:     if (!$env{'form.validatepass'}) {
                   4763: 	$env{'form.validatepass'} = 0;
1.157     albertel 4764:     }
1.257     albertel 4765:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 4766: 
                   4767:     my $stop=0;
                   4768:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   4769: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   4770: 	$r->rflush();
                   4771: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   4772: 	{
                   4773: 	    no strict 'refs';
                   4774: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   4775: 	}
                   4776:     }
                   4777:     if (!$stop) {
1.203     albertel 4778: 	my $warning=&scantron_warning_screen('Start Grading');
                   4779: 	$r->print(<<STUFF);
                   4780: Validation process complete.<br />
                   4781: $warning
                   4782: <input type="submit" name="submit" value="Start Grading" />
                   4783: <input type="hidden" name="command" value="scantron_process" />
                   4784: STUFF
                   4785: 
1.157     albertel 4786:     } else {
                   4787: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   4788: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   4789:     }
                   4790:     if ($stop) {
                   4791: 	$r->print('<input type="submit" name="submit" value="Continue ->" />');
                   4792: 	$r->print(' using corrected info <br />');
                   4793: 	$r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   4794: 	$r->print(" this scanline saving it for later.");
                   4795:     }
1.324     albertel 4796:     $r->print(" </form><br />".&show_grading_menu_form($symb).
1.157     albertel 4797: 	      "</body></html>");
                   4798:     return '';
                   4799: }
                   4800: 
1.200     albertel 4801: sub scantron_remove_file {
1.192     albertel 4802:     my ($which)=@_;
1.257     albertel 4803:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4804:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4805:     my $file='scantron_';
1.200     albertel 4806:     if ($which eq 'corrected' || $which eq 'skipped') {
                   4807: 	$file.=$which.'_';
1.192     albertel 4808:     } else {
                   4809: 	return 'refused';
                   4810:     }
1.257     albertel 4811:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 4812:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   4813: }
                   4814: 
                   4815: sub scantron_remove_scan_data {
1.257     albertel 4816:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4817:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4818:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   4819:     my @todelete;
1.257     albertel 4820:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 4821:     foreach my $key (@keys) {
                   4822: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 4823: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 4824: 		$key=~/remember_skipping/) {
                   4825: 		next;
                   4826: 	    }
1.192     albertel 4827: 	    push(@todelete,$key);
                   4828: 	}
                   4829:     }
1.200     albertel 4830:     my $result;
1.192     albertel 4831:     if (@todelete) {
1.200     albertel 4832: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 4833:     }
                   4834:     return $result;
                   4835: }
                   4836: 
1.157     albertel 4837: sub scantron_getfile {
1.200     albertel 4838:     #FIXME really would prefer a scantron directory
1.257     albertel 4839:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4840:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 4841:     my $lines;
                   4842:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4843: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 4844:     my %scanlines;
                   4845:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   4846:     my $temp=$scanlines{'orig'};
                   4847:     $scanlines{'count'}=$#$temp;
                   4848: 
                   4849:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4850: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 4851:     if ($lines eq '-1') {
                   4852: 	$scanlines{'corrected'}=[];
                   4853:     } else {
                   4854: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   4855:     }
                   4856:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4857: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 4858:     if ($lines eq '-1') {
                   4859: 	$scanlines{'skipped'}=[];
                   4860:     } else {
                   4861: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   4862:     }
1.175     albertel 4863:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 4864:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   4865:     my %scan_data = @tmp;
                   4866:     return (\%scanlines,\%scan_data);
                   4867: }
                   4868: 
                   4869: sub lonnet_putfile {
                   4870:     my ($contents,$filename)=@_;
1.257     albertel 4871:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4872:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4873:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 4874:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 4875: 
                   4876: }
                   4877: 
                   4878: sub scantron_putfile {
                   4879:     my ($scanlines,$scan_data) = @_;
1.200     albertel 4880:     #FIXME really would prefer a scantron directory
1.257     albertel 4881:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4882:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 4883:     if ($scanlines) {
                   4884: 	my $prefix='scantron_';
1.157     albertel 4885: # no need to update orig, shouldn't change
                   4886: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 4887: #		    $env{'form.scantron_selectfile'});
1.200     albertel 4888: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   4889: 			$prefix.'corrected_'.
1.257     albertel 4890: 			$env{'form.scantron_selectfile'});
1.200     albertel 4891: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   4892: 			$prefix.'skipped_'.
1.257     albertel 4893: 			$env{'form.scantron_selectfile'});
1.200     albertel 4894:     }
1.175     albertel 4895:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 4896: }
                   4897: 
                   4898: sub scantron_get_line {
1.200     albertel 4899:     my ($scanlines,$scan_data,$i)=@_;
                   4900:     if (&should_be_skipped($scan_data,$i)) { return undef; }
                   4901:     if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 4902:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   4903:     return $scanlines->{'orig'}[$i]; 
                   4904: }
                   4905: 
1.200     albertel 4906: sub get_todo_count {
                   4907:     my ($scanlines,$scan_data)=@_;
                   4908:     my $count=0;
                   4909:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4910: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   4911: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4912: 	$count++;
                   4913:     }
                   4914:     return $count;
                   4915: }
                   4916: 
1.157     albertel 4917: sub scantron_put_line {
1.200     albertel 4918:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 4919:     if ($skip) {
                   4920: 	$scanlines->{'skipped'}[$i]=$newline;
1.200     albertel 4921: 	&allow_skipping($scan_data,$i);
1.157     albertel 4922: 	return;
                   4923:     }
                   4924:     $scanlines->{'corrected'}[$i]=$newline;
                   4925: }
                   4926: 
                   4927: sub scantron_validate_ID {
                   4928:     my ($r,$currentphase) = @_;
                   4929:     
                   4930:     #get student info
                   4931:     my $classlist=&Apache::loncoursedata::get_classlist();
                   4932:     my %idmap=&username_to_idmap($classlist);
                   4933: 
                   4934:     #get scantron line setup
1.257     albertel 4935:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4936:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4937: 
                   4938:     my %found=('ids'=>{},'usernames'=>{});
                   4939:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 4940: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 4941: 	if ($line=~/^[\s\cz]*$/) { next; }
                   4942: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   4943: 						 $scan_data);
                   4944: 	my $id=$$scan_record{'scantron.ID'};
                   4945: 	my $found;
                   4946: 	foreach my $checkid (keys(%idmap)) {
                   4947: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   4948: 	}
                   4949: 	if ($found) {
                   4950: 	    my $username=$idmap{$found};
                   4951: 	    if ($found{'ids'}{$found}) {
                   4952: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4953: 					 $line,'duplicateID',$found);
1.194     albertel 4954: 		return(1,$currentphase);
1.157     albertel 4955: 	    } elsif ($found{'usernames'}{$username}) {
                   4956: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4957: 					 $line,'duplicateID',$username);
1.194     albertel 4958: 		return(1,$currentphase);
1.157     albertel 4959: 	    }
1.186     albertel 4960: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 4961: 	    $found{'ids'}{$found}++;
                   4962: 	    $found{'usernames'}{$username}++;
                   4963: 	} else {
                   4964: 	    if ($id =~ /^\s*$/) {
1.158     albertel 4965: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 4966: 		if (defined($username) && $found{'usernames'}{$username}) {
                   4967: 		    &scantron_get_correction($r,$i,$scan_record,
                   4968: 					     \%scantron_config,
                   4969: 					     $line,'duplicateID',$username);
1.194     albertel 4970: 		    return(1,$currentphase);
1.157     albertel 4971: 		} elsif (!defined($username)) {
                   4972: 		    &scantron_get_correction($r,$i,$scan_record,
                   4973: 					     \%scantron_config,
                   4974: 					     $line,'incorrectID');
1.194     albertel 4975: 		    return(1,$currentphase);
1.157     albertel 4976: 		}
                   4977: 		$found{'usernames'}{$username}++;
                   4978: 	    } else {
                   4979: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   4980: 					 $line,'incorrectID');
1.194     albertel 4981: 		return(1,$currentphase);
1.157     albertel 4982: 	    }
                   4983: 	}
                   4984:     }
                   4985: 
                   4986:     return (0,$currentphase+1);
                   4987: }
                   4988: 
                   4989: sub scantron_get_correction {
                   4990:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   4991: 
                   4992: #FIXME in the case of a duplicated ID the previous line, probaly need
                   4993: #to show both the current line and the previous one and allow skipping
                   4994: #the previous one or the current one
                   4995: 
1.161     albertel 4996:     $r->print("<p><b>An error was detected ($error)</b>");
1.157     albertel 4997:     if ( defined($$scan_record{'scantron.PaperID'}) ) {
                   4998: 	$r->print(" for PaperID <tt>".
                   4999: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5000:     } else {
                   5001: 	$r->print(" in scanline $i <pre>".
                   5002: 		  $line."</pre> \n");
                   5003:     }
1.242     albertel 5004:     my $message="<p>The ID on the form is  <tt>".
                   5005: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5006: 	"The name on the paper is ".
                   5007: 	$$scan_record{'scantron.LastName'}.",".
                   5008: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5009: 
1.157     albertel 5010:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5011:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5012:     if ($error =~ /ID$/) {
1.186     albertel 5013: 	if ($error eq 'incorrectID') {
1.157     albertel 5014: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5015: 	} elsif ($error eq 'duplicateID') {
                   5016: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5017: 	}
1.242     albertel 5018: 	$r->print($message);
1.157     albertel 5019: 	$r->print("<p>How should I handle this? <br /> \n");
                   5020: 	$r->print("\n<ul><li> ");
                   5021: 	#FIXME it would be nice if this sent back the user ID and
                   5022: 	#could do partial userID matches
                   5023: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5024: 				       'scantron_username','scantron_domain'));
                   5025: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5026: 	$r->print("\n@".
1.257     albertel 5027: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5028: 
                   5029: 	$r->print('</li>');
1.186     albertel 5030:     } elsif ($error =~ /CODE$/) {
                   5031: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5032: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5033: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5034: 	    $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 5035: 	}
1.224     albertel 5036: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5037: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5038: 	$r->print($message);
1.186     albertel 5039: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5040: 	$r->print("\n<br /> ");
1.194     albertel 5041: 	my $i=0;
1.273     albertel 5042: 	if ($error eq 'incorrectCODE' 
                   5043: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5044: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5045: 	    if ($closest > 0) {
                   5046: 		foreach my $testcode (@{$closest}) {
                   5047: 		    my $checked='';
                   5048: 		    if (!$i) { $checked=' checked="on" '; }
                   5049: 		    $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' />");
                   5050: 		    $r->print("\n<br />");
                   5051: 		    $i++;
                   5052: 		}
1.194     albertel 5053: 	    }
                   5054: 	}
1.273     albertel 5055: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   5056: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   5057: 	    $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>");
                   5058: 	    $r->print("\n<br />");
                   5059: 	}
1.194     albertel 5060: 
1.188     albertel 5061: 	$r->print(<<ENDSCRIPT);
                   5062: <script type="text/javascript">
                   5063: function change_radio(field) {
1.190     albertel 5064:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5065:     var i;
                   5066:     for (i=0;i<slct.length;i++) {
                   5067:         if (slct[i].value==field) { slct[i].checked=true; }
                   5068:     }
                   5069: }
                   5070: </script>
                   5071: ENDSCRIPT
1.187     albertel 5072: 	my $href="/adm/pickcode?".
                   5073: 	   "form=".&Apache::lonnet::escape("scantronupload").
1.257     albertel 5074: 	   "&scantron_format=".&Apache::lonnet::escape($env{'form.scantron_format'}).
                   5075: 	   "&scantron_CODElist=".&Apache::lonnet::escape($env{'form.scantron_CODElist'}).
1.187     albertel 5076: 	   "&curCODE=".&Apache::lonnet::escape($$scan_record{'scantron.CODE'}).
1.257     albertel 5077: 	   "&scantron_selectfile=".&Apache::lonnet::escape($env{'form.scantron_selectfile'});
1.272     albertel 5078: 	$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 5079: 	$r->print("\n<br />");
1.272     albertel 5080: 	$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 5081: 	$r->print("\n<br /><br />");
1.157     albertel 5082:     } elsif ($error eq 'doublebubble') {
                   5083: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5084: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5085: 		  join(',',@{$arg}).'" />');
1.242     albertel 5086: 	$r->print($message);
1.157     albertel 5087: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5088: 	foreach my $question (@{$arg}) {
                   5089: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5090: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5091: 	}
                   5092:     } elsif ($error eq 'missingbubble') {
                   5093: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5094: 	$r->print($message);
1.157     albertel 5095: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5096: 	$r->print("Some questions have no scanned bubbles\n");
                   5097: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5098: 		  join(',',@{$arg}).'" />');
                   5099: 	foreach my $question (@{$arg}) {
                   5100: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5101: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5102: 	}
                   5103:     } else {
                   5104: 	$r->print("\n<ul>");
                   5105:     }
                   5106:     $r->print("\n</li></ul>");
                   5107: 
                   5108: }
                   5109: 
                   5110: sub scantron_bubble_selector {
                   5111:     my ($r,$scan_config,$quest,@selected)=@_;
                   5112:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5113: 
                   5114:     my $scmode=$$scan_config{'Qon'};
                   5115:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5116: 
1.157     albertel 5117:     my @alphabet=('A'..'Z');
                   5118:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5119:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5120: 	$r->print("\n".'<td align="center">');
1.157     albertel 5121: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5122: 	else { $r->print('&nbsp;'); }
                   5123: 	$r->print('</td>');
                   5124:     }
1.274     albertel 5125:     $r->print('</tr><tr>');
1.157     albertel 5126:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5127: 	$r->print("\n".
                   5128: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5129: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5130:     }
1.272     albertel 5131:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5132: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5133:     $r->print('</tr></table>');
                   5134: }
                   5135: 
1.194     albertel 5136: sub num_matches {
                   5137:     my ($orig,$code) = @_;
                   5138:     my @code=split(//,$code);
                   5139:     my @orig=split(//,$orig);
                   5140:     my $same=0;
                   5141:     for (my $i=0;$i<scalar(@code);$i++) {
                   5142: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5143:     }
                   5144:     return $same;
                   5145: }
                   5146: 
                   5147: sub scantron_get_closely_matching_CODEs {
                   5148:     my ($allcodes,$CODE)=@_;
                   5149:     my @CODEs;
                   5150:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5151: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5152:     }
                   5153: 
                   5154:     return ($#CODEs,$CODEs[-1]);
                   5155: }
                   5156: 
                   5157: sub get_codes {
1.280     foxr     5158:     my ($old_name, $cdom, $cnum) = @_;
                   5159:     if (!$old_name) {
                   5160: 	$old_name=$env{'form.scantron_CODElist'};
                   5161:     }
                   5162:     if (!$cdom) {
                   5163: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5164:     }
                   5165:     if (!$cnum) {
                   5166: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5167:     }
1.278     albertel 5168:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5169: 				    $cdom,$cnum);
                   5170:     my %allcodes;
                   5171:     if ($result{"type\0$old_name"} eq 'number') {
                   5172: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5173:     } else {
                   5174: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5175:     }
1.194     albertel 5176:     return %allcodes;
                   5177: }
                   5178: 
1.157     albertel 5179: sub scantron_validate_CODE {
                   5180:     my ($r,$currentphase) = @_;
1.257     albertel 5181:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5182:     if ($scantron_config{'CODElocation'} &&
                   5183: 	$scantron_config{'CODEstart'} &&
                   5184: 	$scantron_config{'CODElength'}) {
1.257     albertel 5185: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5186: 	    &FIXME_blow_up()
                   5187: 	}
                   5188:     } else {
                   5189: 	return (0,$currentphase+1);
                   5190:     }
                   5191:     
                   5192:     my %usedCODEs;
                   5193: 
1.194     albertel 5194:     my %allcodes=&get_codes();
1.186     albertel 5195: 
                   5196:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5197:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5198: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5199: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5200: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5201: 						 $scan_data);
                   5202: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5203: 	my $error=0;
1.224     albertel 5204: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5205: 	    &scantron_get_correction($r,$i,$scan_record,
                   5206: 				     \%scantron_config,
                   5207: 				     $line,'incorrectCODE',\%allcodes);
                   5208: 	    return(1,$currentphase);
                   5209: 	}
1.221     albertel 5210: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5211: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5212: 	    &scantron_get_correction($r,$i,$scan_record,
                   5213: 				     \%scantron_config,
1.194     albertel 5214: 				     $line,'incorrectCODE',\%allcodes);
                   5215: 	    return(1,$currentphase);
1.186     albertel 5216: 	}
1.214     albertel 5217: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5218: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5219: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5220: 	    &scantron_get_correction($r,$i,$scan_record,
                   5221: 				     \%scantron_config,
1.194     albertel 5222: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5223: 	    return(1,$currentphase);
1.186     albertel 5224: 	}
1.194     albertel 5225: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5226:     }
1.157     albertel 5227:     return (0,$currentphase+1);
                   5228: }
                   5229: 
                   5230: sub scantron_validate_doublebubble {
                   5231:     my ($r,$currentphase) = @_;
                   5232:     #get student info
                   5233:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5234:     my %idmap=&username_to_idmap($classlist);
                   5235: 
                   5236:     #get scantron line setup
1.257     albertel 5237:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5238:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5239:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5240: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5241: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5242: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5243: 						 $scan_data);
                   5244: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5245: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5246: 				 'doublebubble',
                   5247: 				 $$scan_record{'scantron.doubleerror'});
                   5248:     	return (1,$currentphase);
                   5249:     }
                   5250:     return (0,$currentphase+1);
                   5251: }
                   5252: 
1.191     albertel 5253: sub scantron_get_maxbubble {
                   5254:     my ($r)=@_;
1.257     albertel 5255:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5256: 	$env{'form.scantron_maxbubble'}) {
                   5257: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5258:     }
                   5259:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5260:     my (undef,undef,$sequence)=
1.257     albertel 5261: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.191     albertel 5262:     my $map=$navmap->getResourceByUrl($sequence);
                   5263:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
                   5264:     &Apache::lonnet::delenv('form.counter');
                   5265:     foreach my $resource (@resources) {
1.234     albertel 5266: 	my $result=&Apache::lonnet::ssi($resource->src().'?symb='.&Apache::lonnet::escape($resource->symb()));
1.191     albertel 5267:     }
                   5268:     &Apache::lonnet::delenv('scantron\.');
1.257     albertel 5269:     my $envfile=$env{'user.environment'};
1.191     albertel 5270:     $envfile=~/\/([^\/]+)\.id$/;
                   5271:     $envfile=$1;
                   5272:     &Apache::lonnet::transfer_profile_to_env($r->dir_config('lonIDsDir'),
                   5273: 					     $envfile);
1.257     albertel 5274:     $env{'form.scantron_maxbubble'}=$env{'form.counter'}-1;
                   5275:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5276: }
                   5277: 
1.157     albertel 5278: sub scantron_validate_missingbubbles {
                   5279:     my ($r,$currentphase) = @_;
                   5280:     #get student info
                   5281:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5282:     my %idmap=&username_to_idmap($classlist);
                   5283: 
                   5284:     #get scantron line setup
1.257     albertel 5285:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5286:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5287:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5288:     if (!$max_bubble) { $max_bubble=2**31; }
                   5289:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5290: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5291: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5292: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5293: 						 $scan_data);
                   5294: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5295: 	my @to_correct;
                   5296: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5297: 	    if ($missing > $max_bubble) { next; }
                   5298: 	    push(@to_correct,$missing);
                   5299: 	}
                   5300: 	if (@to_correct) {
                   5301: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5302: 				     $line,'missingbubble',\@to_correct);
                   5303: 	    return (1,$currentphase);
                   5304: 	}
                   5305: 
                   5306:     }
                   5307:     return (0,$currentphase+1);
                   5308: }
                   5309: 
1.82      albertel 5310: sub scantron_process_students {
1.75      albertel 5311:     my ($r) = @_;
1.257     albertel 5312:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5313:     my ($symb)=&get_symb($r);
1.81      albertel 5314:     if (!$symb) {return '';}
1.324     albertel 5315:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5316: 
1.257     albertel 5317:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5318:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5319:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5320:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5321:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5322:     my $map=$navmap->getResourceByUrl($sequence);
                   5323:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5324: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5325:     my $result= <<SCANTRONFORM;
1.81      albertel 5326: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5327:   <input type="hidden" name="command" value="scantron_configphase" />
                   5328:   $default_form_data
                   5329: SCANTRONFORM
1.82      albertel 5330:     $r->print($result);
                   5331: 
                   5332:     my @delayqueue;
1.140     albertel 5333:     my %completedstudents;
                   5334:     
1.200     albertel 5335:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5336:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5337:  				    'Scantron Progress',$count,
1.195     albertel 5338: 				    'inline',undef,'scantronupload');
1.140     albertel 5339:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5340: 					  'Processing first student');
                   5341:     my $start=&Time::HiRes::time();
1.158     albertel 5342:     my $i=-1;
1.200     albertel 5343:     my ($uname,$udom,$started);
1.157     albertel 5344:     while ($i<$scanlines->{'count'}) {
                   5345:  	($uname,$udom)=('','');
                   5346:  	$i++;
1.200     albertel 5347:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5348:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5349: 	if ($started) {
                   5350: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5351: 						     'last student');
                   5352: 	}
                   5353: 	$started=1;
1.157     albertel 5354:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5355:  						 $scan_data);
                   5356:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5357:  					      \%idmap,$i)) {
                   5358:   	    &scantron_add_delay(\@delayqueue,$line,
                   5359:  				'Unable to find a student that matches',1);
                   5360:  	    next;
                   5361:   	}
                   5362:  	if (exists $completedstudents{$uname}) {
                   5363:  	    &scantron_add_delay(\@delayqueue,$line,
                   5364:  				'Student '.$uname.' has multiple sheets',2);
                   5365:  	    next;
                   5366:  	}
                   5367:   	($uname,$udom)=split(/:/,$uname);
                   5368:   	&Apache::lonnet::delenv('form.counter');
                   5369:   	&Apache::lonnet::appenv(%$scan_record);
1.161     albertel 5370: 	
                   5371: 	my $i=0;
1.83      albertel 5372: 	foreach my $resource (@resources) {
1.85      albertel 5373: 	    $i++;
1.193     albertel 5374: 	    my %form=('submitted'     =>'scantron',
                   5375: 		      'grade_target'  =>'grade',
                   5376: 		      'grade_username'=>$uname,
                   5377: 		      'grade_domain'  =>$udom,
1.257     albertel 5378: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5379: 		      'grade_symb'    =>$resource->symb());
                   5380: 	    if (exists($scan_record->{'scantron.CODE'}) &&
                   5381: 		$scan_record->{'scantron.CODE'}) {
                   5382: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5383: 	    } else {
                   5384: 		$form{'CODE'}='';
1.193     albertel 5385: 	    }
                   5386: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5387: 	    if ($result ne '') {
                   5388: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5389: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5390: 	    }
1.213     albertel 5391: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5392: 	}
1.140     albertel 5393: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5394: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5395:     } continue {
1.85      albertel 5396: 	&Apache::lonnet::delenv('form.counter');
1.83      albertel 5397: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5398:     }
1.140     albertel 5399:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5400: #    my $lasttime = &Time::HiRes::time()-$start;
                   5401: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5402: 
1.200     albertel 5403:     $r->print("</form>");
1.324     albertel 5404:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5405:     return '';
1.75      albertel 5406: }
1.157     albertel 5407: 
                   5408: sub scantron_upload_scantron_data {
                   5409:     my ($r)=@_;
1.257     albertel 5410:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5411:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5412: 							  'domainid',
                   5413: 							  'coursename');
1.257     albertel 5414:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5415: 						   'domainid');
1.324     albertel 5416:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5417:     $r->print(<<UPLOAD);
                   5418: <script type="text/javascript" language="javascript">
                   5419:     function checkUpload(formname) {
                   5420: 	if (formname.upfile.value == "") {
                   5421: 	    alert("Please use the browse button to select a file from your local directory.");
                   5422: 	    return false;
                   5423: 	}
                   5424: 	formname.submit();
                   5425:     }
                   5426: </script>
                   5427: 
                   5428: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5429: $default_form_data
1.181     albertel 5430: <table>
                   5431: <tr><td>$select_link </td></tr>
                   5432: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5433: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5434: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5435: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5436: </table>
1.157     albertel 5437: <input name='command' value='scantronupload_save' type='hidden' />
                   5438: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5439: </form>
                   5440: UPLOAD
                   5441:     return '';
                   5442: }
                   5443: 
                   5444: sub scantron_upload_scantron_data_save {
                   5445:     my($r)=@_;
1.324     albertel 5446:     my ($symb)=&get_symb($r,1);
1.182     albertel 5447:     my $doanotherupload=
                   5448: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5449: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5450: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5451: 	'</form>'."\n";
1.257     albertel 5452:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5453: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5454: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5455: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5456: 	if ($symb) {
1.324     albertel 5457: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5458: 	} else {
                   5459: 	    $r->print($doanotherupload);
                   5460: 	}
1.162     albertel 5461: 	return '';
                   5462:     }
1.257     albertel 5463:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5464:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5465:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5466:     #FIXME
                   5467:     #copied from lonnet::userfileupload()
                   5468:     #make that function able to target a specified course
                   5469:     # Replace Windows backslashes by forward slashes
                   5470:     $fname=~s/\\/\//g;
                   5471:     # Get rid of everything but the actual filename
                   5472:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5473:     # Replace spaces by underscores
                   5474:     $fname=~s/\s+/\_/g;
                   5475:     # Replace all other weird characters by nothing
                   5476:     $fname=~s/[^\w\.\-]//g;
                   5477:     # See if there is anything left
                   5478:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5479:     my $uploadedfile=$fname;
1.157     albertel 5480:     $fname='scantron_orig_'.$fname;
1.257     albertel 5481:     if (length($env{'form.upfile'}) < 2) {
                   5482: 	$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 5483:     } else {
1.275     albertel 5484: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5485: 	if ($result =~ m|^/uploaded/|) {
1.257     albertel 5486: 	    $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 5487: 	} else {
1.257     albertel 5488: 	    $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 5489: 	}
                   5490:     }
1.174     albertel 5491:     if ($symb) {
1.209     ng       5492: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5493:     } else {
1.182     albertel 5494: 	$r->print($doanotherupload);
1.174     albertel 5495:     }
1.157     albertel 5496:     return '';
                   5497: }
                   5498: 
1.202     albertel 5499: sub valid_file {
                   5500:     my ($requested_file)=@_;
                   5501:     foreach my $filename (sort(&scantron_filenames())) {
                   5502: 	&Apache::lonnet::logthis("$requested_file  $filename");
                   5503: 	if ($requested_file eq $filename) { return 1; }
                   5504:     }
                   5505:     return 0;
                   5506: }
                   5507: 
                   5508: sub scantron_download_scantron_data {
                   5509:     my ($r)=@_;
1.324     albertel 5510:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5511:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5512:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5513:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5514:     if (! &valid_file($file)) {
                   5515: 	$r->print(<<ERROR);
                   5516: 	<p>
                   5517: 	    The requested file name was invalid.
                   5518:         </p>
                   5519: ERROR
1.324     albertel 5520: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5521: 	return;
                   5522:     }
                   5523:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5524:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5525:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5526:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5527:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5528:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5529:     $r->print(<<DOWNLOAD);
                   5530:     <p>
                   5531: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5532:     </p>
                   5533:     <p>
                   5534: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5535:     </p>
                   5536:     <p>
                   5537: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5538:     </p>
                   5539: DOWNLOAD
1.324     albertel 5540:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5541:     return '';
                   5542: }
1.157     albertel 5543: 
1.75      albertel 5544: #-------- end of section for handling grading scantron forms -------
                   5545: #
                   5546: #-------------------------------------------------------------------
                   5547: 
1.72      ng       5548: #-------------------------- Menu interface -------------------------
                   5549: #
                   5550: #--- Show a Grading Menu button - Calls the next routine ---
                   5551: sub show_grading_menu_form {
1.324     albertel 5552:     my ($symb)=@_;
1.125     ng       5553:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5554: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5555: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5556: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5557: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5558: 	'</form>'."\n";
                   5559:     return $result;
                   5560: }
                   5561: 
1.77      ng       5562: # -- Retrieve choices for grading form
                   5563: sub savedState {
                   5564:     my %savedState = ();
1.257     albertel 5565:     if ($env{'form.saveState'}) {
                   5566: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5567: 	    my ($key,$value) = split(/=/,$_,2);
                   5568: 	    $savedState{$key} = $value;
                   5569: 	}
                   5570:     }
                   5571:     return \%savedState;
                   5572: }
1.76      ng       5573: 
1.72      ng       5574: #--- Displays the main menu page -------
                   5575: sub gradingmenu {
                   5576:     my ($request) = @_;
1.324     albertel 5577:     my ($symb)=&get_symb($request);
1.72      ng       5578:     if (!$symb) {return '';}
1.76      ng       5579:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5580: 
                   5581:     $request->print(<<GRADINGMENUJS);
                   5582: <script type="text/javascript" language="javascript">
1.116     ng       5583:     function checkChoice(formname,val,cmdx) {
                   5584: 	if (val <= 2) {
                   5585: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5586: 	    var cmdsave = cmd;
1.116     ng       5587: 	} else {
                   5588: 	    cmd = cmdx;
1.118     ng       5589: 	    cmdsave = 'submission';
1.116     ng       5590: 	}
                   5591: 	formname.command.value = cmd;
1.118     ng       5592: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5593: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5594: 	if (val < 5) formname.submit();
                   5595: 	if (val == 5) {
1.72      ng       5596: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5597: 	    formname.submit();
                   5598: 	}
1.238     albertel 5599: 	if (val < 7) formname.submit();
1.72      ng       5600:     }
                   5601: 
                   5602:     function checkReceiptNo(formname,nospace) {
                   5603: 	var receiptNo = formname.receipt.value;
                   5604: 	var checkOpt = false;
                   5605: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5606: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5607: 	if (checkOpt) {
                   5608: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5609: 	    formname.receipt.value = "";
                   5610: 	    formname.receipt.focus();
                   5611: 	    return false;
                   5612: 	}
                   5613: 	return true;
                   5614:     }
                   5615: </script>
                   5616: GRADINGMENUJS
1.118     ng       5617:     &commonJSfunctions($request);
                   5618:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
1.324     albertel 5619:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       5620:     $result.=$table;
1.76      ng       5621:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       5622:     my $savedState = &savedState();
1.118     ng       5623:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       5624:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       5625:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       5626:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       5627: 
                   5628:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   5629: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   5630: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   5631: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       5632: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       5633: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       5634: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       5635: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   5636: 
1.326     albertel 5637:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   5638: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       5639: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       5640: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   5641: 
1.326     albertel 5642:     $result.='<table width="100%" border="0">';
1.116     ng       5643:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 5644: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       5645:     if (ref($sections)) {
1.155     albertel 5646: 	foreach (sort (@$sections)) {
                   5647: 	    $result.='<option value="'.$_.'" '.
                   5648: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   5649: 	}
1.116     ng       5650:     }
1.238     albertel 5651:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       5652: 
1.167     sakharuk 5653:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       5654: 
1.116     ng       5655:     $result.='</td></tr>';
                   5656: 
1.288     albertel 5657:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       5658: 	'<input type="radio" name="radioChoice" value="submission" '.
1.326     albertel 5659: 	($saveCmd eq 'submission' ? 'checked' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 5660: 	'</label> <select name="submitonly">'.
1.145     albertel 5661: 	'<option value="yes" '.
1.326     albertel 5662: 	($saveSub eq 'yes' ? 'selected="on"' : '').' />'.&mt('with submissions').'</option>'.
1.301     albertel 5663: 	'<option value="queued" '.
1.326     albertel 5664: 	($saveSub eq 'queued' ? 'selected="on"' : '').' />'.&mt('in grading queue').'</option>'.
1.145     albertel 5665: 	'<option value="graded" '.
1.326     albertel 5666: 	($saveSub eq 'graded' ? 'selected="on"' : '').' />'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 5667: 	'<option value="incorrect" '.
1.326     albertel 5668: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').' />'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 5669: 	'<option value="all" '.
1.326     albertel 5670: 	($saveSub eq 'all' ? 'selected="on"' : '').' />'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       5671: 
1.116     ng       5672:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 5673: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.326     albertel 5674: 	($saveCmd eq 'viewgrades' ? 'checked' : '').' /> '.
1.288     albertel 5675: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       5676: 
1.118     ng       5677:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 5678: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.326     albertel 5679: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').' /> '.
1.288     albertel 5680: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       5681: 
1.116     ng       5682:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       5683: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       5684: 	'</td></tr></table>'."\n";
                   5685: 
                   5686:     $result.='</td><td valign="top">';
                   5687: 
1.326     albertel 5688:     $result.='<table width="100%" border="0">';
1.116     ng       5689:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      5690: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   5691: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       5692: 
1.75      albertel 5693:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       5694: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      5695: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 5696: 
1.257     albertel 5697:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       5698: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      5699: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   5700: 	    ' '.&mt('receipt').': '.
1.257     albertel 5701: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 5702: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       5703: 	    '</td></tr>'."\n";
                   5704:     } 
1.238     albertel 5705:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5706: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   5707: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 5708:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5709: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   5710: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       5711: 
1.116     ng       5712:     $result.='</form></td></tr></table>'."\n".
1.72      ng       5713: 	'</td></tr></table>'."\n".
                   5714: 	'</td></tr></table>'."\n";
1.44      ng       5715:     return $result;
1.2       albertel 5716: }
                   5717: 
1.285     albertel 5718: sub reset_perm {
                   5719:     undef(%perm);
                   5720: }
                   5721: 
                   5722: sub init_perm {
                   5723:     &reset_perm();
1.300     albertel 5724:     foreach my $test_perm ('vgr','mgr','opa') {
                   5725: 
                   5726: 	my $scope = $env{'request.course.id'};
                   5727: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   5728: 
                   5729: 	    $scope .= '/'.$env{'request.course.sec'};
                   5730: 	    if ( $perm{$test_perm}=
                   5731: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   5732: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   5733: 	    } else {
                   5734: 		delete($perm{$test_perm});
                   5735: 	    }
1.285     albertel 5736: 	}
                   5737:     }
                   5738: }
                   5739: 
1.1       albertel 5740: sub handler {
1.41      ng       5741:     my $request=$_[0];
1.102     albertel 5742: 
1.285     albertel 5743:     &reset_perm();
1.257     albertel 5744:     if ($env{'browser.mathml'}) {
1.141     www      5745: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       5746:     } else {
1.141     www      5747: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       5748:     }
                   5749:     $request->send_http_header;
1.44      ng       5750:     return '' if $request->header_only;
1.41      ng       5751:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 5752:     my $symb=&get_symb($request,1);
1.160     albertel 5753:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   5754:     my $command=$commands[0];
                   5755:     if ($#commands > 0) {
                   5756: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   5757:     }
1.41      ng       5758:     &send_header($request);
1.324     albertel 5759:     if ($symb eq '' && $command eq '') {
1.257     albertel 5760: 	if ($env{'user.adv'}) {
                   5761: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   5762: 		($env{'form.codethree'})) {
                   5763: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   5764: 		    $env{'form.codethree'};
1.41      ng       5765: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   5766: 		    &Apache::lonnet::checkin($token);
                   5767: 		if ($tsymb) {
1.137     albertel 5768: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       5769: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 5770: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   5771: 					  ('grade_username' => $tuname,
                   5772: 					   'grade_domain' => $tudom,
                   5773: 					   'grade_courseid' => $tcrsid,
                   5774: 					   'grade_symb' => $tsymb)));
1.41      ng       5775: 		    } else {
1.45      ng       5776: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 5777: 		    }
1.41      ng       5778: 		} else {
1.45      ng       5779: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       5780: 		}
1.14      www      5781: 	    } else {
1.41      ng       5782: 		$request->print(&Apache::lonxml::tokeninputfield());
                   5783: 	    }
                   5784: 	}
                   5785:     } else {
1.285     albertel 5786: 	&init_perm();
1.104     albertel 5787: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 5788: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 5789: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       5790: 	    &pickStudentPage($request);
1.103     albertel 5791: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       5792: 	    &displayPage($request);
1.104     albertel 5793: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       5794: 	    &updateGradeByPage($request);
1.104     albertel 5795: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       5796: 	    &processGroup($request);
1.104     albertel 5797: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       5798: 	    $request->print(&gradingmenu($request));
1.104     albertel 5799: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       5800: 	    $request->print(&viewgrades($request));
1.104     albertel 5801: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       5802: 	    $request->print(&processHandGrade($request));
1.106     albertel 5803: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       5804: 	    $request->print(&editgrades($request));
1.106     albertel 5805: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       5806: 	    $request->print(&verifyreceipt($request));
1.106     albertel 5807: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       5808: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 5809: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       5810: 	    $request->print(&csvupload($request));
1.106     albertel 5811: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       5812: 	    $request->print(&csvuploadmap($request));
1.246     albertel 5813: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 5814: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 5815: 		$request->print(&csvuploadoptions($request));
1.41      ng       5816: 	    } else {
1.257     albertel 5817: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   5818: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       5819: 		} else {
1.257     albertel 5820: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       5821: 		}
                   5822: 		$request->print(&csvuploadmap($request));
                   5823: 	    }
1.246     albertel 5824: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   5825: 	    $request->print(&csvuploadassign($request));
1.106     albertel 5826: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 5827: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 5828:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   5829:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 5830: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   5831: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 5832: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 5833: 	    $request->print(&scantron_process_students($request));
1.157     albertel 5834:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 5835:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   5836: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 5837:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 5838:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 5839:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   5840: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 5841:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 5842:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 5843: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 5844:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 5845: 	} elsif ($command) {
1.157     albertel 5846: 	    $request->print("Access Denied ($command)");
1.26      albertel 5847: 	}
1.2       albertel 5848:     }
1.41      ng       5849:     &send_footer($request);
1.44      ng       5850:     return '';
                   5851: }
                   5852: 
                   5853: sub send_header {
                   5854:     my ($request)= @_;
                   5855:     $request->print(&Apache::lontexconvert::header());
                   5856: #  $request->print("
                   5857: #<script>
                   5858: #remotewindow=open('','homeworkremote');
                   5859: #remotewindow.close();
                   5860: #</script>"); 
1.47      www      5861:     $request->print(&Apache::loncommon::bodytag('Grading'));
1.157     albertel 5862:     $request->rflush();
1.44      ng       5863: }
                   5864: 
                   5865: sub send_footer {
                   5866:     my ($request)= @_;
1.212     albertel 5867:     $request->print('</body></html>');
1.1       albertel 5868: }
                   5869: 
                   5870: 1;
                   5871: 
1.13      albertel 5872: __END__;

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