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

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

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