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

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

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