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

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

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