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

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

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