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

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

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