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

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

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