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

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

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