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

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

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