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

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

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