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

1.17      albertel    1: # The LearningOnline Network with CAPA
1.13      albertel    2: # The LON-CAPA Grading handler
1.17      albertel    3: #
1.352   ! albertel    4: # $Id: grades.pm,v 1.351 2006/04/11 20:51:46 albertel Exp $
1.17      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: package Apache::grades;
                     30: use strict;
                     31: use Apache::style;
                     32: use Apache::lonxml;
                     33: use Apache::lonnet;
1.3       albertel   34: use Apache::loncommon;
1.112     ng         35: use Apache::lonhtmlcommon;
1.68      ng         36: use Apache::lonnavmaps;
1.1       albertel   37: use Apache::lonhomework;
1.55      matthew    38: use Apache::loncoursedata;
1.38      ng         39: use Apache::lonmsg qw(:user_normal_msg);
1.1       albertel   40: use Apache::Constants qw(:common);
1.167     sakharuk   41: use Apache::lonlocal;
1.170     albertel   42: use String::Similarity;
1.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.341     banghart 2445: 		    $directory =~ /^.+$stuname\/portfolio(.*)/;
                   2446: 		    my $portfolio_path = $1;
                   2447: 		    my @dir_list = &Apache::lonnet::dirlist($portfolio_path,$domain,$stuname,$portfolio_root);
1.338     banghart 2448: 		    my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.341     banghart 2449: 		    my $new_answer = &version_selected_portfile($domain, $stuname, $portfolio_path, $answer_file, $version);
1.338     banghart 2450:                     $$newrecord{"resource.$new_part.$resp_id.handback"} = $new_answer;
1.337     banghart 2451:                     # set the filename to match the submitted file name
                   2452:                     $env{'form.'.$newflg.'_'.$part_resp.'_returndoc1.filename'} = $env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter};
                   2453:                     my $result=&Apache::lonnet::userfileupload($newflg.'_'.$part_resp.'_returndoc'.$file_counter,'',
1.338     banghart 2454:             	    'portfolio',undef,undef,undef,$stuname,$domain);
1.337     banghart 2455:                     if ($result !~ m|^/uploaded/|) {
                   2456:                         $request->print('<font color="red"> An errror occured ('.$result.
                   2457:                         ') while trying to upload '.&display_file().'</font><br />');
                   2458:                     # $request->print(&done('Back'));
                   2459:                     }
                   2460:                     $request->print("<br />".$fname." will be the uploaded file name");
1.338     banghart 2461:                     $request->print("<font color=\"red\">Will upload document </font>".$env{'form.'.$newflg.'_'.$part_resp.'_origdoc'.$file_counter});
1.337     banghart 2462:                     $file_counter++;
                   2463:                 }
                   2464:             }
                   2465:         }
1.338     banghart 2466:     return;
1.337     banghart 2467: }
                   2468: 
1.313     banghart 2469: sub get_submitted_files {
                   2470:     my ($udom,$uname,$partid,$respid,$record) = @_;
                   2471:     my @files;
                   2472:     if ($$record{"resource.$partid.$respid.portfiles"}) {
                   2473:         my $file_url = '/uploaded/'.$udom.'/'.$uname.'/portfolio';
                   2474:         foreach my $file (split(',',$$record{"resource.$partid.$respid.portfiles"})) {
                   2475:     	    push(@files,$file_url.$file);
                   2476:         }
                   2477:     }
                   2478:     if ($$record{"resource.$partid.$respid.uploadedurl"}) {
                   2479:         push(@files,$$record{"resource.$partid.$respid.uploadedurl"});
                   2480:     }
                   2481:     return (\@files);
                   2482: }
1.322     albertel 2483: 
1.269     raeburn  2484: # ----------- Provides number of tries since last reset.
                   2485: sub get_num_tries {
                   2486:     my ($record,$last_reset,$part) = @_;
                   2487:     my $timestamp = '';
                   2488:     my $num_tries = 0;
                   2489:     if ($$record{'version'}) {
                   2490:         for (my $version=$$record{'version'};$version>=1;$version--) {
                   2491:             if (exists($$record{$version.':resource.'.$part.'.solved'})) {
                   2492:                 $timestamp = $$record{$version.':timestamp'};
                   2493:                 if ($timestamp > $last_reset) {
                   2494:                     $num_tries ++;
                   2495:                 } else {
                   2496:                     last;
                   2497:                 }
                   2498:             }
                   2499:         }
                   2500:     }
                   2501:     return $num_tries;
                   2502: }
                   2503: 
                   2504: # ----------- Determine decrements required in aggregate totals 
                   2505: sub decrement_aggs {
                   2506:     my ($symb,$part,$aggregate,$aggtries,$totaltries,$solvedstatus) = @_;
                   2507:     my %decrement = (
                   2508:                         attempts => 0,
                   2509:                         users => 0,
                   2510:                         correct => 0
                   2511:                     );
                   2512:     $decrement{'attempts'} = $aggtries;
                   2513:     if ($solvedstatus =~ /^correct/) {
                   2514:         $decrement{'correct'} = 1;
                   2515:     }
                   2516:     if ($aggtries == $totaltries) {
                   2517:         $decrement{'users'} = 1;
                   2518:     }
                   2519:     foreach my $type (keys (%decrement)) {
                   2520:         $$aggregate{$symb."\0".$part."\0".$type} = -$decrement{$type};
                   2521:     }
                   2522:     return;
                   2523: }
                   2524: 
                   2525: # ----------- Determine timestamps for last reset of aggregate totals for parts  
                   2526: sub get_last_resets {
1.270     albertel 2527:     my ($symb,$courseid,$partids) =@_;
                   2528:     my %last_resets;
1.269     raeburn  2529:     my $cdom = $env{'course.'.$courseid.'.domain'};
                   2530:     my $cname = $env{'course.'.$courseid.'.num'};
1.271     albertel 2531:     my @keys;
                   2532:     foreach my $part (@{$partids}) {
                   2533: 	push(@keys,"$symb\0$part\0resettime");
                   2534:     }
                   2535:     my %results=&Apache::lonnet::get('nohist_resourcetracker',\@keys,
                   2536: 				     $cdom,$cname);
                   2537:     foreach my $part (@{$partids}) {
                   2538: 	$last_resets{$part}=$results{"$symb\0$part\0resettime"};
1.269     raeburn  2539:     }
1.270     albertel 2540:     return %last_resets;
1.269     raeburn  2541: }
                   2542: 
1.251     banghart 2543: # ----------- Handles creating versions for portfolio files as answers
                   2544: sub version_portfiles {
1.343     banghart 2545:     my ($record, $parts_graded, $courseid, $symb, $domain, $stu_name, $v_flag) = @_;
1.263     banghart 2546:     my $version_parts = join('|',@$v_flag);
1.343     banghart 2547:     my @returned_keys;
1.255     banghart 2548:     my $parts = join('|', @$parts_graded);
1.252     banghart 2549:     my $portfolio_root = &Apache::loncommon::propath($domain,
1.306     banghart 2550: 						 $stu_name).
1.252     banghart 2551: 						'/userfiles/portfolio';
1.277     albertel 2552:     foreach my $key (keys(%$record)) {
1.259     banghart 2553:         my $new_portfiles;
1.263     banghart 2554:         if ($key =~ /^resource\.($version_parts)\./ && $key =~ /\.portfiles$/ ) {
1.342     banghart 2555:             my @versioned_portfiles;
1.255     banghart 2556:             my @portfiles = split(/,/,$$record{$key});
1.252     banghart 2557:             foreach my $file (@portfiles) {
1.306     banghart 2558:                 &Apache::lonnet::unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
1.304     albertel 2559:                 my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   2560: 		my ($answer_name,$answer_ver,$answer_ext) =
                   2561: 		    &file_name_version_ext($answer_file);
1.306     banghart 2562:                 my @dir_list = &Apache::lonnet::dirlist($directory,$domain,$stu_name,$portfolio_root);
1.342     banghart 2563:                 my $version = &get_next_version($answer_name, $answer_ext, \@dir_list);
1.306     banghart 2564:                 my $new_answer = &version_selected_portfile($domain, $stu_name, $directory, $answer_file, $version);
                   2565:                 if ($new_answer ne 'problem getting file') {
1.342     banghart 2566:                     push(@versioned_portfiles, $directory.$new_answer);
1.306     banghart 2567:                     &Apache::lonnet::mark_as_readonly($domain,$stu_name,
                   2568:                         ['/portfolio'.$directory.$new_answer],
                   2569:                         [$symb,$env{'request.course.id'},'graded']);
1.259     banghart 2570:                 }
1.252     banghart 2571:             }
1.343     banghart 2572:             $$record{$key} = join(',',@versioned_portfiles);
                   2573:             push(@returned_keys,$key);
1.251     banghart 2574:         }
                   2575:     } 
1.343     banghart 2576:     return (@returned_keys);   
1.305     banghart 2577: }
                   2578: 
1.307     banghart 2579: sub get_next_version {
1.341     banghart 2580:     my ($answer_name, $answer_ext, $dir_list) = @_;
1.307     banghart 2581:     my $version;
                   2582:     foreach my $row (@$dir_list) {
                   2583:         my ($file) = split(/\&/,$row,2);
                   2584:         my ($file_name,$file_version,$file_ext) =
                   2585: 	    &file_name_version_ext($file);
                   2586:         if (($file_name eq $answer_name) && 
                   2587: 	    ($file_ext eq $answer_ext)) {
                   2588:                 # gets here if filename and extension match, regardless of version
                   2589:                 if ($file_version ne '') {
                   2590:                 # a versioned file is found  so save it for later
                   2591:                 if ($file_version > $version) {
                   2592: 		    $version = $file_version;
                   2593: 	        }
                   2594:             }
                   2595:         }
                   2596:     } 
                   2597:     $version ++;
                   2598:     return($version);
                   2599: }
                   2600: 
1.305     banghart 2601: sub version_selected_portfile {
1.306     banghart 2602:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   2603:     my ($answer_name,$answer_ver,$answer_ext) =
                   2604:         &file_name_version_ext($file_name);
                   2605:     my $new_answer;
                   2606:     $env{'form.copy'} = &Apache::lonnet::getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   2607:     if($env{'form.copy'} eq '-1') {
                   2608:         &Apache::lonnet::logthis('problem getting file '.$file_name);
                   2609:         $new_answer = 'problem getting file';
                   2610:     } else {
                   2611:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   2612:         my $copy_result = &Apache::lonnet::finishuserfileupload(
                   2613:                             $stu_name,$domain,'copy',
                   2614: 		        '/portfolio'.$directory.$new_answer);
                   2615:     }    
                   2616:     return ($new_answer);
1.251     banghart 2617: }
                   2618: 
1.304     albertel 2619: sub file_name_version_ext {
                   2620:     my ($file)=@_;
                   2621:     my @file_parts = split(/\./, $file);
                   2622:     my ($name,$version,$ext);
                   2623:     if (@file_parts > 1) {
                   2624: 	$ext=pop(@file_parts);
                   2625: 	if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   2626: 	    $version=pop(@file_parts);
                   2627: 	}
                   2628: 	$name=join('.',@file_parts);
                   2629:     } else {
                   2630: 	$name=join('.',@file_parts);
                   2631:     }
                   2632:     return($name,$version,$ext);
                   2633: }
                   2634: 
1.44      ng       2635: #--------------------------------------------------------------------------------------
                   2636: #
                   2637: #-------------------------- Next few routines handles grading by section or whole class
                   2638: #
                   2639: #--- Javascript to handle grading by section or whole class
1.42      ng       2640: sub viewgrades_js {
                   2641:     my ($request) = shift;
                   2642: 
1.41      ng       2643:     $request->print(<<VIEWJAVASCRIPT);
                   2644: <script type="text/javascript" language="javascript">
1.45      ng       2645:    function writePoint(partid,weight,point) {
1.125     ng       2646: 	var radioButton = document.classgrade["RADVAL_"+partid];
                   2647: 	var textbox = document.classgrade["TEXTVAL_"+partid];
1.42      ng       2648: 	if (point == "textval") {
1.125     ng       2649: 	    point = document.classgrade["TEXTVAL_"+partid].value;
1.109     matthew  2650: 	    if (isNaN(point) || parseFloat(point) < 0) {
                   2651: 		alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.42      ng       2652: 		var resetbox = false;
                   2653: 		for (var i=0; i<radioButton.length; i++) {
                   2654: 		    if (radioButton[i].checked) {
                   2655: 			textbox.value = i;
                   2656: 			resetbox = true;
                   2657: 		    }
                   2658: 		}
                   2659: 		if (!resetbox) {
                   2660: 		    textbox.value = "";
                   2661: 		}
                   2662: 		return;
                   2663: 	    }
1.109     matthew  2664: 	    if (parseFloat(point) > parseFloat(weight)) {
                   2665: 		var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2666: 				   ") greater than the weight for the part. Accept?");
                   2667: 		if (resp == false) {
                   2668: 		    textbox.value = "";
                   2669: 		    return;
                   2670: 		}
                   2671: 	    }
1.42      ng       2672: 	    for (var i=0; i<radioButton.length; i++) {
                   2673: 		radioButton[i].checked=false;
1.109     matthew  2674: 		if (parseFloat(point) == i) {
1.42      ng       2675: 		    radioButton[i].checked=true;
                   2676: 		}
                   2677: 	    }
1.41      ng       2678: 
1.42      ng       2679: 	} else {
1.125     ng       2680: 	    textbox.value = parseFloat(point);
1.42      ng       2681: 	}
1.41      ng       2682: 	for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2683: 	    var user = document.classgrade["ctr"+i].value;
1.289     albertel 2684: 	    user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2685: 	    var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2686: 	    var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2687: 	    var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2688: 	    if (saveval != "correct") {
                   2689: 		scorename.value = point;
1.43      ng       2690: 		if (selname[0].selected != true) {
                   2691: 		    selname[0].selected = true;
                   2692: 		}
1.42      ng       2693: 	    }
                   2694: 	}
1.125     ng       2695: 	document.classgrade["SELVAL_"+partid][0].selected = true;
1.42      ng       2696:     }
                   2697: 
                   2698:     function writeRadText(partid,weight) {
1.125     ng       2699: 	var selval   = document.classgrade["SELVAL_"+partid];
                   2700: 	var radioButton = document.classgrade["RADVAL_"+partid];
1.265     www      2701:         var override = document.classgrade["FORCE_"+partid].checked;
1.125     ng       2702: 	var textbox = document.classgrade["TEXTVAL_"+partid];
                   2703: 	if (selval[1].selected || selval[2].selected) {
1.42      ng       2704: 	    for (var i=0; i<radioButton.length; i++) {
                   2705: 		radioButton[i].checked=false;
                   2706: 
                   2707: 	    }
                   2708: 	    textbox.value = "";
                   2709: 
                   2710: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2711: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2712: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2713: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2714: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2715: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2716: 		if ((saveval != "correct") || override) {
1.42      ng       2717: 		    scorename.value = "";
1.125     ng       2718: 		    if (selval[1].selected) {
                   2719: 			selname[1].selected = true;
                   2720: 		    } else {
                   2721: 			selname[2].selected = true;
                   2722: 			if (Number(document.classgrade["GD_"+user+"_"+partid+"_tries"].value)) 
                   2723: 			{document.classgrade["GD_"+user+"_"+partid+"_tries"].value = '0';}
                   2724: 		    }
1.42      ng       2725: 		}
                   2726: 	    }
1.43      ng       2727: 	} else {
                   2728: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2729: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2730: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2731: 		var scorename = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2732: 		var saveval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2733: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.265     www      2734: 		if ((saveval != "correct") || override) {
1.125     ng       2735: 		    scorename.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
1.43      ng       2736: 		    selname[0].selected = true;
                   2737: 		}
                   2738: 	    }
                   2739: 	}	    
1.42      ng       2740:     }
                   2741: 
                   2742:     function changeSelect(partid,user) {
1.125     ng       2743: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2744: 	var textbox = document.classgrade["GD_"+user+'_'+partid+"_awarded"];
1.44      ng       2745: 	var point  = textbox.value;
1.125     ng       2746: 	var weight = document.classgrade["weight_"+partid].value;
1.44      ng       2747: 
1.109     matthew  2748: 	if (isNaN(point) || parseFloat(point) < 0) {
                   2749: 	    alert("A number equal or greater than 0 is expected. Entered value = "+parseFloat(point));
1.44      ng       2750: 	    textbox.value = "";
                   2751: 	    return;
                   2752: 	}
1.109     matthew  2753: 	if (parseFloat(point) > parseFloat(weight)) {
                   2754: 	    var resp = confirm("You entered a value ("+parseFloat(point)+
1.44      ng       2755: 			       ") greater than the weight of the part. Accept?");
                   2756: 	    if (resp == false) {
                   2757: 		textbox.value = "";
                   2758: 		return;
                   2759: 	    }
                   2760: 	}
1.42      ng       2761: 	selval[0].selected = true;
                   2762:     }
                   2763: 
                   2764:     function changeOneScore(partid,user) {
1.125     ng       2765: 	var selval = document.classgrade["GD_"+user+'_'+partid+"_solved"];
                   2766: 	if (selval[1].selected || selval[2].selected) {
                   2767: 	    document.classgrade["GD_"+user+'_'+partid+"_awarded"].value = "";
                   2768: 	    if (selval[2].selected) {
                   2769: 		document.classgrade["GD_"+user+'_'+partid+"_tries"].value = "0";
                   2770: 	    }
1.269     raeburn  2771:         }
1.42      ng       2772:     }
                   2773: 
                   2774:     function resetEntry(numpart) {
                   2775: 	for (ctpart=0;ctpart<numpart;ctpart++) {
1.125     ng       2776: 	    var partid = document.classgrade["partid_"+ctpart].value;
                   2777: 	    var radioButton = document.classgrade["RADVAL_"+partid];
                   2778: 	    var textbox = document.classgrade["TEXTVAL_"+partid];
                   2779: 	    var selval  = document.classgrade["SELVAL_"+partid];
1.42      ng       2780: 	    for (var i=0; i<radioButton.length; i++) {
                   2781: 		radioButton[i].checked=false;
                   2782: 
                   2783: 	    }
                   2784: 	    textbox.value = "";
                   2785: 	    selval[0].selected = true;
                   2786: 
                   2787: 	    for (i=0;i<document.classgrade.total.value;i++) {
1.125     ng       2788: 		var user = document.classgrade["ctr"+i].value;
1.289     albertel 2789: 		user = user.replace(new RegExp(':', 'g'),"_");
1.125     ng       2790: 		var resetscore = document.classgrade["GD_"+user+"_"+partid+"_awarded"];
                   2791: 		resetscore.value = document.classgrade["GD_"+user+"_"+partid+"_awarded_s"].value;
                   2792: 		var resettries = document.classgrade["GD_"+user+"_"+partid+"_tries"];
                   2793: 		resettries.value = document.classgrade["GD_"+user+"_"+partid+"_tries_s"].value;
                   2794: 		var saveselval   = document.classgrade["GD_"+user+"_"+partid+"_solved_s"].value;
                   2795: 		var selname   = document.classgrade["GD_"+user+"_"+partid+"_solved"];
1.42      ng       2796: 		if (saveselval == "excused") {
1.43      ng       2797: 		    if (selname[1].selected == false) { selname[1].selected = true;}
1.42      ng       2798: 		} else {
1.43      ng       2799: 		    if (selname[0].selected == false) {selname[0].selected = true};
1.42      ng       2800: 		}
                   2801: 	    }
1.41      ng       2802: 	}
1.42      ng       2803:     }
                   2804: 
1.41      ng       2805: </script>
                   2806: VIEWJAVASCRIPT
1.42      ng       2807: }
                   2808: 
1.44      ng       2809: #--- show scores for a section or whole class w/ option to change/update a score
1.42      ng       2810: sub viewgrades {
                   2811:     my ($request) = shift;
                   2812:     &viewgrades_js($request);
1.41      ng       2813: 
1.324     albertel 2814:     my ($symb) = &get_symb($request);
1.168     albertel 2815:     #need to make sure we have the correct data for later EXT calls, 
                   2816:     #thus invalidate the cache
                   2817:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 2818:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   2819:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 2820:     &Apache::lonnet::clear_EXT_cache_status();
                   2821: 
1.167     sakharuk 2822:     my $result='<h3><font color="#339933">'.&mt('Manual Grading').'</font></h3>';
1.257     albertel 2823:     $result.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font>'."\n";
1.41      ng       2824: 
                   2825:     #view individual student submission form - called using Javascript viewOneStudent
1.324     albertel 2826:     $result.=&jscriptNform($symb);
1.41      ng       2827: 
1.44      ng       2828:     #beginning of class grading form
1.41      ng       2829:     $result.= '<form action="/adm/grades" method="post" name="classgrade">'."\n".
1.106     albertel 2830: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.38      ng       2831: 	'<input type="hidden" name="command" value="editgrades" />'."\n".
1.257     albertel 2832: 	'<input type="hidden" name="section" value="'.$env{'form.section'}.'" />'."\n".
                   2833: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   2834: 	'<input type="hidden" name="Status" value="'.$env{'form.Status'}.'" />'."\n".
                   2835: 	'<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.72      ng       2836: 
1.126     ng       2837:     my $sectionClass;
1.257     albertel 2838:     if ($env{'form.section'} eq 'all') {
1.126     ng       2839: 	$sectionClass='Class </h3>';
1.257     albertel 2840:     } elsif ($env{'form.section'} eq 'none') {
1.126     ng       2841: 	$sectionClass='Students in no Section </h3>';
1.52      albertel 2842:     } else {
1.257     albertel 2843: 	$sectionClass='Students in Section '.$env{'form.section'}.'</h3>';
1.52      albertel 2844:     }
1.126     ng       2845:     $result.='<h3>Assign Common Grade To '.$sectionClass;
1.52      albertel 2846:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
                   2847: 	'<table border=0><tr bgcolor="#ffffdd"><td>';
1.44      ng       2848:     #radio buttons/text box for assigning points for a section or class.
                   2849:     #handles different parts of a problem
1.324     albertel 2850:     my ($partlist,$handgrade) = &response_type($symb);
1.42      ng       2851:     my %weight = ();
                   2852:     my $ctsparts = 0;
1.41      ng       2853:     $result.='<table border="0">';
1.45      ng       2854:     my %seen = ();
1.42      ng       2855:     for (sort keys(%$handgrade)) {
1.54      albertel 2856: 	my ($partid,$respid) = split (/_/,$_,2);
1.45      ng       2857: 	next if $seen{$partid};
                   2858: 	$seen{$partid}++;
1.147     albertel 2859: 	my $handgrade=$$handgrade{$_};
1.42      ng       2860: 	my $wgt = &Apache::lonnet::EXT('resource.'.$partid.'.weight',$symb);
                   2861: 	$weight{$partid} = $wgt eq '' ? '1' : $wgt;
                   2862: 
1.44      ng       2863: 	$result.='<input type="hidden" name="partid_'.
                   2864: 	    $ctsparts.'" value="'.$partid.'" />'."\n";
                   2865: 	$result.='<input type="hidden" name="weight_'.
                   2866: 	    $partid.'" value="'.$weight{$partid}.'" />'."\n";
1.324     albertel 2867: 	my $display_part=&get_display_part($partid,$symb);
1.207     albertel 2868: 	$result.='<tr><td><b>Part:</b> '.$display_part.'&nbsp; &nbsp;<b>Point:</b> </td><td>';
1.42      ng       2869: 	$result.='<table border="0"><tr>';  
1.41      ng       2870: 	my $ctr = 0;
1.42      ng       2871: 	while ($ctr<=$weight{$partid}) { # display radio buttons in a nice table 10 across
1.288     albertel 2872: 	    $result.= '<td><label><input type="radio" name="RADVAL_'.$partid.'" '.
1.54      albertel 2873: 		'onclick="javascript:writePoint(\''.$partid.'\','.$weight{$partid}.
1.288     albertel 2874: 		','.$ctr.')" />'.$ctr."</label></td>\n";
1.41      ng       2875: 	    $result.=(($ctr+1)%10 == 0 ? '</tr><tr>' : '');
                   2876: 	    $ctr++;
                   2877: 	}
                   2878: 	$result.='</tr></table>';
1.44      ng       2879: 	$result.= '</td><td><b> or </b><input type="text" name="TEXTVAL_'.
1.54      albertel 2880: 	    $partid.'" size="4" '.'onChange="javascript:writePoint(\''.
                   2881: 		$partid.'\','.$weight{$partid}.',\'textval\')" /> /'.
1.42      ng       2882: 	    $weight{$partid}.' (problem weight)</td>'."\n";
                   2883: 	$result.= '</td><td><select name="SELVAL_'.$partid.'"'.
1.54      albertel 2884: 	    'onChange="javascript:writeRadText(\''.$partid.'\','.
1.59      albertel 2885: 		$weight{$partid}.')"> '.
1.42      ng       2886: 	    '<option selected="on"> </option>'.
1.125     ng       2887: 	    '<option>excused</option>'.
1.265     www      2888: 	    '<option>reset status</option></select></td>'.
1.266     albertel 2889:             '<td><label><input type="checkbox" name="FORCE_'.$partid.'" /> Override "Correct"</label></td></tr>'."\n";
1.42      ng       2890: 	$ctsparts++;
1.41      ng       2891:     }
1.52      albertel 2892:     $result.='</table>'.'</td></tr></table>'.'</td></tr></table>'."\n".
                   2893: 	'<input type="hidden" name="totalparts" value="'.$ctsparts.'" />';
1.42      ng       2894:     $result.='<input type="button" value="Reset" '.
1.111     ng       2895: 	'onClick="javascript:resetEntry('.$ctsparts.');" TARGET=_self>';
1.41      ng       2896: 
1.44      ng       2897:     #table listing all the students in a section/class
                   2898:     #header of table
1.126     ng       2899:     $result.= '<h3>Assign Grade to Specific Students in '.$sectionClass;
1.42      ng       2900:     $result.= '<table border=0><tr><td bgcolor="#777777">'."\n".
1.126     ng       2901: 	'<table border=0><tr bgcolor="#deffff"><td>&nbsp;<b>No.</b>&nbsp;</td>'.
1.129     ng       2902: 	'<td>'.&nameUserString('header')."</td>\n";
1.324     albertel 2903:     my (@parts) = sort(&getpartlist($symb));
                   2904:     my (undef,undef,$url)=&Apache::lonnet::decode_symb($symb);
1.269     raeburn  2905:     my @partids = ();
1.41      ng       2906:     foreach my $part (@parts) {
                   2907: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
1.126     ng       2908: 	$display =~ s|^Number of Attempts|Tries<br />|; # makes the column narrower
1.41      ng       2909: 	if  (!$display) { $display = &Apache::lonnet::metadata($url,$part.'.name'); }
1.207     albertel 2910: 	my ($partid) = &split_part_type($part);
1.269     raeburn  2911:         push(@partids, $partid);
1.324     albertel 2912: 	my $display_part=&get_display_part($partid,$symb);
1.41      ng       2913: 	if ($display =~ /^Partial Credit Factor/) {
1.207     albertel 2914: 	    $result.='<td><b>Score Part:</b> '.$display_part.
                   2915: 		' <br /><b>(weight = '.$weight{$partid}.')</b></td>'."\n";
1.41      ng       2916: 	    next;
1.207     albertel 2917: 	} else {
                   2918: 	    $display =~s/\[Part: \Q$partid\E\]/Part:<\/b> $display_part/;
1.41      ng       2919: 	}
1.53      albertel 2920: 	$display =~ s|Problem Status|Grade Status<br />|;
1.207     albertel 2921: 	$result.='<td><b>'.$display.'</td>'."\n";
1.41      ng       2922:     }
                   2923:     $result.='</tr>';
1.44      ng       2924: 
1.270     albertel 2925:     my %last_resets = 
                   2926: 	&get_last_resets($symb,$env{'request.course.id'},\@partids);
1.269     raeburn  2927: 
1.41      ng       2928:     #get info for each student
1.44      ng       2929:     #list all the students - with points and grade status
1.257     albertel 2930:     my (undef,undef,$fullname) = &getclasslist($env{'form.section'},'1');
1.41      ng       2931:     my $ctr = 0;
1.294     albertel 2932:     foreach (sort 
                   2933: 	     {
                   2934: 		 if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   2935: 		     return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   2936: 		 }
                   2937: 		 return $a cmp $b;
                   2938: 	     } (keys(%$fullname))) {
1.126     ng       2939: 	$ctr++;
1.324     albertel 2940: 	$result.=&viewstudentgrade($symb,$env{'request.course.id'},
1.269     raeburn  2941: 				   $_,$$fullname{$_},\@parts,\%weight,$ctr,\%last_resets);
1.41      ng       2942:     }
                   2943:     $result.='</table></td></tr></table>';
                   2944:     $result.='<input type="hidden" name="total" value="'.$ctr.'" />'."\n";
1.126     ng       2945:     $result.='<input type="button" value="Save" '.
1.45      ng       2946: 	'onClick="javascript:submit();" TARGET=_self /></form>'."\n";
1.96      albertel 2947:     if (scalar(%$fullname) eq 0) {
                   2948: 	my $colspan=3+scalar(@parts);
1.257     albertel 2949: 	$result='<font color="red">There are no students in section "'.$env{'form.section'}.
                   2950: 	    '" with enrollment status "'.$env{'form.Status'}.'" to modify or grade.</font>';
1.96      albertel 2951:     }
1.324     albertel 2952:     $result.=&show_grading_menu_form($symb);
1.41      ng       2953:     return $result;
                   2954: }
                   2955: 
1.44      ng       2956: #--- call by previous routine to display each student
1.41      ng       2957: sub viewstudentgrade {
1.324     albertel 2958:     my ($symb,$courseid,$student,$fullname,$parts,$weight,$ctr,$last_resets) = @_;
1.44      ng       2959:     my ($uname,$udom) = split(/:/,$student);
                   2960:     my %record=&Apache::lonnet::restore($symb,$courseid,$udom,$uname);
1.269     raeburn  2961:     my %aggregates = (); 
1.233     albertel 2962:     my $result='<tr bgcolor="#ffffdd"><td align="right">'.
                   2963: 	'<input type="hidden" name="ctr'.($ctr-1).'" value="'.$student.'" />'.
                   2964: 	"\n".$ctr.'&nbsp;</td><td>&nbsp;'.
1.44      ng       2965: 	'<a href="javascript:viewOneStudent(\''.$uname.'\',\''.$udom.
1.112     ng       2966: 	'\')"; TARGET=_self>'.$fullname.'</a> '.
1.257     albertel 2967: 	'<font color="#999999">('.$uname.($env{'user.domain'} eq $udom ? '' : ':'.$udom).')</font></td>'."\n";
1.281     albertel 2968:     $student=~s/:/_/; # colon doen't work in javascript for names
1.63      albertel 2969:     foreach my $apart (@$parts) {
                   2970: 	my ($part,$type) = &split_part_type($apart);
1.41      ng       2971: 	my $score=$record{"resource.$part.$type"};
1.276     albertel 2972:         $result.='<td align="center">';
1.269     raeburn  2973:         my ($aggtries,$totaltries);
                   2974:         unless (exists($aggregates{$part})) {
1.270     albertel 2975: 	    $totaltries = $record{'resource.'.$part.'.tries'};
                   2976: 
                   2977: 	    $aggtries = $totaltries;
1.269     raeburn  2978:             if ($$last_resets{$part}) {  
1.270     albertel 2979:                 $aggtries = &get_num_tries(\%record,$$last_resets{$part},
                   2980: 					   $part);
                   2981:             }
1.269     raeburn  2982:             $result.='<input type="hidden" name="'.
                   2983:                 'GD_'.$student.'_'.$part.'_aggtries" value="'.$aggtries.'" />'."\n";
                   2984:             $result.='<input type="hidden" name="'.
                   2985:                 'GD_'.$student.'_'.$part.'_totaltries" value="'.$totaltries.'" />'."\n";
                   2986:             $aggregates{$part} = 1;
                   2987:         }
1.41      ng       2988: 	if ($type eq 'awarded') {
1.320     albertel 2989: 	    my $pts = $score eq '' ? '' : &compute_points($score,$$weight{$part});
1.42      ng       2990: 	    $result.='<input type="hidden" name="'.
1.89      albertel 2991: 		'GD_'.$student.'_'.$part.'_awarded_s" value="'.$pts.'" />'."\n";
1.233     albertel 2992: 	    $result.='<input type="text" name="'.
1.89      albertel 2993: 		'GD_'.$student.'_'.$part.'_awarded" '.
                   2994: 		'onChange="javascript:changeSelect(\''.$part.'\',\''.$student.
1.44      ng       2995: 		'\')" value="'.$pts.'" size="4" /></td>'."\n";
1.41      ng       2996: 	} elsif ($type eq 'solved') {
                   2997: 	    my ($status,$foo)=split(/_/,$score,2);
                   2998: 	    $status = 'nothing' if ($status eq '');
1.89      albertel 2999: 	    $result.='<input type="hidden" name="'.'GD_'.$student.'_'.
1.54      albertel 3000: 		$part.'_solved_s" value="'.$status.'" />'."\n";
1.233     albertel 3001: 	    $result.='&nbsp;<select name="'.
1.89      albertel 3002: 		'GD_'.$student.'_'.$part.'_solved" '.
                   3003: 		'onChange="javascript:changeOneScore(\''.$part.'\',\''.$student.'\')" >'."\n";
1.125     ng       3004: 	    $result.= (($status eq 'excused') ? '<option> </option><option selected="on">excused</option>' 
                   3005: 		: '<option selected="on"> </option><option>excused</option>')."\n";
                   3006: 	    $result.='<option>reset status</option>';
1.126     ng       3007: 	    $result.="</select>&nbsp;</td>\n";
1.122     ng       3008: 	} else {
                   3009: 	    $result.='<input type="hidden" name="'.
                   3010: 		'GD_'.$student.'_'.$part.'_'.$type.'_s" value="'.$score.'" />'.
                   3011: 		    "\n";
1.233     albertel 3012: 	    $result.='<input type="text" name="'.
1.122     ng       3013: 		'GD_'.$student.'_'.$part.'_'.$type.'" '.
                   3014: 		'value="'.$score.'" size="4" /></td>'."\n";
1.41      ng       3015: 	}
                   3016:     }
                   3017:     $result.='</tr>';
                   3018:     return $result;
1.38      ng       3019: }
                   3020: 
1.44      ng       3021: #--- change scores for all the students in a section/class
                   3022: #    record does not get update if unchanged
1.38      ng       3023: sub editgrades {
1.41      ng       3024:     my ($request) = @_;
                   3025: 
1.324     albertel 3026:     my $symb=&get_symb($request);
1.45      ng       3027:     my $title='<h3><font color="#339933">Current Grade Status</font></h3>';
1.257     albertel 3028:     $title.='<font size=+1><b>Current Resource: </b>'.$env{'form.probTitle'}.'</font><br />'."\n";
                   3029:     $title.='<font size=+1><b>Section: </b>'.$env{'form.section'}.'</font>'."\n";
1.126     ng       3030: 
1.44      ng       3031:     my $result= '<table border="0"><tr><td bgcolor="#777777">'."\n";
1.129     ng       3032:     $result.= '<table border="0"><tr bgcolor="#deffff">'.
                   3033: 	'<td rowspan=2 valign="center">&nbsp;<b>No.</b>&nbsp;</td>'.
                   3034: 	'<td rowspan=2 valign="center">'.&nameUserString('header')."</td>\n";
1.43      ng       3035: 
                   3036:     my %scoreptr = (
                   3037: 		    'correct'  =>'correct_by_override',
                   3038: 		    'incorrect'=>'incorrect_by_override',
                   3039: 		    'excused'  =>'excused',
                   3040: 		    'ungraded' =>'ungraded_attempted',
                   3041: 		    'nothing'  => '',
                   3042: 		    );
1.257     albertel 3043:     my ($classlist,undef,$fullname) = &getclasslist($env{'form.section'},'0');
1.34      ng       3044: 
1.44      ng       3045:     my (@partid);
                   3046:     my %weight = ();
1.54      albertel 3047:     my %columns = ();
1.44      ng       3048:     my ($i,$ctr,$count,$rec_update) = (0,0,0,0);
1.54      albertel 3049: 
1.324     albertel 3050:     my (@parts) = sort(&getpartlist($symb));
1.54      albertel 3051:     my $header;
1.257     albertel 3052:     while ($ctr < $env{'form.totalparts'}) {
                   3053: 	my $partid = $env{'form.partid_'.$ctr};
1.44      ng       3054: 	push @partid,$partid;
1.257     albertel 3055: 	$weight{$partid} = $env{'form.weight_'.$partid};
1.44      ng       3056: 	$ctr++;
1.54      albertel 3057:     }
1.324     albertel 3058:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.54      albertel 3059:     foreach my $partid (@partid) {
                   3060: 	$header .= '<td align="center">&nbsp;<b>Old Score</b>&nbsp;</td>'.
                   3061: 	    '<td align="center">&nbsp;<b>New Score</b>&nbsp;</td>';
                   3062: 	$columns{$partid}=2;
                   3063: 	foreach my $stores (@parts) {
                   3064: 	    my ($part,$type) = &split_part_type($stores);
                   3065: 	    if ($part !~ m/^\Q$partid\E/) { next;}
                   3066: 	    if ($type eq 'awarded' || $type eq 'solved') { next; }
                   3067: 	    my $display=&Apache::lonnet::metadata($url,$stores.'.display');
                   3068: 	    $display =~ s/\[Part: (\w)+\]//;
1.125     ng       3069: 	    $display =~ s/Number of Attempts/Tries/;
                   3070: 	    $header .= '<td align="center">&nbsp;<b>Old '.$display.'</b>&nbsp;</td>'.
                   3071: 		'<td align="center">&nbsp;<b>New '.$display.'</b>&nbsp;</td>';
1.54      albertel 3072: 	    $columns{$partid}+=2;
                   3073: 	}
                   3074:     }
                   3075:     foreach my $partid (@partid) {
1.324     albertel 3076: 	my $display_part=&get_display_part($partid,$symb);
1.54      albertel 3077: 	$result .= '<td colspan="'.$columns{$partid}.
1.207     albertel 3078: 	    '" align="center"><b>Part:</b> '.$display_part.
                   3079: 	    ' (Weight = '.$weight{$partid}.')</td>';
1.54      albertel 3080: 
1.44      ng       3081:     }
                   3082:     $result .= '</tr><tr bgcolor="#deffff">';
1.54      albertel 3083:     $result .= $header;
1.44      ng       3084:     $result .= '</tr>'."\n";
1.93      albertel 3085:     my $noupdate;
1.126     ng       3086:     my ($updateCtr,$noupdateCtr) = (1,1);
1.257     albertel 3087:     for ($i=0; $i<$env{'form.total'}; $i++) {
1.93      albertel 3088: 	my $line;
1.257     albertel 3089: 	my $user = $env{'form.ctr'.$i};
1.281     albertel 3090: 	my ($uname,$udom)=split(/:/,$user);
1.44      ng       3091: 	my %newrecord;
                   3092: 	my $updateflag = 0;
1.281     albertel 3093: 	$line .= '<td>'.&nameUserString(undef,$$fullname{$user},$uname,$udom).'</td>';
1.108     albertel 3094: 	my $usec=$classlist->{"$uname:$udom"}[5];
1.105     albertel 3095: 	if (!&canmodify($usec)) {
1.126     ng       3096: 	    my $numcols=scalar(@partid)*4+2;
1.105     albertel 3097: 	    $noupdate.=$line."<td colspan=\"$numcols\"><font color=\"red\">Not allowed to modify student</font></td></tr>";
                   3098: 	    next;
                   3099: 	}
1.269     raeburn  3100:         my %aggregate = ();
                   3101:         my $aggregateflag = 0;
1.281     albertel 3102: 	$user=~s/:/_/; # colon doen't work in javascript for names
1.44      ng       3103: 	foreach (@partid) {
1.257     albertel 3104: 	    my $old_aw    = $env{'form.GD_'.$user.'_'.$_.'_awarded_s'};
1.54      albertel 3105: 	    my $old_part_pcr = $old_aw/($weight{$_} ne '0' ? $weight{$_}:1);
                   3106: 	    my $old_part  = $old_aw eq '' ? '' : $old_part_pcr;
1.257     albertel 3107: 	    my $old_score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
                   3108: 	    my $awarded   = $env{'form.GD_'.$user.'_'.$_.'_awarded'};
1.54      albertel 3109: 	    my $pcr       = $awarded/($weight{$_} ne '0' ? $weight{$_} : 1);
                   3110: 	    my $partial   = $awarded eq '' ? '' : $pcr;
1.44      ng       3111: 	    my $score;
                   3112: 	    if ($partial eq '') {
1.257     albertel 3113: 		$score = $scoreptr{$env{'form.GD_'.$user.'_'.$_.'_solved_s'}};
1.44      ng       3114: 	    } elsif ($partial > 0) {
                   3115: 		$score = 'correct_by_override';
                   3116: 	    } elsif ($partial == 0) {
                   3117: 		$score = 'incorrect_by_override';
                   3118: 	    }
1.257     albertel 3119: 	    my $dropMenu = $env{'form.GD_'.$user.'_'.$_.'_solved'};
1.125     ng       3120: 	    $score = 'excused' if (($dropMenu eq 'excused') && ($score ne 'excused'));
                   3121: 
1.292     albertel 3122: 	    $newrecord{'resource.'.$_.'.regrader'}=
                   3123: 		"$env{'user.name'}:$env{'user.domain'}";
1.125     ng       3124: 	    if ($dropMenu eq 'reset status' &&
                   3125: 		$old_score ne '') { # ignore if no previous attempts => nothing to reset
1.299     albertel 3126: 		$newrecord{'resource.'.$_.'.tries'} = '';
1.125     ng       3127: 		$newrecord{'resource.'.$_.'.solved'} = '';
                   3128: 		$newrecord{'resource.'.$_.'.award'} = '';
1.299     albertel 3129: 		$newrecord{'resource.'.$_.'.awarded'} = '';
1.125     ng       3130: 		$updateflag = 1;
1.269     raeburn  3131:                 if ($env{'form.GD_'.$user.'_'.$_.'_aggtries'} > 0) {
                   3132:                     my $aggtries = $env{'form.GD_'.$user.'_'.$_.'_aggtries'};
                   3133:                     my $totaltries = $env{'form.GD_'.$user.'_'.$_.'_totaltries'};
                   3134:                     my $solvedstatus = $env{'form.GD_'.$user.'_'.$_.'_solved_s'};
                   3135:                     &decrement_aggs($symb,$_,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   3136:                     $aggregateflag = 1;
                   3137:                 }
1.139     albertel 3138: 	    } elsif (!($old_part eq $partial && $old_score eq $score)) {
                   3139: 		$updateflag = 1;
                   3140: 		$newrecord{'resource.'.$_.'.awarded'}  = $partial if $partial ne '';
                   3141: 		$newrecord{'resource.'.$_.'.solved'}   = $score;
                   3142: 		$rec_update++;
1.125     ng       3143: 	    }
                   3144: 
1.93      albertel 3145: 	    $line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.44      ng       3146: 		'<td align="center">'.$awarded.
                   3147: 		($score eq 'excused' ? $score : '').'&nbsp;</td>';
1.5       albertel 3148: 
1.54      albertel 3149: 
                   3150: 	    my $partid=$_;
                   3151: 	    foreach my $stores (@parts) {
                   3152: 		my ($part,$type) = &split_part_type($stores);
                   3153: 		if ($part !~ m/^\Q$partid\E/) { next;}
                   3154: 		if ($type eq 'awarded' || $type eq 'solved') { next; }
1.257     albertel 3155: 		my $old_aw    = $env{'form.GD_'.$user.'_'.$part.'_'.$type.'_s'};
                   3156: 		my $awarded   = $env{'form.GD_'.$user.'_'.$part.'_'.$type};
1.54      albertel 3157: 		if ($awarded ne '' && $awarded ne $old_aw) {
                   3158: 		    $newrecord{'resource.'.$part.'.'.$type}= $awarded;
1.257     albertel 3159: 		    $newrecord{'resource.'.$part.'.regrader'}="$env{'user.name'}:$env{'user.domain'}";
1.54      albertel 3160: 		    $updateflag=1;
                   3161: 		}
1.93      albertel 3162: 		$line .= '<td align="center">'.$old_aw.'&nbsp;</td>'.
1.54      albertel 3163: 		    '<td align="center">'.$awarded.'&nbsp;</td>';
                   3164: 	    }
1.44      ng       3165: 	}
1.93      albertel 3166: 	$line.='</tr>'."\n";
1.301     albertel 3167: 
                   3168: 	my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3169: 	my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3170: 
1.44      ng       3171: 	if ($updateflag) {
                   3172: 	    $count++;
1.257     albertel 3173: 	    &Apache::lonnet::cstore(\%newrecord,$symb,$env{'request.course.id'},
1.89      albertel 3174: 				    $udom,$uname);
1.301     albertel 3175: 
                   3176: 	    if (&Apache::bridgetask::in_queue('gradingqueue',$symb,$cdom,
                   3177: 					      $cnum,$udom,$uname)) {
                   3178: 		# need to figure out if should be in queue.
                   3179: 		my %record =  
                   3180: 		    &Apache::lonnet::restore($symb,$env{'request.course.id'},
                   3181: 					     $udom,$uname);
                   3182: 		my $all_graded = 1;
                   3183: 		my $none_graded = 1;
                   3184: 		foreach my $part (@parts) {
                   3185: 		    if ( $record{'resource.'.$part.'.awarded'} eq '' ) {
                   3186: 			$all_graded = 0;
                   3187: 		    } else {
                   3188: 			$none_graded = 0;
                   3189: 		    }
                   3190: 		}
                   3191: 
                   3192: 		if ($all_graded || $none_graded) {
                   3193: 		    &Apache::bridgetask::remove_from_queue('gradingqueue',
                   3194: 							   $symb,$cdom,$cnum,
                   3195: 							   $udom,$uname);
                   3196: 		}
                   3197: 	    }
                   3198: 
1.126     ng       3199: 	    $result.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$updateCtr.'&nbsp;</td>'.$line;
                   3200: 	    $updateCtr++;
1.93      albertel 3201: 	} else {
1.126     ng       3202: 	    $noupdate.='<tr bgcolor="#ffffde"><td align="right">&nbsp;'.$noupdateCtr.'&nbsp;</td>'.$line;
                   3203: 	    $noupdateCtr++;
1.44      ng       3204: 	}
1.269     raeburn  3205:         if ($aggregateflag) {
                   3206:             &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
1.301     albertel 3207: 				  $cdom,$cnum);
1.269     raeburn  3208:         }
1.93      albertel 3209:     }
                   3210:     if ($noupdate) {
1.126     ng       3211: #	my $numcols=(scalar(@partid)*(scalar(@parts)-1)*2)+3;
                   3212: 	my $numcols=scalar(@partid)*4+2;
1.204     albertel 3213: 	$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       3214:     }
1.72      ng       3215:     $result .= '</table></td></tr></table>'."\n".
1.324     albertel 3216: 	&show_grading_menu_form ($symb);
1.125     ng       3217:     my $msg = '<br /><b>Number of records updated = '.$rec_update.
1.44      ng       3218: 	' for '.$count.' student'.($count <= 1 ? '' : 's').'.</b><br />'.
1.257     albertel 3219: 	'<b>Total number of students = '.$env{'form.total'}.'</b><br />';
1.44      ng       3220:     return $title.$msg.$result;
1.5       albertel 3221: }
1.54      albertel 3222: 
                   3223: sub split_part_type {
                   3224:     my ($partstr) = @_;
                   3225:     my ($temp,@allparts)=split(/_/,$partstr);
                   3226:     my $type=pop(@allparts);
                   3227:     my $part=join('.',@allparts);
                   3228:     return ($part,$type);
                   3229: }
                   3230: 
1.44      ng       3231: #------------- end of section for handling grading by section/class ---------
                   3232: #
                   3233: #----------------------------------------------------------------------------
                   3234: 
1.5       albertel 3235: 
1.44      ng       3236: #----------------------------------------------------------------------------
                   3237: #
                   3238: #-------------------------- Next few routines handles grading by csv upload
                   3239: #
                   3240: #--- Javascript to handle csv upload
1.27      albertel 3241: sub csvupload_javascript_reverse_associate {
1.246     albertel 3242:     my $error1=&mt('You need to specify the username or ID');
                   3243:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3244:   return(<<ENDPICK);
                   3245:   function verify(vf) {
                   3246:     var foundsomething=0;
                   3247:     var founduname=0;
1.243     albertel 3248:     var foundID=0;
1.27      albertel 3249:     for (i=0;i<=vf.nfields.value;i++) {
                   3250:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3251:       if (i==0 && tw!=0) { foundID=1; }
                   3252:       if (i==1 && tw!=0) { founduname=1; }
                   3253:       if (i!=0 && i!=1 && i!=2 && tw!=0) { foundsomething=1; }
1.27      albertel 3254:     }
1.246     albertel 3255:     if (founduname==0 && foundID==0) {
                   3256: 	alert('$error1');
                   3257: 	return;
1.27      albertel 3258:     }
                   3259:     if (foundsomething==0) {
1.246     albertel 3260: 	alert('$error2');
                   3261: 	return;
1.27      albertel 3262:     }
                   3263:     vf.submit();
                   3264:   }
                   3265:   function flip(vf,tf) {
                   3266:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3267:     var i;
                   3268:     for (i=0;i<=vf.nfields.value;i++) {
                   3269:       //can not pick the same destination field for both name and domain
                   3270:       if (((i ==0)||(i ==1)) && 
                   3271:           ((tf==0)||(tf==1)) && 
                   3272:           (i!=tf) &&
                   3273:           (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3274:         eval('vf.f'+i+'.selectedIndex=0;')
                   3275:       }
                   3276:     }
                   3277:   }
                   3278: ENDPICK
                   3279: }
                   3280: 
                   3281: sub csvupload_javascript_forward_associate {
1.246     albertel 3282:     my $error1=&mt('You need to specify the username or ID');
                   3283:     my $error2=&mt('You need to specify at least one grading field');
1.27      albertel 3284:   return(<<ENDPICK);
                   3285:   function verify(vf) {
                   3286:     var foundsomething=0;
                   3287:     var founduname=0;
1.243     albertel 3288:     var foundID=0;
1.27      albertel 3289:     for (i=0;i<=vf.nfields.value;i++) {
                   3290:       tw=eval('vf.f'+i+'.selectedIndex');
1.243     albertel 3291:       if (tw==1) { foundID=1; }
                   3292:       if (tw==2) { founduname=1; }
                   3293:       if (tw>3) { foundsomething=1; }
1.27      albertel 3294:     }
1.246     albertel 3295:     if (founduname==0 && foundID==0) {
                   3296: 	alert('$error1');
                   3297: 	return;
1.27      albertel 3298:     }
                   3299:     if (foundsomething==0) {
1.246     albertel 3300: 	alert('$error2');
                   3301: 	return;
1.27      albertel 3302:     }
                   3303:     vf.submit();
                   3304:   }
                   3305:   function flip(vf,tf) {
                   3306:     var nw=eval('vf.f'+tf+'.selectedIndex');
                   3307:     var i;
                   3308:     //can not pick the same destination field twice
                   3309:     for (i=0;i<=vf.nfields.value;i++) {
                   3310:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                   3311:         eval('vf.f'+i+'.selectedIndex=0;')
                   3312:       }
                   3313:     }
                   3314:   }
                   3315: ENDPICK
                   3316: }
                   3317: 
1.26      albertel 3318: sub csvuploadmap_header {
1.324     albertel 3319:     my ($request,$symb,$datatoken,$distotal)= @_;
1.41      ng       3320:     my $javascript;
1.257     albertel 3321:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.41      ng       3322: 	$javascript=&csvupload_javascript_reverse_associate();
                   3323:     } else {
                   3324: 	$javascript=&csvupload_javascript_forward_associate();
                   3325:     }
1.45      ng       3326: 
1.324     albertel 3327:     my ($result) = &showResourceInfo($symb,$env{'form.probTitle'});
1.257     albertel 3328:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.245     albertel 3329:     my $ignore=&mt('Ignore First Line');
1.41      ng       3330:     $request->print(<<ENDPICK);
1.26      albertel 3331: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.45      ng       3332: <h3><font color="#339933">Uploading Class Grades</font></h3>
                   3333: $result
1.326     albertel 3334: <hr />
1.26      albertel 3335: <h3>Identify fields</h3>
                   3336: Total number of records found in file: $distotal <hr />
                   3337: Enter as many fields as you can. The system will inform you and bring you back
                   3338: to this page if the data selected is insufficient to run your class.<hr />
                   3339: <input type="button" value="Reverse Association" onClick="javascript:this.form.associate.value='Reverse Association';submit(this.form);" />
1.245     albertel 3340: <label><input type="checkbox" name="noFirstLine" $checked />$ignore</label>
1.26      albertel 3341: <input type="hidden" name="associate"  value="" />
                   3342: <input type="hidden" name="phase"      value="three" />
                   3343: <input type="hidden" name="datatoken"  value="$datatoken" />
1.257     albertel 3344: <input type="hidden" name="fileupload" value="$env{'form.fileupload'}" />
                   3345: <input type="hidden" name="upfiletype" value="$env{'form.upfiletype'}" />
1.26      albertel 3346: <input type="hidden" name="upfile_associate" 
1.257     albertel 3347:                                        value="$env{'form.upfile_associate'}" />
1.26      albertel 3348: <input type="hidden" name="symb"       value="$symb" />
1.257     albertel 3349: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
                   3350: <input type="hidden" name="probTitle"  value="$env{'form.probTitle'}" />
1.246     albertel 3351: <input type="hidden" name="command"    value="csvuploadoptions" />
1.26      albertel 3352: <hr />
                   3353: <script type="text/javascript" language="Javascript">
                   3354: $javascript
                   3355: </script>
                   3356: ENDPICK
1.118     ng       3357:     return '';
1.26      albertel 3358: 
                   3359: }
                   3360: 
                   3361: sub csvupload_fields {
1.324     albertel 3362:     my ($symb) = @_;
                   3363:     my (@parts) = &getpartlist($symb);
1.243     albertel 3364:     my @fields=(['ID','Student ID'],
                   3365: 		['username','Student Username'],
                   3366: 		['domain','Student Domain']);
1.324     albertel 3367:     my (undef,undef,$url) = &Apache::lonnet::decode_symb($symb);
1.41      ng       3368:     foreach my $part (sort(@parts)) {
                   3369: 	my @datum;
                   3370: 	my $display=&Apache::lonnet::metadata($url,$part.'.display');
                   3371: 	my $name=$part;
                   3372: 	if  (!$display) { $display = $name; }
                   3373: 	@datum=($name,$display);
1.244     albertel 3374: 	if ($name=~/^stores_(.*)_awarded/) {
                   3375: 	    push(@fields,['stores_'.$1.'_points',"Points [Part: $1]"]);
                   3376: 	}
1.41      ng       3377: 	push(@fields,\@datum);
                   3378:     }
                   3379:     return (@fields);
1.26      albertel 3380: }
                   3381: 
                   3382: sub csvuploadmap_footer {
1.41      ng       3383:     my ($request,$i,$keyfields) =@_;
                   3384:     $request->print(<<ENDPICK);
1.26      albertel 3385: </table>
                   3386: <input type="hidden" name="nfields" value="$i" />
                   3387: <input type="hidden" name="keyfields" value="$keyfields" />
                   3388: <input type="button" onClick="javascript:verify(this.form)" value="Assign Grades" /><br />
                   3389: </form>
                   3390: ENDPICK
                   3391: }
                   3392: 
1.283     albertel 3393: sub checkforfile_js {
1.86      ng       3394:     my $result =<<CSVFORMJS;
                   3395: <script type="text/javascript" language="javascript">
                   3396:     function checkUpload(formname) {
                   3397: 	if (formname.upfile.value == "") {
                   3398: 	    alert("Please use the browse button to select a file from your local directory.");
                   3399: 	    return false;
                   3400: 	}
                   3401: 	formname.submit();
                   3402:     }
                   3403:     </script>
                   3404: CSVFORMJS
1.283     albertel 3405:     return $result;
                   3406: }
                   3407: 
                   3408: sub upcsvScores_form {
                   3409:     my ($request) = shift;
1.324     albertel 3410:     my ($symb)=&get_symb($request);
1.283     albertel 3411:     if (!$symb) {return '';}
                   3412:     my $result=&checkforfile_js();
1.257     albertel 3413:     $env{'form.probTitle'} = &Apache::lonnet::gettitle($symb);
1.324     albertel 3414:     my ($table) = &showResourceInfo($symb,$env{'form.probTitle'});
1.118     ng       3415:     $result.=$table;
1.326     albertel 3416:     $result.='<br /><table width="100%" border="0"><tr><td bgcolor="#777777">'."\n";
                   3417:     $result.='<table width="100%" border="0"><tr bgcolor="#e6ffff"><td>'."\n";
1.118     ng       3418:     $result.='&nbsp;<b>Specify a file containing the class scores for current resource'.
1.86      ng       3419: 	'.</b></td></tr>'."\n";
                   3420:     $result.='<tr bgcolor=#ffffe6><td>'."\n";
                   3421:     my $upfile_select=&Apache::loncommon::upfile_select_html();
1.245     albertel 3422:     my $ignore=&mt('Ignore First Line');
1.86      ng       3423:     $result.=<<ENDUPFORM;
1.106     albertel 3424: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
1.86      ng       3425: <input type="hidden" name="symb" value="$symb" />
                   3426: <input type="hidden" name="command" value="csvuploadmap" />
1.257     albertel 3427: <input type="hidden" name="probTitle" value="$env{'form.probTitle'}" />
                   3428: <input type="hidden" name="saveState"  value="$env{'form.saveState'}" />
1.86      ng       3429: $upfile_select
                   3430: <br /><input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scores" />
1.283     albertel 3431: <label><input type="checkbox" name="noFirstLine" />$ignore</label>
1.86      ng       3432: </form>
                   3433: ENDUPFORM
                   3434:     $result.='</td></tr></table>'."\n";
                   3435:     $result.='</td></tr></table><br /><br />'."\n";
1.324     albertel 3436:     $result.=&show_grading_menu_form($symb);
1.86      ng       3437:     return $result;
                   3438: }
                   3439: 
                   3440: 
1.26      albertel 3441: sub csvuploadmap {
1.41      ng       3442:     my ($request)= @_;
1.324     albertel 3443:     my ($symb)=&get_symb($request);
1.41      ng       3444:     if (!$symb) {return '';}
1.72      ng       3445: 
1.41      ng       3446:     my $datatoken;
1.257     albertel 3447:     if (!$env{'form.datatoken'}) {
1.41      ng       3448: 	$datatoken=&Apache::loncommon::upfile_store($request);
1.26      albertel 3449:     } else {
1.257     albertel 3450: 	$datatoken=$env{'form.datatoken'};
1.41      ng       3451: 	&Apache::loncommon::load_tmp_file($request);
1.26      albertel 3452:     }
1.41      ng       3453:     my @records=&Apache::loncommon::upfile_record_sep();
1.257     albertel 3454:     if ($env{'form.noFirstLine'}) { shift(@records); }
1.324     albertel 3455:     &csvuploadmap_header($request,$symb,$datatoken,$#records+1);
1.41      ng       3456:     my ($i,$keyfields);
                   3457:     if (@records) {
1.324     albertel 3458: 	my @fields=&csvupload_fields($symb);
1.45      ng       3459: 
1.257     albertel 3460: 	if ($env{'form.upfile_associate'} eq 'reverse') {	
1.41      ng       3461: 	    &Apache::loncommon::csv_print_samples($request,\@records);
                   3462: 	    $i=&Apache::loncommon::csv_print_select_table($request,\@records,
                   3463: 							  \@fields);
                   3464: 	    foreach (@fields) { $keyfields.=$_->[0].','; }
                   3465: 	    chop($keyfields);
                   3466: 	} else {
                   3467: 	    unshift(@fields,['none','']);
                   3468: 	    $i=&Apache::loncommon::csv_samples_select_table($request,\@records,
                   3469: 							    \@fields);
1.311     banghart 3470:             foreach my $rec (@records) {
                   3471:                 my %temp = &Apache::loncommon::record_sep($rec);
                   3472:                 if (%temp) {
                   3473:                     $keyfields=join(',',sort(keys(%temp)));
                   3474:                     last;
                   3475:                 }
                   3476:             }
1.41      ng       3477: 	}
                   3478:     }
                   3479:     &csvuploadmap_footer($request,$i,$keyfields);
1.324     albertel 3480:     $request->print(&show_grading_menu_form($symb));
1.72      ng       3481: 
1.41      ng       3482:     return '';
1.27      albertel 3483: }
                   3484: 
1.246     albertel 3485: sub csvuploadoptions {
1.41      ng       3486:     my ($request)= @_;
1.324     albertel 3487:     my ($symb)=&get_symb($request);
1.257     albertel 3488:     my $checked=(($env{'form.noFirstLine'})?'1':'0');
1.246     albertel 3489:     my $ignore=&mt('Ignore First Line');
                   3490:     $request->print(<<ENDPICK);
                   3491: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="gradesupload">
                   3492: <h3><font color="#339933">Uploading Class Grade Options</font></h3>
                   3493: <input type="hidden" name="command"    value="csvuploadassign" />
1.302     albertel 3494: <!--
1.246     albertel 3495: <p>
                   3496: <label>
                   3497:    <input type="checkbox" name="show_full_results" />
                   3498:    Show a table of all changes
                   3499: </label>
                   3500: </p>
1.302     albertel 3501: -->
1.246     albertel 3502: <p>
                   3503: <label>
                   3504:    <input type="checkbox" name="overwite_scores" checked="checked" />
                   3505:    Overwrite any existing score
                   3506: </label>
                   3507: </p>
                   3508: ENDPICK
                   3509:     my %fields=&get_fields();
                   3510:     if (!defined($fields{'domain'})) {
1.257     albertel 3511: 	my $domform = &Apache::loncommon::select_dom_form($env{'request.role.domain'},'default_domain');
1.246     albertel 3512: 	$request->print("\n<p> Users are in domain: ".$domform."</p>\n");
                   3513:     }
1.257     albertel 3514:     foreach my $key (sort(keys(%env))) {
1.246     albertel 3515: 	if ($key !~ /^form\.(.*)$/) { next; }
                   3516: 	my $cleankey=$1;
                   3517: 	if ($cleankey eq 'command') { next; }
                   3518: 	$request->print('<input type="hidden" name="'.$cleankey.
1.257     albertel 3519: 			'"  value="'.$env{$key}.'" />'."\n");
1.246     albertel 3520:     }
                   3521:     # FIXME do a check for any duplicated user ids...
                   3522:     # FIXME do a check for any invalid user ids?...
1.290     albertel 3523:     $request->print('<input type="submit" value="Assign Grades" /><br />
                   3524: <hr /></form>'."\n");
1.324     albertel 3525:     $request->print(&show_grading_menu_form($symb));
1.246     albertel 3526:     return '';
                   3527: }
                   3528: 
                   3529: sub get_fields {
                   3530:     my %fields;
1.257     albertel 3531:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   3532:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   3533: 	if ($env{'form.upfile_associate'} eq 'reverse') {
                   3534: 	    if ($env{'form.f'.$i} ne 'none') {
                   3535: 		$fields{$keyfields[$i]}=$env{'form.f'.$i};
1.41      ng       3536: 	    }
                   3537: 	} else {
1.257     albertel 3538: 	    if ($env{'form.f'.$i} ne 'none') {
                   3539: 		$fields{$env{'form.f'.$i}}=$keyfields[$i];
1.41      ng       3540: 	    }
                   3541: 	}
1.27      albertel 3542:     }
1.246     albertel 3543:     return %fields;
                   3544: }
                   3545: 
                   3546: sub csvuploadassign {
                   3547:     my ($request)= @_;
1.324     albertel 3548:     my ($symb)=&get_symb($request);
1.246     albertel 3549:     if (!$symb) {return '';}
1.345     bowersj2 3550:     my $error_msg = '';
1.246     albertel 3551:     &Apache::loncommon::load_tmp_file($request);
                   3552:     my @gradedata = &Apache::loncommon::upfile_record_sep();
1.257     albertel 3553:     if ($env{'form.noFirstLine'}) { shift(@gradedata); }
1.246     albertel 3554:     my %fields=&get_fields();
1.41      ng       3555:     $request->print('<h3>Assigning Grades</h3>');
1.257     albertel 3556:     my $courseid=$env{'request.course.id'};
1.97      albertel 3557:     my ($classlist) = &getclasslist('all',0);
1.106     albertel 3558:     my @notallowed;
1.41      ng       3559:     my @skipped;
                   3560:     my $countdone=0;
                   3561:     foreach my $grade (@gradedata) {
                   3562: 	my %entries=&Apache::loncommon::record_sep($grade);
1.246     albertel 3563: 	my $domain;
                   3564: 	if ($entries{$fields{'domain'}}) {
                   3565: 	    $domain=$entries{$fields{'domain'}};
                   3566: 	} else {
1.257     albertel 3567: 	    $domain=$env{'form.default_domain'};
1.246     albertel 3568: 	}
1.243     albertel 3569: 	$domain=~s/\s//g;
1.41      ng       3570: 	my $username=$entries{$fields{'username'}};
1.160     albertel 3571: 	$username=~s/\s//g;
1.243     albertel 3572: 	if (!$username) {
                   3573: 	    my $id=$entries{$fields{'ID'}};
1.247     albertel 3574: 	    $id=~s/\s//g;
1.243     albertel 3575: 	    my %ids=&Apache::lonnet::idget($domain,$id);
                   3576: 	    $username=$ids{$id};
                   3577: 	}
1.41      ng       3578: 	if (!exists($$classlist{"$username:$domain"})) {
1.247     albertel 3579: 	    my $id=$entries{$fields{'ID'}};
                   3580: 	    $id=~s/\s//g;
                   3581: 	    if ($id) {
                   3582: 		push(@skipped,"$id:$domain");
                   3583: 	    } else {
                   3584: 		push(@skipped,"$username:$domain");
                   3585: 	    }
1.41      ng       3586: 	    next;
                   3587: 	}
1.108     albertel 3588: 	my $usec=$classlist->{"$username:$domain"}[5];
1.106     albertel 3589: 	if (!&canmodify($usec)) {
                   3590: 	    push(@notallowed,"$username:$domain");
                   3591: 	    next;
                   3592: 	}
1.244     albertel 3593: 	my %points;
1.41      ng       3594: 	my %grades;
                   3595: 	foreach my $dest (keys(%fields)) {
1.244     albertel 3596: 	    if ($dest eq 'ID' || $dest eq 'username' ||
                   3597: 		$dest eq 'domain') { next; }
                   3598: 	    if ($entries{$fields{$dest}} =~ /^\s*$/) { next; }
                   3599: 	    if ($dest=~/stores_(.*)_points/) {
                   3600: 		my $part=$1;
                   3601: 		my $wgt =&Apache::lonnet::EXT('resource.'.$part.'.weight',
                   3602: 					      $symb,$domain,$username);
1.345     bowersj2 3603:                 if ($wgt) {
                   3604:                     $entries{$fields{$dest}}=~s/\s//g;
                   3605:                     my $pcr=$entries{$fields{$dest}} / $wgt;
                   3606:                     my $award='correct_by_override';
                   3607:                     $grades{"resource.$part.awarded"}=$pcr;
                   3608:                     $grades{"resource.$part.solved"}=$award;
                   3609:                     $points{$part}=1;
                   3610:                 } else {
                   3611:                     $error_msg = "<br />" .
                   3612:                         &mt("Some point values were assigned"
                   3613:                             ." for problems with a weight "
                   3614:                             ."of zero. These values were "
                   3615:                             ."ignored.");
                   3616:                 }
1.244     albertel 3617: 	    } else {
                   3618: 		if ($dest=~/stores_(.*)_awarded/) { if ($points{$1}) {next;} }
                   3619: 		if ($dest=~/stores_(.*)_solved/)  { if ($points{$1}) {next;} }
                   3620: 		my $store_key=$dest;
                   3621: 		$store_key=~s/^stores/resource/;
                   3622: 		$store_key=~s/_/\./g;
                   3623: 		$grades{$store_key}=$entries{$fields{$dest}};
                   3624: 	    }
1.41      ng       3625: 	}
1.244     albertel 3626: 	if (! %grades) { push(@skipped,"$username:$domain no data to store"); }
1.257     albertel 3627: 	$grades{"resource.regrader"}="$env{'user.name'}:$env{'user.domain'}";
1.244     albertel 3628: #	&Apache::lonnet::logthis(" storing ".(join('-',%grades)));
1.302     albertel 3629: 	my $result=&Apache::lonnet::cstore(\%grades,$symb,
                   3630: 					   $env{'request.course.id'},
                   3631: 					   $domain,$username);
                   3632: 	if ($result eq 'ok') {
                   3633: 	    $request->print('.');
                   3634: 	} else {
                   3635: 	    $request->print("<p>
                   3636:                               <font color='red'>
                   3637:                                  Failed to store student $username\@$domain.
                   3638:                                  Message when trying to store was ($result)
                   3639:                               </font>
                   3640:                              </p>" );
                   3641: 	}
1.41      ng       3642: 	$request->rflush();
                   3643: 	$countdone++;
                   3644:     }
                   3645:     $request->print("<br />Stored $countdone students\n");
                   3646:     if (@skipped) {
1.325     www      3647: 	$request->print('<p><font size="+1"><b>Skipped Students</b></font></p>');
1.106     albertel 3648: 	foreach my $student (@skipped) { $request->print("$student<br />\n"); }
                   3649:     }
                   3650:     if (@notallowed) {
                   3651: 	$request->print('<p><font size="+1" color="red"><b>Students Not Allowed to Modify</b></font></p>');
                   3652: 	foreach my $student (@notallowed) { $request->print("$student<br />\n"); }
1.41      ng       3653:     }
1.106     albertel 3654:     $request->print("<br />\n");
1.324     albertel 3655:     $request->print(&show_grading_menu_form($symb));
1.345     bowersj2 3656:     return $error_msg;
1.26      albertel 3657: }
1.44      ng       3658: #------------- end of section for handling csv file upload ---------
                   3659: #
                   3660: #-------------------------------------------------------------------
                   3661: #
1.122     ng       3662: #-------------- Next few routines handle grading by page/sequence
1.72      ng       3663: #
                   3664: #--- Select a page/sequence and a student to grade
1.68      ng       3665: sub pickStudentPage {
                   3666:     my ($request) = shift;
                   3667: 
                   3668:     $request->print(<<LISTJAVASCRIPT);
                   3669: <script type="text/javascript" language="javascript">
                   3670: 
                   3671: function checkPickOne(formname) {
1.76      ng       3672:     if (radioSelection(formname.student) == null) {
1.68      ng       3673: 	alert("Please select the student you wish to grade.");
                   3674: 	return;
                   3675:     }
1.125     ng       3676:     ptr = pullDownSelection(formname.selectpage);
                   3677:     formname.page.value = formname["page"+ptr].value;
                   3678:     formname.title.value = formname["title"+ptr].value;
1.68      ng       3679:     formname.submit();
                   3680: }
                   3681: 
                   3682: </script>
                   3683: LISTJAVASCRIPT
1.118     ng       3684:     &commonJSfunctions($request);
1.324     albertel 3685:     my ($symb) = &get_symb($request);
1.257     albertel 3686:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3687:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3688:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
1.68      ng       3689: 
                   3690:     my $result='<h3><font color="#339933">&nbsp;'.
                   3691: 	'Manual Grading by Page or Sequence</font></h3>';
                   3692: 
1.80      ng       3693:     $result.='<form action="/adm/grades" method="post" name="displayPage">'."\n";
1.70      ng       3694:     $result.='&nbsp;<b>Problems from:</b> <select name="selectpage">'."\n";
1.74      albertel 3695:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 3696:     my ($curpage) =&Apache::lonnet::decode_symb($symb); 
                   3697: #    my ($curpage,$mapId) =&Apache::lonnet::decode_symb($symb); 
                   3698: #    my $type=($curpage =~ /\.(page|sequence)/);
1.70      ng       3699:     my $ctr=0;
1.68      ng       3700:     foreach (@$titles) {
                   3701: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
1.70      ng       3702: 	$result.='<option value="'.$ctr.'" '.
1.71      ng       3703: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   3704: 	    '>'.$showtitle.'</option>'."\n";
1.70      ng       3705: 	$ctr++;
1.68      ng       3706:     }
1.326     albertel 3707:     $result.= '</select>'."<br />\n";
1.70      ng       3708:     $ctr=0;
                   3709:     foreach (@$titles) {
                   3710: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   3711: 	$result.='<input type="hidden" name="page'.$ctr.'" value="'.$$symbx{$_}.'" />'."\n";
                   3712: 	$result.='<input type="hidden" name="title'.$ctr.'" value="'.$showtitle.'" />'."\n";
                   3713: 	$ctr++;
                   3714:     }
1.72      ng       3715:     $result.='<input type="hidden" name="page" />'."\n".
                   3716: 	'<input type="hidden" name="title" />'."\n";
1.68      ng       3717: 
1.288     albertel 3718:     $result.='&nbsp;<b>View Problems Text: </b><label><input type="radio" name="vProb" value="no" checked="on" /> no </label>'."\n".
                   3719: 	'<label><input type="radio" name="vProb" value="yes" /> yes </label>'."<br />\n";
1.72      ng       3720: 
1.71      ng       3721:     $result.='&nbsp;<b>Submission Details: </b>'.
1.288     albertel 3722: 	'<label><input type="radio" name="lastSub" value="none" /> none</label>'."\n".
                   3723: 	'<label><input type="radio" name="lastSub" value="datesub" checked /> by dates and submissions</label>'."\n".
                   3724: 	'<label><input type="radio" name="lastSub" value="all" /> all details</label>'."\n";
1.72      ng       3725: 
1.68      ng       3726:     $result.='<input type="hidden" name="section"     value="'.$getsec.'" />'."\n".
1.257     albertel 3727: 	'<input type="hidden" name="Status"  value="'.$env{'form.Status'}.'" />'."\n".
1.72      ng       3728: 	'<input type="hidden" name="command" value="displayPage" />'."\n".
1.80      ng       3729: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 3730: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."<br />\n";
1.72      ng       3731: 
1.80      ng       3732:     $result.='&nbsp;<input type="button" '.
1.126     ng       3733: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /><br />'."\n";
1.72      ng       3734: 
1.68      ng       3735:     $request->print($result);
                   3736: 
1.326     albertel 3737:     my $studentTable.='&nbsp;<b>Select a student you wish to grade and then click on the Next button.</b><br />'.
1.68      ng       3738: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3739: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.126     ng       3740: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3741: 	'<td>'.&nameUserString('header').'</td>'.
1.126     ng       3742: 	'<td align="right">&nbsp;<b>No.</b></td>'.
1.129     ng       3743: 	'<td>'.&nameUserString('header').'</td></tr>';
1.68      ng       3744:  
1.76      ng       3745:     my (undef,undef,$fullname) = &getclasslist($getsec,'1');
1.68      ng       3746:     my $ptr = 1;
1.294     albertel 3747:     foreach my $student (sort 
                   3748: 			 {
                   3749: 			     if (lc($$fullname{$a}) ne lc($$fullname{$b})) {
                   3750: 				 return (lc($$fullname{$a}) cmp lc($$fullname{$b}));
                   3751: 			     }
                   3752: 			     return $a cmp $b;
                   3753: 			 } (keys(%$fullname))) {
1.68      ng       3754: 	my ($uname,$udom) = split(/:/,$student);
1.126     ng       3755: 	$studentTable.=($ptr%2 == 1 ? '<tr bgcolor="#ffffe6">' : '</td>');
                   3756: 	$studentTable.='<td align="right">'.$ptr.'&nbsp;</td>';
1.288     albertel 3757: 	$studentTable.='<td>&nbsp;<label><input type="radio" name="student" value="'.$student.'" /> '
                   3758: 	    .&nameUserString(undef,$$fullname{$student},$uname,$udom)."</label>\n";
1.126     ng       3759: 	$studentTable.=($ptr%2 == 0 ? '</td></tr>' : '');
1.68      ng       3760: 	$ptr++;
                   3761:     }
1.126     ng       3762:     $studentTable.='</td><td>&nbsp;</td><td>&nbsp;' if ($ptr%2 == 0);
1.68      ng       3763:     $studentTable.='</td></tr></table></td></tr></table>'."\n";
1.126     ng       3764:     $studentTable.='<input type="button" '.
                   3765: 	'onClick="javascript:checkPickOne(this.form);"value="Next->" /></form>'."\n";
1.68      ng       3766: 
1.324     albertel 3767:     $studentTable.=&show_grading_menu_form($symb);
1.68      ng       3768:     $request->print($studentTable);
                   3769: 
                   3770:     return '';
                   3771: }
                   3772: 
                   3773: sub getSymbMap {
1.74      albertel 3774:     my ($request) = @_;
1.132     bowersj2 3775:     my $navmap = Apache::lonnavmaps::navmap->new();
1.68      ng       3776: 
                   3777:     my %symbx = ();
                   3778:     my @titles = ();
1.117     bowersj2 3779:     my $minder = 0;
                   3780: 
                   3781:     # Gather every sequence that has problems.
1.240     albertel 3782:     my @sequences = $navmap->retrieveResources(undef, sub { shift->is_map(); },
                   3783: 					       1,0,1);
1.117     bowersj2 3784:     for my $sequence ($navmap->getById('0.0'), @sequences) {
1.241     albertel 3785: 	if ($navmap->hasResource($sequence, sub { shift->is_problem(); }, 0) ) {
1.117     bowersj2 3786: 	    my $title = $minder.'.'.$sequence->compTitle();
                   3787: 	    push @titles, $title; # minder in case two titles are identical
                   3788: 	    $symbx{$title} = $sequence->symb();
                   3789: 	    $minder++;
1.241     albertel 3790: 	}
1.68      ng       3791:     }
                   3792:     return \@titles,\%symbx;
                   3793: }
                   3794: 
1.72      ng       3795: #
                   3796: #--- Displays a page/sequence w/wo problems, w/wo submissions
1.68      ng       3797: sub displayPage {
                   3798:     my ($request) = shift;
                   3799: 
1.324     albertel 3800:     my ($symb) = &get_symb($request);
1.257     albertel 3801:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   3802:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   3803:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   3804:     my $pageTitle = $env{'form.page'};
1.103     albertel 3805:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 3806:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   3807:     my $usec=$classlist->{$env{'form.student'}}[5];
1.168     albertel 3808: 
                   3809:     #need to make sure we have the correct data for later EXT calls, 
                   3810:     #thus invalidate the cache
                   3811:     &Apache::lonnet::devalidatecourseresdata(
1.257     albertel 3812:                  $env{'course.'.$env{'request.course.id'}.'.num'},
                   3813:                  $env{'course.'.$env{'request.course.id'}.'.domain'});
1.168     albertel 3814:     &Apache::lonnet::clear_EXT_cache_status();
                   3815: 
1.103     albertel 3816:     if (!&canview($usec)) {
1.257     albertel 3817: 	$request->print('<font color="red">Unable to view requested student.('.$env{'form.student'}.')</font>');
1.324     albertel 3818: 	$request->print(&show_grading_menu_form($symb));
1.103     albertel 3819: 	return;
                   3820:     }
1.257     albertel 3821:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   3822:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$$fullname{$env{'form.student'}},$uname,$udom).
1.129     ng       3823: 	'</h3>'."\n";
1.71      ng       3824:     &sub_page_js($request);
                   3825:     $request->print($result);
                   3826: 
1.132     bowersj2 3827:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 3828:     my ($mapUrl, $id, $resUrl)=&Apache::lonnet::decode_symb($env{'form.page'});
1.68      ng       3829:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 3830:     if (!$map) {
                   3831: 	$request->print('<font color="red">Unable to view requested sequence. ('.$resUrl.')</font>');
1.324     albertel 3832: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 3833: 	return; 
                   3834:     }
1.68      ng       3835:     my $iterator = $navmap->getIterator($map->map_start(),
                   3836: 					$map->map_finish());
                   3837: 
1.71      ng       3838:     my $studentTable='<form action="/adm/grades" method="post" name="gradePage">'."\n".
1.72      ng       3839: 	'<input type="hidden" name="command" value="gradeByPage" />'."\n".
1.257     albertel 3840: 	'<input type="hidden" name="fullname" value="'.$$fullname{$env{'form.student'}}.'" />'."\n".
                   3841: 	'<input type="hidden" name="student" value="'.$env{'form.student'}.'" />'."\n".
1.72      ng       3842: 	'<input type="hidden" name="page"    value="'.$pageTitle.'" />'."\n".
1.257     albertel 3843: 	'<input type="hidden" name="title"   value="'.$env{'form.title'}.'" />'."\n".
1.72      ng       3844: 	'<input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.125     ng       3845: 	'<input type="hidden" name="overRideScore" value="no" />'."\n".
1.257     albertel 3846: 	'<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n";
1.71      ng       3847: 
                   3848:     my $checkIcon = '<img src="'.$request->dir_config('lonIconsURL').
                   3849: 	'/check.gif" height="16" border="0" />';
                   3850: 
1.118     ng       3851:     $studentTable.='&nbsp;<b>Note:</b> Problems graded correct by the computer are marked with a '.$checkIcon.
                   3852: 	' symbol.'."\n".
1.71      ng       3853: 	'<table border="0"><tr><td bgcolor="#777777">'.
                   3854: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.118     ng       3855: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.257     albertel 3856: 	'<td><b>&nbsp;'.($env{'form.vProb'} eq 'no' ? 'Title' : 'Problem Text').'/Grade</b></td></tr>';
1.71      ng       3857: 
1.329     albertel 3858:     &Apache::lonxml::clear_problem_counter();
1.196     albertel 3859:     my ($depth,$question,$prob) = (1,1,1);
1.68      ng       3860:     $iterator->next(); # skip the first BEGIN_MAP
                   3861:     my $curRes = $iterator->next(); # for "current resource"
1.101     albertel 3862:     while ($depth > 0) {
1.68      ng       3863:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 3864:         if($curRes == $iterator->END_MAP) { $depth--; }
1.68      ng       3865: 
1.235     albertel 3866:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 3867: 	    my $parts = $curRes->parts();
1.68      ng       3868:             my $title = $curRes->compTitle();
1.71      ng       3869: 	    my $symbx = $curRes->symb();
1.196     albertel 3870: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 3871: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       3872: 	    $studentTable.='<td valign="top">';
1.257     albertel 3873: 	    if ($env{'form.vProb'} eq 'yes' ) {
1.144     albertel 3874: 		$studentTable.=&show_problem($request,$symbx,$uname,$udom,1,
                   3875: 					     undef,'both');
1.71      ng       3876: 	    } else {
1.257     albertel 3877: 		my $companswer = &Apache::loncommon::get_student_answers($symbx,$uname,$udom,$env{'request.course.id'});
1.80      ng       3878: 		$companswer =~ s|<form(.*?)>||g;
                   3879: 		$companswer =~ s|</form>||g;
1.71      ng       3880: #		while ($companswer =~ /(<a href\=\"javascript:newWindow.*?Script Vars<\/a>)/s) { #<a href="javascript:newWindow</a>
1.116     ng       3881: #		    $companswer =~ s/$1/ /ms;
1.326     albertel 3882: #		    $request->print('match='.$1."<br />\n");
1.71      ng       3883: #		}
1.116     ng       3884: #		$companswer =~ s|<table border=\"1\">|<table border=\"0\">|g;
1.326     albertel 3885: 		$studentTable.='&nbsp;<b>'.$title.'</b>&nbsp;<br />&nbsp;<b>Correct answer:</b><br />'.$companswer;
1.71      ng       3886: 	    }
                   3887: 
1.257     albertel 3888: 	    my %record = &Apache::lonnet::restore($symbx,$env{'request.course.id'},$udom,$uname);
1.125     ng       3889: 
1.257     albertel 3890: 	    if ($env{'form.lastSub'} eq 'datesub') {
1.71      ng       3891: 		if ($record{'version'} eq '') {
                   3892: 		    $studentTable.='<br />&nbsp;<font color="red">No recorded submission for this problem</font><br />';
                   3893: 		} else {
1.116     ng       3894: 		    my %responseType = ();
                   3895: 		    foreach my $partid (@{$parts}) {
1.147     albertel 3896: 			my @responseIds =$curRes->responseIds($partid);
                   3897: 			my @responseType =$curRes->responseType($partid);
                   3898: 			my %responseIds;
                   3899: 			for (my $i=0;$i<=$#responseIds;$i++) {
                   3900: 			    $responseIds{$responseIds[$i]}=$responseType[$i];
                   3901: 			}
                   3902: 			$responseType{$partid} = \%responseIds;
1.116     ng       3903: 		    }
1.148     albertel 3904: 		    $studentTable.= &displaySubByDates($symbx,\%record,$parts,\%responseType,$checkIcon,$uname,$udom);
1.147     albertel 3905: 
1.71      ng       3906: 		}
1.257     albertel 3907: 	    } elsif ($env{'form.lastSub'} eq 'all') {
                   3908: 		my $last = ($env{'form.lastSub'} eq 'last' ? 'last' : '');
1.71      ng       3909: 		$studentTable.=&Apache::loncommon::get_previous_attempt($symbx,$uname,$udom,
1.257     albertel 3910: 									$env{'request.course.id'},
1.71      ng       3911: 									'','.submission');
                   3912:  
                   3913: 	    }
1.103     albertel 3914: 	    if (&canmodify($usec)) {
                   3915: 		foreach my $partid (@{$parts}) {
                   3916: 		    $studentTable.=&gradeBox($request,$symbx,$uname,$udom,$question,$partid,\%record);
                   3917: 		    $studentTable.='<input type="hidden" name="q_'.$question.'" value="'.$partid.'" />'."\n";
                   3918: 		    $question++;
                   3919: 		}
1.196     albertel 3920: 		$prob++;
1.71      ng       3921: 	    }
                   3922: 	    $studentTable.='</td></tr>';
1.68      ng       3923: 
1.103     albertel 3924: 	}
1.68      ng       3925:         $curRes = $iterator->next();
                   3926:     }
                   3927: 
1.71      ng       3928:     $studentTable.='</td></tr></table></td></tr></table>'."\n".
1.125     ng       3929: 	'<input type="button" value="Save" '.
1.71      ng       3930: 	'onClick="javascript:checkSubmitPage(this.form,'.$question.');" TARGET=_self />'.
                   3931: 	'</form>'."\n";
1.324     albertel 3932:     $studentTable.=&show_grading_menu_form($symb);
1.71      ng       3933:     $request->print($studentTable);
                   3934: 
                   3935:     return '';
1.119     ng       3936: }
                   3937: 
                   3938: sub displaySubByDates {
1.148     albertel 3939:     my ($symb,$record,$parts,$responseType,$checkIcon,$uname,$udom) = @_;
1.224     albertel 3940:     my $isCODE=0;
1.335     albertel 3941:     my $isTask = ($symb =~/\.task$/);
1.224     albertel 3942:     if (exists($record->{'resource.CODE'})) { $isCODE=1; }
1.119     ng       3943:     my $studentTable='<table border="0" width="100%"><tr><td bgcolor="#777777">'.
                   3944: 	'<table border="0" width="100%"><tr bgcolor="#e6ffff">'.
                   3945: 	'<td><b>Date/Time</b></td>'.
1.224     albertel 3946: 	($isCODE?'<td><b>CODE</b></td>':'').
1.119     ng       3947: 	'<td><b>Submission</b></td>'.
                   3948: 	'<td><b>Status&nbsp;</b></td></tr>';
                   3949:     my ($version);
                   3950:     my %mark;
1.148     albertel 3951:     my %orders;
1.119     ng       3952:     $mark{'correct_by_student'} = $checkIcon;
1.147     albertel 3953:     if (!exists($$record{'1:timestamp'})) {
                   3954: 	return '<br />&nbsp;<font color="red">Nothing submitted - no attempts</font><br />';
                   3955:     }
1.335     albertel 3956: 
                   3957:     my $interaction;
1.119     ng       3958:     for ($version=1;$version<=$$record{'version'};$version++) {
                   3959: 	my $timestamp = scalar(localtime($$record{$version.':timestamp'}));
1.335     albertel 3960: 	if (exists($$record{$version.':resource.0.version'})) {
                   3961: 	    $interaction = $$record{$version.':resource.0.version'};
                   3962: 	}
                   3963: 
                   3964: 	my $where = ($isTask ? "$version:resource.$interaction"
                   3965: 		             : "$version:resource");
                   3966: 	#&Apache::lonnet::logthis(" got $where");
1.119     ng       3967: 	$studentTable.='<tr bgcolor="#ffffff" valign="top"><td>'.$timestamp.'</td>';
1.224     albertel 3968: 	if ($isCODE) {
                   3969: 	    $studentTable.='<td>'.$record->{$version.':resource.CODE'}.'</td>';
                   3970: 	}
1.119     ng       3971: 	my @versionKeys = split(/\:/,$$record{$version.':keys'});
                   3972: 	my @displaySub = ();
                   3973: 	foreach my $partid (@{$parts}) {
1.335     albertel 3974: 	    my @matchKey = ($isTask ? sort(grep /^resource\.\d+\.\Q$partid\E\.award$/,@versionKeys)
                   3975: 			            : sort(grep /^resource\.\Q$partid\E\..*?\.submission$/,@versionKeys));
                   3976: 	    
                   3977: 
1.122     ng       3978: #	    next if ($$record{"$version:resource.$partid.solved"} eq '');
1.324     albertel 3979: 	    my $display_part=&get_display_part($partid,$symb);
1.147     albertel 3980: 	    foreach my $matchKey (@matchKey) {
1.198     albertel 3981: 		if (exists($$record{$version.':'.$matchKey}) &&
                   3982: 		    $$record{$version.':'.$matchKey} ne '') {
1.335     albertel 3983: 
                   3984: 		    my ($responseId)= ($isTask ? ($matchKey=~ /^resource\.(.*?)\.\Q$partid\E\.award$/)
                   3985: 				               : ($matchKey=~ /^resource\.\Q$partid\E\.(.*?)\.submission$/));
                   3986: 		    #&Apache::lonnet::logthis("match $matchKey $responseId (".$$record{$version.':'.$matchKey});
1.207     albertel 3987: 		    $displaySub[0].='<b>Part:</b>&nbsp;'.$display_part.'&nbsp;';
1.147     albertel 3988: 		    $displaySub[0].='<font color="#999999">(ID&nbsp;'.
1.207     albertel 3989: 			$responseId.')</font>&nbsp;<b>';
1.335     albertel 3990: 		    if ($$record{"$where.$partid.tries"} eq '') {
1.147     albertel 3991: 			$displaySub[0].='Trial&nbsp;not&nbsp;counted';
                   3992: 		    } else {
                   3993: 			$displaySub[0].='Trial&nbsp;'.
1.335     albertel 3994: 			    $$record{"$where.$partid.tries"};
1.147     albertel 3995: 		    }
1.335     albertel 3996: 		    my $responseType=($isTask ? 'Task'
                   3997:                                               : $responseType->{$partid}->{$responseId});
1.148     albertel 3998: 		    if (!exists($orders{$partid})) { $orders{$partid}={}; }
                   3999: 		    if (!exists($orders{$partid}->{$responseId})) {
                   4000: 			$orders{$partid}->{$responseId}=
                   4001: 			    &get_order($partid,$responseId,$symb,$uname,$udom);
                   4002: 		    }
1.147     albertel 4003: 		    $displaySub[0].='</b>&nbsp; '.
1.336     albertel 4004: 			&cleanRecord($$record{$version.':'.$matchKey},$responseType,$symb,$partid,$responseId,$record,$orders{$partid}->{$responseId},"$version:",$uname,$udom).'<br />';
1.147     albertel 4005: 		}
                   4006: 	    }
1.335     albertel 4007: 	    if (exists($$record{"$where.$partid.checkedin"})) {
                   4008: 		$displaySub[1].='Checked in by '.
                   4009: 		    $$record{"$where.$partid.checkedin"}.' into slot '.
                   4010: 		    $$record{"$where.$partid.checkedin.slot"}.
                   4011: 		    '<br />';
                   4012: 	    }
                   4013: 	    if (exists $$record{"$where.$partid.award"}) {
1.207     albertel 4014: 		$displaySub[1].='<b>Part:</b>&nbsp;'.$display_part.' &nbsp;'.
1.335     albertel 4015: 		    lc($$record{"$where.$partid.award"}).' '.
                   4016: 		    $mark{$$record{"$where.$partid.solved"}}.
1.147     albertel 4017: 		    '<br />';
                   4018: 	    }
1.335     albertel 4019: 	    if (exists $$record{"$where.$partid.regrader"}) {
                   4020: 		$displaySub[2].=$$record{"$where.$partid.regrader"}.
                   4021: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
                   4022: 	    } elsif ($$record{"$version:resource.$partid.regrader"} =~ /\S/) {
                   4023: 		$displaySub[2].=
                   4024: 		    $$record{"$version:resource.$partid.regrader"}.
1.207     albertel 4025: 		    ' (<b>'.&mt('Part').':</b> '.$display_part.')';
1.147     albertel 4026: 	    }
                   4027: 	}
                   4028: 	# needed because old essay regrader has not parts info
                   4029: 	if (exists $$record{"$version:resource.regrader"}) {
                   4030: 	    $displaySub[2].=$$record{"$version:resource.regrader"};
                   4031: 	}
                   4032: 	$studentTable.='<td>'.$displaySub[0].'&nbsp;</td><td>'.$displaySub[1];
                   4033: 	if ($displaySub[2]) {
                   4034: 	    $studentTable.='Manually graded by '.$displaySub[2];
                   4035: 	}
                   4036: 	$studentTable.='&nbsp;</td></tr>';
                   4037:     
1.119     ng       4038:     }
                   4039:     $studentTable.='</table></td></tr></table>';
                   4040:     return $studentTable;
1.71      ng       4041: }
                   4042: 
                   4043: sub updateGradeByPage {
                   4044:     my ($request) = shift;
                   4045: 
1.257     albertel 4046:     my $cdom      = $env{"course.$env{'request.course.id'}.domain"};
                   4047:     my $cnum      = $env{"course.$env{'request.course.id'}.num"};
                   4048:     my $getsec    = $env{'form.section'} eq '' ? 'all' : $env{'form.section'};
                   4049:     my $pageTitle = $env{'form.page'};
1.103     albertel 4050:     my ($classlist,undef,$fullname) = &getclasslist($getsec,'1');
1.257     albertel 4051:     my ($uname,$udom) = split(/:/,$env{'form.student'});
                   4052:     my $usec=$classlist->{$env{'form.student'}}[5];
1.103     albertel 4053:     if (!&canmodify($usec)) {
1.257     albertel 4054: 	$request->print('<font color="red">Unable to modify requested student.('.$env{'form.student'}.'</font>');
1.324     albertel 4055: 	$request->print(&show_grading_menu_form($env{'form.symb'}));
1.103     albertel 4056: 	return;
                   4057:     }
1.257     albertel 4058:     my $result='<h3><font color="#339933">&nbsp;'.$env{'form.title'}.'</font></h3>';
                   4059:     $result.='<h3>&nbsp;Student: '.&nameUserString(undef,$env{'form.fullname'},$uname,$udom).
1.129     ng       4060: 	'</h3>'."\n";
1.70      ng       4061: 
1.68      ng       4062:     $request->print($result);
                   4063: 
1.132     bowersj2 4064:     my $navmap = Apache::lonnavmaps::navmap->new();
1.257     albertel 4065:     my ($mapUrl, $id, $resUrl) = &Apache::lonnet::decode_symb( $env{'form.page'});
1.71      ng       4066:     my $map = $navmap->getResourceByUrl($resUrl); # add to navmaps
1.288     albertel 4067:     if (!$map) {
                   4068: 	$request->print('<font color="red">Unable to grade requested sequence. ('.$resUrl.')</font>');
1.324     albertel 4069: 	my ($symb)=&get_symb($request);
                   4070: 	$request->print(&show_grading_menu_form($symb));
1.288     albertel 4071: 	return; 
                   4072:     }
1.71      ng       4073:     my $iterator = $navmap->getIterator($map->map_start(),
                   4074: 					$map->map_finish());
1.70      ng       4075: 
1.71      ng       4076:     my $studentTable='<table border="0"><tr><td bgcolor="#777777">'.
1.68      ng       4077: 	'<table border="0"><tr bgcolor="#e6ffff">'.
1.125     ng       4078: 	'<td align="center"><b>&nbsp;Prob.&nbsp;</b></td>'.
1.71      ng       4079: 	'<td><b>&nbsp;Title&nbsp;</b></td>'.
                   4080: 	'<td><b>&nbsp;Previous Score&nbsp;</b></td>'.
                   4081: 	'<td><b>&nbsp;New Score&nbsp;</b></td></tr>';
                   4082: 
                   4083:     $iterator->next(); # skip the first BEGIN_MAP
                   4084:     my $curRes = $iterator->next(); # for "current resource"
1.196     albertel 4085:     my ($depth,$question,$prob,$changeflag)= (1,1,1,0);
1.101     albertel 4086:     while ($depth > 0) {
1.71      ng       4087:         if($curRes == $iterator->BEGIN_MAP) { $depth++; }
1.100     bowersj2 4088:         if($curRes == $iterator->END_MAP) { $depth--; }
1.71      ng       4089: 
                   4090:         if (ref($curRes) && $curRes->is_problem() && !$curRes->randomout) {
1.91      albertel 4091: 	    my $parts = $curRes->parts();
1.71      ng       4092:             my $title = $curRes->compTitle();
                   4093: 	    my $symbx = $curRes->symb();
1.196     albertel 4094: 	    $studentTable.='<tr bgcolor="#ffffe6"><td align="center" valign="top" >'.$prob.
1.326     albertel 4095: 		(scalar(@{$parts}) == 1 ? '' : '<br />('.scalar(@{$parts}).'&nbsp;parts)').'</td>';
1.71      ng       4096: 	    $studentTable.='<td valign="top">&nbsp;<b>'.$title.'</b>&nbsp;</td>';
                   4097: 
                   4098: 	    my %newrecord=();
                   4099: 	    my @displayPts=();
1.269     raeburn  4100:             my %aggregate = ();
                   4101:             my $aggregateflag = 0;
1.71      ng       4102: 	    foreach my $partid (@{$parts}) {
1.257     albertel 4103: 		my $newpts = $env{'form.GD_BOX'.$question.'_'.$partid};
                   4104: 		my $oldpts = $env{'form.oldpts'.$question.'_'.$partid};
1.71      ng       4105: 
1.257     albertel 4106: 		my $wgt = $env{'form.WGT'.$question.'_'.$partid} != 0 ? 
                   4107: 		    $env{'form.WGT'.$question.'_'.$partid} : 1;
1.71      ng       4108: 		my $partial = $newpts/$wgt;
                   4109: 		my $score;
                   4110: 		if ($partial > 0) {
                   4111: 		    $score = 'correct_by_override';
1.125     ng       4112: 		} elsif ($newpts ne '') { #empty is taken as 0
1.71      ng       4113: 		    $score = 'incorrect_by_override';
                   4114: 		}
1.257     albertel 4115: 		my $dropMenu = $env{'form.GD_SEL'.$question.'_'.$partid};
1.125     ng       4116: 		if ($dropMenu eq 'excused') {
1.71      ng       4117: 		    $partial = '';
                   4118: 		    $score = 'excused';
1.125     ng       4119: 		} elsif ($dropMenu eq 'reset status'
1.257     albertel 4120: 			 && $env{'form.solved'.$question.'_'.$partid} ne '') { #update only if previous record exists
1.125     ng       4121: 		    $newrecord{'resource.'.$partid.'.tries'} = 0;
                   4122: 		    $newrecord{'resource.'.$partid.'.solved'} = '';
                   4123: 		    $newrecord{'resource.'.$partid.'.award'} = '';
                   4124: 		    $newrecord{'resource.'.$partid.'.awarded'} = 0;
1.257     albertel 4125: 		    $newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}";
1.125     ng       4126: 		    $changeflag++;
                   4127: 		    $newpts = '';
1.269     raeburn  4128:                     
                   4129:                     my $aggtries =  $env{'form.aggtries'.$question.'_'.$partid};
                   4130:                     my $totaltries = $env{'form.totaltries'.$question.'_'.$partid};
                   4131:                     my $solvedstatus = $env{'form.solved'.$question.'_'.$partid};
                   4132:                     if ($aggtries > 0) {
                   4133:                         &decrement_aggs($symbx,$partid,\%aggregate,$aggtries,$totaltries,$solvedstatus);
                   4134:                         $aggregateflag = 1;
                   4135:                     }
1.71      ng       4136: 		}
1.324     albertel 4137: 		my $display_part=&get_display_part($partid,$curRes->symb());
1.257     albertel 4138: 		my $oldstatus = $env{'form.solved'.$question.'_'.$partid};
1.207     albertel 4139: 		$displayPts[0].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.71      ng       4140: 		    (($oldstatus eq 'excused') ? 'excused' : $oldpts).
1.326     albertel 4141: 		    '&nbsp;<br />';
1.207     albertel 4142: 		$displayPts[1].='&nbsp;<b>Part:</b> '.$display_part.' = '.
1.125     ng       4143: 		     (($score eq 'excused') ? 'excused' : $newpts).
1.326     albertel 4144: 		    '&nbsp;<br />';
1.71      ng       4145: 
                   4146: 		$question++;
1.125     ng       4147: 		next if ($dropMenu eq 'reset status' || ($newpts == $oldpts && $score ne 'excused'));
                   4148: 
1.71      ng       4149: 		$newrecord{'resource.'.$partid.'.awarded'}  = $partial if $partial ne '';
1.125     ng       4150: 		$newrecord{'resource.'.$partid.'.solved'}   = $score if $score ne '';
1.257     albertel 4151: 		$newrecord{'resource.'.$partid.'.regrader'} = "$env{'user.name'}:$env{'user.domain'}"
1.125     ng       4152: 		    if (scalar(keys(%newrecord)) > 0);
1.71      ng       4153: 
                   4154: 		$changeflag++;
                   4155: 	    }
                   4156: 	    if (scalar(keys(%newrecord)) > 0) {
1.257     albertel 4157: 		&Apache::lonnet::cstore(\%newrecord,$symbx,$env{'request.course.id'},
1.71      ng       4158: 					$udom,$uname);
                   4159: 	    }
1.269     raeburn  4160:             if ($aggregateflag) {
                   4161:                 &Apache::lonnet::cinc('nohist_resourcetracker',\%aggregate,
                   4162:                       $env{'course.'.$env{'request.course.id'}.'.domain'},
                   4163:                       $env{'course.'.$env{'request.course.id'}.'.num'});
                   4164:             }
1.125     ng       4165: 
1.71      ng       4166: 	    $studentTable.='<td valign="top">'.$displayPts[0].'</td>'.
                   4167: 		'<td valign="top">'.$displayPts[1].'</td>'.
                   4168: 		'</tr>';
1.68      ng       4169: 
1.196     albertel 4170: 	    $prob++;
1.68      ng       4171: 	}
1.71      ng       4172:         $curRes = $iterator->next();
1.68      ng       4173:     }
1.98      albertel 4174: 
1.71      ng       4175:     $studentTable.='</td></tr></table></td></tr></table>';
1.324     albertel 4176:     $studentTable.=&show_grading_menu_form($env{'form.symb'});
1.76      ng       4177:     my $grademsg=($changeflag == 0 ? 'No score was changed or updated.' :
                   4178: 		  'The scores were changed for '.
                   4179: 		  $changeflag.' problem'.($changeflag == 1 ? '.' : 's.'));
                   4180:     $request->print($grademsg.$studentTable);
1.68      ng       4181: 
1.70      ng       4182:     return '';
                   4183: }
                   4184: 
1.72      ng       4185: #-------- end of section for handling grading by page/sequence ---------
                   4186: #
                   4187: #-------------------------------------------------------------------
                   4188: 
1.75      albertel 4189: #--------------------Scantron Grading-----------------------------------
                   4190: #
                   4191: #------ start of section for handling grading by page/sequence ---------
                   4192: 
1.81      albertel 4193: sub defaultFormData {
1.324     albertel 4194:     my ($symb)=@_;
1.81      albertel 4195:     return '
                   4196:       <input type="hidden" name="symb"    value="'.$symb.'" />'."\n".
1.257     albertel 4197:      '<input type="hidden" name="saveState" value="'.$env{'form.saveState'}.'" />'."\n".
                   4198:      '<input type="hidden" name="probTitle" value="'.$env{'form.probTitle'}.'" />'."\n";
1.81      albertel 4199: }
                   4200: 
1.75      albertel 4201: sub getSequenceDropDown {
                   4202:     my ($request,$symb)=@_;
                   4203:     my $result='<select name="selectpage">'."\n";
                   4204:     my ($titles,$symbx) = &getSymbMap($request);
1.137     albertel 4205:     my ($curpage)=&Apache::lonnet::decode_symb($symb); 
1.75      albertel 4206:     my $ctr=0;
                   4207:     foreach (@$titles) {
                   4208: 	my ($minder,$showtitle) = ($_ =~ /(\d+)\.(.*)/);
                   4209: 	$result.='<option value="'.$$symbx{$_}.'" '.
                   4210: 	    ($$symbx{$_} =~ /$curpage$/ ? 'selected="on"' : '').
                   4211: 	    '>'.$showtitle.'</option>'."\n";
                   4212: 	$ctr++;
                   4213:     }
                   4214:     $result.= '</select>';
                   4215:     return $result;
                   4216: }
                   4217: 
1.202     albertel 4218: sub scantron_filenames {
1.257     albertel 4219:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4220:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
1.157     albertel 4221:     my @files=&Apache::lonnet::dirlist('userfiles',$cdom,$cname,
1.162     albertel 4222: 				    &Apache::loncommon::propath($cdom,$cname));
1.202     albertel 4223:     my @possiblenames;
1.201     albertel 4224:     foreach my $filename (sort(@files)) {
1.157     albertel 4225: 	($filename)=split(/&/,$filename);
                   4226: 	if ($filename!~/^scantron_orig_/) { next ; }
                   4227: 	$filename=~s/^scantron_orig_//;
1.202     albertel 4228: 	push(@possiblenames,$filename);
                   4229:     }
                   4230:     return @possiblenames;
                   4231: }
                   4232: 
                   4233: sub scantron_uploads {
1.209     ng       4234:     my ($file2grade) = @_;
1.202     albertel 4235:     my $result=	'<select name="scantron_selectfile">';
                   4236:     $result.="<option></option>";
                   4237:     foreach my $filename (sort(&scantron_filenames())) {
1.209     ng       4238: 	$result.="<option".($filename eq $file2grade ? ' selected="on"':'').">$filename</option>\n";
1.81      albertel 4239:     }
                   4240:     $result.="</select>";
                   4241:     return $result;
                   4242: }
                   4243: 
1.82      albertel 4244: sub scantron_scantab {
                   4245:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4246:     my $result='<select name="scantron_format">'."\n";
1.191     albertel 4247:     $result.='<option></option>'."\n";
1.82      albertel 4248:     foreach my $line (<$fh>) {
                   4249: 	my ($name,$descrip)=split(/:/,$line);
                   4250: 	if ($name =~ /^\#/) { next; }
                   4251: 	$result.='<option value="'.$name.'">'.$descrip.'</option>'."\n";
                   4252:     }
                   4253:     $result.='</select>'."\n";
                   4254: 
                   4255:     return $result;
                   4256: }
                   4257: 
1.186     albertel 4258: sub scantron_CODElist {
1.257     albertel 4259:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4260:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.186     albertel 4261:     my @names=&Apache::lonnet::getkeys('CODEs',$cdom,$cnum);
                   4262:     my $namechoice='<option></option>';
1.225     albertel 4263:     foreach my $name (sort {uc($a) cmp uc($b)} @names) {
1.191     albertel 4264: 	if ($name =~ /^error: 2 /) { next; }
1.278     albertel 4265: 	if ($name =~ /^type\0/) { next; }
1.186     albertel 4266: 	$namechoice.='<option value="'.$name.'">'.$name.'</option>';
                   4267:     }
                   4268:     $namechoice='<select name="scantron_CODElist">'.$namechoice.'</select>';
                   4269:     return $namechoice;
                   4270: }
                   4271: 
                   4272: sub scantron_CODEunique {
                   4273:     my $result='<nobr>
1.272     albertel 4274:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4275:                         value="yes" checked="checked" /> Yes </label>
1.186     albertel 4276:                 </nobr>
                   4277:                 <nobr>
1.272     albertel 4278:                  <label><input type="radio" name="scantron_CODEunique"
1.308     albertel 4279:                         value="no" /> No </label>
1.186     albertel 4280:                 </nobr>';
                   4281:     return $result;
                   4282: }
                   4283: 
1.75      albertel 4284: sub scantron_selectphase {
1.209     ng       4285:     my ($r,$file2grade) = @_;
1.324     albertel 4286:     my ($symb)=&get_symb($r);
1.75      albertel 4287:     if (!$symb) {return '';}
                   4288:     my $sequence_selector=&getSequenceDropDown($r,$symb);
1.324     albertel 4289:     my $default_form_data=&defaultFormData($symb);
                   4290:     my $grading_menu_button=&show_grading_menu_form($symb);
1.209     ng       4291:     my $file_selector=&scantron_uploads($file2grade);
1.82      albertel 4292:     my $format_selector=&scantron_scantab();
1.186     albertel 4293:     my $CODE_selector=&scantron_CODElist();
                   4294:     my $CODE_unique=&scantron_CODEunique();
1.75      albertel 4295:     my $result;
1.157     albertel 4296:     #FIXME allow instructor to be able to download the scantron file
                   4297:     # and to upload it,
1.75      albertel 4298:     $result.= <<SCANTRONFORM;
1.162     albertel 4299:     <table width="100%" border="0">
1.75      albertel 4300:     <tr>
1.226     albertel 4301:      <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantron_process">
1.75      albertel 4302:       <td bgcolor="#777777">
1.203     albertel 4303:        <input type="hidden" name="command" value="scantron_warning" />
1.162     albertel 4304:         $default_form_data
1.75      albertel 4305:         <table width="100%" border="0">
                   4306:           <tr bgcolor="#e6ffff">
1.174     albertel 4307:             <td colspan="2">
                   4308:               &nbsp;<b>Specify file and which Folder/Sequence to grade</b>
1.75      albertel 4309:             </td>
                   4310:           </tr>
                   4311:           <tr bgcolor="#ffffe6">
1.174     albertel 4312:             <td> Sequence to grade: </td><td> $sequence_selector </td>
1.75      albertel 4313:           </tr>
                   4314:           <tr bgcolor="#ffffe6">
1.174     albertel 4315:             <td> Filename of scoring office file: </td><td> $file_selector </td>
1.75      albertel 4316:           </tr>
1.82      albertel 4317:           <tr bgcolor="#ffffe6">
1.174     albertel 4318:             <td> Format of data file: </td><td> $format_selector </td>
1.82      albertel 4319:           </tr>
1.157     albertel 4320:           <tr bgcolor="#ffffe6">
1.186     albertel 4321:             <td> Saved CODEs to validate against: </td><td> $CODE_selector</td>
                   4322:           </tr>
                   4323:           <tr bgcolor="#ffffe6">
                   4324:             <td> Each CODE is only to be used once:</td><td> $CODE_unique </td>
                   4325:           </tr>
                   4326:           <tr bgcolor="#ffffe6">
1.187     albertel 4327: 	    <td> Options: </td>
                   4328:             <td>
1.272     albertel 4329: 	       <label><input type="checkbox" name="scantron_options_redo" value="redo_skipped"/> Do only previously skipped records</label> <br />
1.331     albertel 4330:                <label><input type="checkbox" name="scantron_options_ignore" value="ignore_corrections"/> Remove all exisiting corrections</label> <br />
                   4331:                <label><input type="checkbox" name="scantron_options_hidden" value="ignore_hidden"/> Skip hidden resources when grading</label>
1.187     albertel 4332: 	    </td>
                   4333:           </tr>
                   4334:           <tr bgcolor="#ffffe6">
1.174     albertel 4335:             <td colspan="2">
1.265     www      4336:               <input type="submit" value="Grading: Validate Scantron Records" />
1.162     albertel 4337:             </td>
                   4338:           </tr>
                   4339:         </table>
1.226     albertel 4340:        </td>
                   4341:      </form>
1.162     albertel 4342:     </tr>
                   4343: SCANTRONFORM
                   4344:    
                   4345:     $r->print($result);
                   4346: 
1.257     albertel 4347:     if (&Apache::lonnet::allowed('usc',$env{'request.role.domain'}) ||
                   4348:         &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 4349: 
                   4350:         $r->print(<<SCANTRONFORM);
                   4351:     <tr>
                   4352:       <td bgcolor="#777777">
                   4353:         <table width="100%" border="0">
                   4354:           <tr bgcolor="#e6ffff">
                   4355:             <td>
1.174     albertel 4356:               &nbsp;<b>Specify a Scantron data file to upload.</b>
1.162     albertel 4357:             </td>
                   4358:           </tr>
                   4359:           <tr bgcolor="#ffffe6">
                   4360:             <td>
                   4361: SCANTRONFORM
1.324     albertel 4362:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 4363:     my $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4364:     my $cnum= $env{'course.'.$env{'request.course.id'}.'.num'};
1.174     albertel 4365:     $r->print(<<UPLOAD);
                   4366:               <script type="text/javascript" language="javascript">
                   4367:     function checkUpload(formname) {
                   4368: 	if (formname.upfile.value == "") {
                   4369: 	    alert("Please use the browse button to select a file from your local directory.");
                   4370: 	    return false;
                   4371: 	}
                   4372: 	formname.submit();
                   4373:     }
                   4374:               </script>
                   4375: 
                   4376:               <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
                   4377:                 $default_form_data
                   4378:                 <input name='courseid' type='hidden' value='$cnum' />
                   4379:                 <input name='domainid' type='hidden' value='$cdom' />
                   4380:                 <input name='command' value='scantronupload_save' type='hidden' />
                   4381:                 File to upload:<input type="file" name="upfile" size="50" />
                   4382:                 <br />
                   4383:                 <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   4384:               </form>
                   4385: UPLOAD
1.162     albertel 4386: 
                   4387:         $r->print(<<SCANTRONFORM);
                   4388:             </td>
                   4389:           </tr>
1.75      albertel 4390:         </table>
                   4391:       </td>
                   4392:     </tr>
1.162     albertel 4393: SCANTRONFORM
                   4394:     }
1.187     albertel 4395:     $r->print(<<SCANTRONFORM);
                   4396:     <tr>
1.226     albertel 4397:       <form action='/adm/grades' name='scantron_download'>
                   4398:         <td bgcolor="#777777">
1.187     albertel 4399:           <input type="hidden" name="command" value="scantron_download" />
                   4400:           <table width="100%" border="0">
                   4401:             <tr bgcolor="#e6ffff">
                   4402:               <td colspan="2">
                   4403:                 &nbsp;<b>Download a scoring office file</b>
                   4404:               </td>
                   4405:             </tr>
                   4406:             <tr bgcolor="#ffffe6">
                   4407:               <td> Filename of scoring office file: </td><td> $file_selector </td>
                   4408:             </tr>
                   4409:             <tr bgcolor="#ffffe6">
                   4410:               <td colspan="2">
1.293     www      4411:                 <input type="submit" value="Download: Show List of Associated Files" />
1.187     albertel 4412:               </td>
                   4413:             </tr>
                   4414:           </table>
1.226     albertel 4415:         </td>
                   4416:       </form>
1.187     albertel 4417:     </tr>
                   4418: SCANTRONFORM
1.162     albertel 4419: 
                   4420:     $r->print(<<SCANTRONFORM);
1.75      albertel 4421:   </table>
1.81      albertel 4422: $grading_menu_button
1.75      albertel 4423: SCANTRONFORM
                   4424: 
1.162     albertel 4425:     return
1.75      albertel 4426: }
                   4427: 
1.82      albertel 4428: sub get_scantron_config {
                   4429:     my ($which) = @_;
                   4430:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.'/scantronformat.tab');
                   4431:     my %config;
1.157     albertel 4432:     #FIXME probably should move to XML it has already gotten a bit much now
1.82      albertel 4433:     foreach my $line (<$fh>) {
                   4434: 	my ($name,$descrip)=split(/:/,$line);
                   4435: 	if ($name ne $which ) { next; }
                   4436: 	chomp($line);
                   4437: 	my @config=split(/:/,$line);
                   4438: 	$config{'name'}=$config[0];
                   4439: 	$config{'description'}=$config[1];
                   4440: 	$config{'CODElocation'}=$config[2];
                   4441: 	$config{'CODEstart'}=$config[3];
                   4442: 	$config{'CODElength'}=$config[4];
                   4443: 	$config{'IDstart'}=$config[5];
                   4444: 	$config{'IDlength'}=$config[6];
                   4445: 	$config{'Qstart'}=$config[7];
                   4446: 	$config{'Qlength'}=$config[8];
                   4447: 	$config{'Qoff'}=$config[9];
                   4448: 	$config{'Qon'}=$config[10];
1.157     albertel 4449: 	$config{'PaperID'}=$config[11];
                   4450: 	$config{'PaperIDlength'}=$config[12];
                   4451: 	$config{'FirstName'}=$config[13];
                   4452: 	$config{'FirstNamelength'}=$config[14];
                   4453: 	$config{'LastName'}=$config[15];
                   4454: 	$config{'LastNamelength'}=$config[16];
1.82      albertel 4455: 	last;
                   4456:     }
                   4457:     return %config;
                   4458: }
                   4459: 
                   4460: sub username_to_idmap {
                   4461:     my ($classlist)= @_;
                   4462:     my %idmap;
                   4463:     foreach my $student (keys(%$classlist)) {
                   4464: 	$idmap{$classlist->{$student}->[&Apache::loncoursedata::CL_ID]}=
                   4465: 	    $student;
                   4466:     }
                   4467:     return %idmap;
                   4468: }
                   4469: 
1.157     albertel 4470: sub scantron_fixup_scanline {
                   4471:     my ($scantron_config,$scan_data,$line,$whichline,$field,$args)=@_;
                   4472:     if ($field eq 'ID') {
                   4473: 	if (length($args->{'newid'}) > $$scantron_config{'IDlength'}) {
1.186     albertel 4474: 	    return ($line,1,'New value too large');
1.157     albertel 4475: 	}
                   4476: 	if (length($args->{'newid'}) < $$scantron_config{'IDlength'}) {
                   4477: 	    $args->{'newid'}=sprintf('%-'.$$scantron_config{'IDlength'}.'s',
                   4478: 				     $args->{'newid'});
                   4479: 	}
                   4480: 	substr($line,$$scantron_config{'IDstart'}-1,
                   4481: 	       $$scantron_config{'IDlength'})=$args->{'newid'};
                   4482: 	if ($args->{'newid'}=~/^\s*$/) {
                   4483: 	    &scan_data($scan_data,"$whichline.user",
                   4484: 		       $args->{'username'}.':'.$args->{'domain'});
                   4485: 	}
1.186     albertel 4486:     } elsif ($field eq 'CODE') {
1.192     albertel 4487: 	if ($args->{'CODE_ignore_dup'}) {
                   4488: 	    &scan_data($scan_data,"$whichline.CODE_ignore_dup",'1');
                   4489: 	}
                   4490: 	&scan_data($scan_data,"$whichline.useCODE",'1');
                   4491: 	if ($args->{'CODE'} ne 'use_unfound') {
1.191     albertel 4492: 	    if (length($args->{'CODE'}) > $$scantron_config{'CODElength'}) {
                   4493: 		return ($line,1,'New CODE value too large');
                   4494: 	    }
                   4495: 	    if (length($args->{'CODE'}) < $$scantron_config{'CODElength'}) {
                   4496: 		$args->{'CODE'}=sprintf('%-'.$$scantron_config{'CODElength'}.'s',$args->{'CODE'});
                   4497: 	    }
                   4498: 	    substr($line,$$scantron_config{'CODEstart'}-1,
                   4499: 		   $$scantron_config{'CODElength'})=$args->{'CODE'};
1.186     albertel 4500: 	}
1.157     albertel 4501:     } elsif ($field eq 'answer') {
                   4502: 	my $length=$scantron_config->{'Qlength'};
                   4503: 	my $off=$scantron_config->{'Qoff'};
                   4504: 	my $on=$scantron_config->{'Qon'};
                   4505: 	my $answer=${off}x$length;
                   4506: 	if ($args->{'response'} eq 'none') {
                   4507: 	    &scan_data($scan_data,
                   4508: 		       "$whichline.no_bubble.".$args->{'question'},'1');
                   4509: 	} else {
1.274     albertel 4510: 	    if ($on eq 'letter') {
                   4511: 		my @alphabet=('A'..'Z');
                   4512: 		$answer=$alphabet[$args->{'response'}];
                   4513: 	    } elsif ($on eq 'number') {
                   4514: 		$answer=$args->{'response'}+1;
                   4515: 	    } else {
                   4516: 		substr($answer,$args->{'response'},1)=$on;
                   4517: 	    }
1.157     albertel 4518: 	    &scan_data($scan_data,
                   4519: 		       "$whichline.no_bubble.".$args->{'question'},undef,'1');
                   4520: 	}
                   4521: 	my $where=$length*($args->{'question'}-1)+$scantron_config->{'Qstart'};
                   4522: 	substr($line,$where-1,$length)=$answer;
                   4523:     }
                   4524:     return $line;
                   4525: }
                   4526: 
                   4527: sub scan_data {
                   4528:     my ($scan_data,$key,$value,$delete)=@_;
1.257     albertel 4529:     my $filename=$env{'form.scantron_selectfile'};
1.157     albertel 4530:     if (defined($value)) {
                   4531: 	$scan_data->{$filename.'_'.$key} = $value;
                   4532:     }
                   4533:     if ($delete) { delete($scan_data->{$filename.'_'.$key}); }
                   4534:     return $scan_data->{$filename.'_'.$key};
                   4535: }
                   4536: 
1.82      albertel 4537: sub scantron_parse_scanline {
1.194     albertel 4538:     my ($line,$whichline,$scantron_config,$scan_data,$justHeader)=@_;
1.82      albertel 4539:     my %record;
                   4540:     my $questions=substr($line,$$scantron_config{'Qstart'}-1);
                   4541:     my $data=substr($line,0,$$scantron_config{'Qstart'}-1);
1.278     albertel 4542:     if (!($$scantron_config{'CODElocation'} eq 0 ||
                   4543: 	  $$scantron_config{'CODElocation'} eq 'none')) {
                   4544: 	if ($$scantron_config{'CODElocation'} < 0 ||
                   4545: 	    $$scantron_config{'CODElocation'} eq 'letter' ||
                   4546: 	    $$scantron_config{'CODElocation'} eq 'number') {
1.191     albertel 4547: 	    $record{'scantron.CODE'}=substr($data,
                   4548: 					    $$scantron_config{'CODEstart'}-1,
1.83      albertel 4549: 					    $$scantron_config{'CODElength'});
1.191     albertel 4550: 	    if (&scan_data($scan_data,"$whichline.useCODE")) {
                   4551: 		$record{'scantron.useCODE'}=1;
                   4552: 	    }
1.192     albertel 4553: 	    if (&scan_data($scan_data,"$whichline.CODE_ignore_dup")) {
                   4554: 		$record{'scantron.CODE_ignore_dup'}=1;
                   4555: 	    }
1.82      albertel 4556: 	} else {
                   4557: 	    #FIXME interpret first N questions
                   4558: 	}
                   4559:     }
1.83      albertel 4560:     $record{'scantron.ID'}=substr($data,$$scantron_config{'IDstart'}-1,
                   4561: 				  $$scantron_config{'IDlength'});
1.157     albertel 4562:     $record{'scantron.PaperID'}=
                   4563: 	substr($data,$$scantron_config{'PaperID'}-1,
                   4564: 	       $$scantron_config{'PaperIDlength'});
                   4565:     $record{'scantron.FirstName'}=
                   4566: 	substr($data,$$scantron_config{'FirstName'}-1,
                   4567: 	       $$scantron_config{'FirstNamelength'});
                   4568:     $record{'scantron.LastName'}=
                   4569: 	substr($data,$$scantron_config{'LastName'}-1,
                   4570: 	       $$scantron_config{'LastNamelength'});
1.194     albertel 4571:     if ($justHeader) { return \%record; }
                   4572: 
1.82      albertel 4573:     my @alphabet=('A'..'Z');
                   4574:     my $questnum=0;
                   4575:     while ($questions) {
                   4576: 	$questnum++;
                   4577: 	my $currentquest=substr($questions,0,$$scantron_config{'Qlength'});
                   4578: 	substr($questions,0,$$scantron_config{'Qlength'})='';
1.83      albertel 4579: 	if (length($currentquest) < $$scantron_config{'Qlength'}) { next; }
1.239     albertel 4580: 	if ($$scantron_config{'Qon'} eq 'letter') {
1.274     albertel 4581: 	    if ($currentquest eq '?') {
                   4582: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4583: 		$record{"scantron.$questnum.answer"}='';
                   4584: 	    } elsif (!$currentquest 
                   4585: 		     || $currentquest eq $$scantron_config{'Qoff'}
                   4586: 		     || $currentquest !~ /^[A-Z]$/) {
1.239     albertel 4587: 		$record{"scantron.$questnum.answer"}='';
                   4588: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4589: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4590: 		}
                   4591: 	    } else {
                   4592: 		$record{"scantron.$questnum.answer"}=$currentquest;
                   4593: 	    }
                   4594: 	} elsif ($$scantron_config{'Qon'} eq 'number') {
1.274     albertel 4595: 	    if ($currentquest eq '?') {
                   4596: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4597: 		$record{"scantron.$questnum.answer"}='';
                   4598: 		} elsif (!$currentquest 
                   4599: 			 || $currentquest eq $$scantron_config{'Qoff'} 
                   4600: 			 || $currentquest !~ /^\d$/) {
1.239     albertel 4601: 		$record{"scantron.$questnum.answer"}='';
                   4602: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4603: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4604: 		}
                   4605: 	    } else {
                   4606: 		$record{"scantron.$questnum.answer"}=
                   4607: 		    $alphabet[$currentquest-1];
                   4608: 	    }
1.82      albertel 4609: 	} else {
1.239     albertel 4610: 	    my @array=split($$scantron_config{'Qon'},$currentquest,-1);
                   4611: 	    if (length($array[0]) eq $$scantron_config{'Qlength'}) {
                   4612: 		$record{"scantron.$questnum.answer"}='';
                   4613: 		if (!&scan_data($scan_data,"$whichline.no_bubble.$questnum")) {
                   4614: 		    push(@{$record{"scantron.missingerror"}},$questnum);
                   4615: 		}
                   4616: 	    } else {
                   4617: 		$record{"scantron.$questnum.answer"}=
                   4618: 		    $alphabet[length($array[0])];
                   4619: 	    }
                   4620: 	    if (scalar(@array) gt 2) {
                   4621: 		push(@{$record{'scantron.doubleerror'}},$questnum);
                   4622: 		my @ans=@array;
                   4623: 		my $i=length($ans[0]);shift(@ans);
                   4624: 		while ($#ans) {
                   4625: 		    $i+=length($ans[0])+1;
                   4626: 		    $record{"scantron.$questnum.answer"}.=$alphabet[$i];
                   4627: 		    shift(@ans);
                   4628: 		}
                   4629: 	    }
1.82      albertel 4630: 	}
                   4631:     }
1.83      albertel 4632:     $record{'scantron.maxquest'}=$questnum;
                   4633:     return \%record;
1.82      albertel 4634: }
                   4635: 
                   4636: sub scantron_add_delay {
1.140     albertel 4637:     my ($delayqueue,$scanline,$errormessage,$errorcode)=@_;
                   4638:     push(@$delayqueue,
                   4639: 	 {'line' => $scanline, 'emsg' => $errormessage,
                   4640: 	  'ecode' => $errorcode }
                   4641: 	 );
1.82      albertel 4642: }
                   4643: 
                   4644: sub scantron_find_student {
1.157     albertel 4645:     my ($scantron_record,$scan_data,$idmap,$line)=@_;
1.83      albertel 4646:     my $scanID=$$scantron_record{'scantron.ID'};
1.157     albertel 4647:     if ($scanID =~ /^\s*$/) {
                   4648:  	return &scan_data($scan_data,"$line.user");
                   4649:     }
1.83      albertel 4650:     foreach my $id (keys(%$idmap)) {
1.157     albertel 4651:  	if (lc($id) eq lc($scanID)) {
                   4652:  	    return $$idmap{$id};
                   4653:  	}
1.83      albertel 4654:     }
                   4655:     return undef;
                   4656: }
                   4657: 
                   4658: sub scantron_filter {
                   4659:     my ($curres)=@_;
1.331     albertel 4660: 
                   4661:     if (ref($curres) && $curres->is_problem()) {
                   4662: 	# if the user has asked to not have either hidden
                   4663: 	# or 'randomout' controlled resources to be graded
                   4664: 	# don't include them
                   4665: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   4666: 	    && $curres->randomout) {
                   4667: 	    return 0;
                   4668: 	}
1.83      albertel 4669: 	return 1;
                   4670:     }
                   4671:     return 0;
1.82      albertel 4672: }
                   4673: 
1.157     albertel 4674: sub scantron_process_corrections {
                   4675:     my ($r) = @_;
1.257     albertel 4676:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 4677:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4678:     my $classlist=&Apache::loncoursedata::get_classlist();
1.257     albertel 4679:     my $which=$env{'form.scantron_line'};
1.200     albertel 4680:     my $line=&scantron_get_line($scanlines,$scan_data,$which);
1.157     albertel 4681:     my ($skip,$err,$errmsg);
1.257     albertel 4682:     if ($env{'form.scantron_skip_record'}) {
1.157     albertel 4683: 	$skip=1;
1.257     albertel 4684:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)ID$/) {
                   4685: 	my $newstudent=$env{'form.scantron_username'}.':'.
                   4686: 	    $env{'form.scantron_domain'};
1.157     albertel 4687: 	my $newid=$classlist->{$newstudent}->[&Apache::loncoursedata::CL_ID];
                   4688: 	($line,$err,$errmsg)=
                   4689: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
                   4690: 				     'ID',{'newid'=>$newid,
1.257     albertel 4691: 				    'username'=>$env{'form.scantron_username'},
                   4692: 				    'domain'=>$env{'form.scantron_domain'}});
                   4693:     } elsif ($env{'form.scantron_corrections'} =~ /^(duplicate|incorrect)CODE$/) {
                   4694: 	my $resolution=$env{'form.scantron_CODE_resolution'};
1.190     albertel 4695: 	my $newCODE;
1.192     albertel 4696: 	my %args;
1.190     albertel 4697: 	if      ($resolution eq 'use_unfound') {
1.191     albertel 4698: 	    $newCODE='use_unfound';
1.190     albertel 4699: 	} elsif ($resolution eq 'use_found') {
1.257     albertel 4700: 	    $newCODE=$env{'form.scantron_CODE_selectedvalue'};
1.190     albertel 4701: 	} elsif ($resolution eq 'use_typed') {
1.257     albertel 4702: 	    $newCODE=$env{'form.scantron_CODE_newvalue'};
1.194     albertel 4703: 	} elsif ($resolution =~ /^use_closest_(\d+)/) {
1.257     albertel 4704: 	    $newCODE=$env{"form.scantron_CODE_closest_$1"};
1.190     albertel 4705: 	}
1.257     albertel 4706: 	if ($env{'form.scantron_corrections'} eq 'duplicateCODE') {
1.192     albertel 4707: 	    $args{'CODE_ignore_dup'}=1;
                   4708: 	}
                   4709: 	$args{'CODE'}=$newCODE;
1.186     albertel 4710: 	($line,$err,$errmsg)=
                   4711: 	    &scantron_fixup_scanline(\%scantron_config,$scan_data,$line,$which,
1.192     albertel 4712: 				     'CODE',\%args);
1.257     albertel 4713:     } elsif ($env{'form.scantron_corrections'} =~ /^(missing|double)bubble$/) {
                   4714: 	foreach my $question (split(',',$env{'form.scantron_questions'})) {
1.157     albertel 4715: 	    ($line,$err,$errmsg)=
                   4716: 		&scantron_fixup_scanline(\%scantron_config,$scan_data,$line,
                   4717: 					 $which,'answer',
                   4718: 					 { 'question'=>$question,
1.257     albertel 4719: 		       'response'=>$env{"form.scantron_correct_Q_$question"}});
1.157     albertel 4720: 	    if ($err) { last; }
                   4721: 	}
                   4722:     }
                   4723:     if ($err) {
1.287     albertel 4724: 	$r->print("<font color='red'>Unable to accept last correction, an error occurred :$errmsg:</font>");
1.157     albertel 4725:     } else {
1.200     albertel 4726: 	&scantron_put_line($scanlines,$scan_data,$which,$line,$skip);
1.157     albertel 4727: 	&scantron_putfile($scanlines,$scan_data);
                   4728:     }
                   4729: }
                   4730: 
1.200     albertel 4731: sub reset_skipping_status {
                   4732:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4733:     &scan_data($scan_data,'remember_skipping',undef,1);
                   4734:     &scantron_putfile(undef,$scan_data);
                   4735: }
                   4736: 
                   4737: sub allow_skipping {
                   4738:     my ($scan_data,$i)=@_;
                   4739:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4740:     delete($remembered{$i});
                   4741:     &scan_data($scan_data,'remember_skipping',join(':',%remembered));
                   4742: }
                   4743: 
                   4744: sub should_be_skipped {
                   4745:     my ($scan_data,$i)=@_;
1.257     albertel 4746:     if ($env{'form.scantron_options_redo'} !~ /^redo_/) {
1.200     albertel 4747: 	# not redoing old skips
                   4748: 	return 0;
                   4749:     }
                   4750:     my %remembered=split(':',&scan_data($scan_data,'remember_skipping'));
                   4751:     if (exists($remembered{$i})) { return 0; }
                   4752:     return 1;
                   4753: }
                   4754: 
                   4755: sub remember_current_skipped {
                   4756:     my ($scanlines,$scan_data)=&scantron_getfile();
                   4757:     my %to_remember;
                   4758:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   4759: 	if ($scanlines->{'skipped'}[$i]) {
                   4760: 	    $to_remember{$i}=1;
                   4761: 	}
                   4762:     }
                   4763:     &scan_data($scan_data,'remember_skipping',join(':',%to_remember));
                   4764:     &scantron_putfile(undef,$scan_data);
                   4765: }
                   4766: 
                   4767: sub check_for_error {
                   4768:     my ($r,$result)=@_;
                   4769:     if ($result ne 'ok' && $result ne 'not_found' ) {
                   4770: 	$r->print("An error occured ($result) when trying to Remove the existing corrections.");
                   4771:     }
                   4772: }
1.157     albertel 4773: 
1.203     albertel 4774: sub scantron_warning_screen {
                   4775:     my ($button_text)=@_;
1.257     albertel 4776:     my $title=&Apache::lonnet::gettitle($env{'form.selectpage'});
1.284     albertel 4777:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
                   4778:     my $CODElist="a";
                   4779:     if ($scantron_config{'CODElocation'} &&
                   4780: 	$scantron_config{'CODEstart'} &&
                   4781: 	$scantron_config{'CODElength'}) {
                   4782: 	$CODElist=$env{'form.scantron_CODElist'};
                   4783: 	if ($CODElist eq '') { $CODElist='<font color="red">None</font>'; }
                   4784: 	$CODElist=
                   4785: 	    '<tr><td><b>List of CODES to validate against:</b></td><td><tt>'.
                   4786: 	    $CODElist.'</tt></td></tr>';
                   4787:     }
1.203     albertel 4788:     return (<<STUFF);
                   4789: <p>
                   4790: <font color="red">Please double check the information
                   4791:                  below before clicking on '$button_text'</font>
                   4792: </p>
                   4793: <table>
1.284     albertel 4794: <tr><td><b>Sequence to be Graded:</b></td><td>$title</td></tr>
1.257     albertel 4795: <tr><td><b>Data File that will be used:</b></td><td><tt>$env{'form.scantron_selectfile'}</tt></td></tr>
1.284     albertel 4796: $CODElist
1.203     albertel 4797: </table>
                   4798: </font>
                   4799: <br />
                   4800: <p> If this information is correct, please click on '$button_text'.</p>
                   4801: <p> If something is incorrect, please click the 'Grading Menu' button to start over.</p>
                   4802: 
                   4803: <br />
                   4804: STUFF
                   4805: }
                   4806: 
                   4807: sub scantron_do_warning {
                   4808:     my ($r)=@_;
1.324     albertel 4809:     my ($symb)=&get_symb($r);
1.203     albertel 4810:     if (!$symb) {return '';}
1.324     albertel 4811:     my $default_form_data=&defaultFormData($symb);
1.203     albertel 4812:     $r->print(&scantron_form_start().$default_form_data);
1.257     albertel 4813:     if ( $env{'form.selectpage'} eq '' ||
                   4814: 	 $env{'form.scantron_selectfile'} eq '' ||
                   4815: 	 $env{'form.scantron_format'} eq '' ) {
1.237     albertel 4816: 	$r->print("<p>You have forgetten to specify some information. Please go Back and try again.</p>");
1.257     albertel 4817: 	if ( $env{'form.selectpage'} eq '') {
1.237     albertel 4818: 	    $r->print('<p><font color="red">You have not selected a Sequence to grade</font></p>');
                   4819: 	} 
1.257     albertel 4820: 	if ( $env{'form.scantron_selectfile'} eq '') {
1.237     albertel 4821: 	    $r->print('<p><font color="red">You have not selected a file that contains the student\'s response data.</font></p>');
                   4822: 	} 
1.257     albertel 4823: 	if ( $env{'form.scantron_format'} eq '') {
1.237     albertel 4824: 	    $r->print('<p><font color="red">You have not selected a the format of the student\'s response data.</font></p>');
                   4825: 	} 
                   4826:     } else {
1.265     www      4827: 	my $warning=&scantron_warning_screen('Grading: Validate Records');
1.237     albertel 4828: 	$r->print(<<STUFF);
1.203     albertel 4829: $warning
1.265     www      4830: <input type="submit" name="submit" value="Grading: Validate Records" />
1.203     albertel 4831: <input type="hidden" name="command" value="scantron_validate" />
                   4832: STUFF
1.237     albertel 4833:     }
1.352   ! albertel 4834:     $r->print("</form><br />".&show_grading_menu_form($symb));
1.203     albertel 4835:     return '';
                   4836: }
                   4837: 
                   4838: sub scantron_form_start {
                   4839:     my ($max_bubble)=@_;
                   4840:     my $result= <<SCANTRONFORM;
                   4841: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
1.257     albertel 4842:   <input type="hidden" name="selectpage" value="$env{'form.selectpage'}" />
                   4843:   <input type="hidden" name="scantron_format" value="$env{'form.scantron_format'}" />
                   4844:   <input type="hidden" name="scantron_selectfile" value="$env{'form.scantron_selectfile'}" />
1.218     albertel 4845:   <input type="hidden" name="scantron_maxbubble" value="$max_bubble" />
1.257     albertel 4846:   <input type="hidden" name="scantron_CODElist" value="$env{'form.scantron_CODElist'}" />
                   4847:   <input type="hidden" name="scantron_CODEunique" value="$env{'form.scantron_CODEunique'}" />
                   4848:   <input type="hidden" name="scantron_options_redo" value="$env{'form.scantron_options_redo'}" />
                   4849:   <input type="hidden" name="scantron_options_ignore" value="$env{'form.scantron_options_ignore'}" />
1.331     albertel 4850:   <input type="hidden" name="scantron_options_hidden" value="$env{'form.scantron_options_hidden'}" />
1.203     albertel 4851: SCANTRONFORM
                   4852:     return $result;
                   4853: }
                   4854: 
1.157     albertel 4855: sub scantron_validate_file {
                   4856:     my ($r) = @_;
1.324     albertel 4857:     my ($symb)=&get_symb($r);
1.157     albertel 4858:     if (!$symb) {return '';}
1.324     albertel 4859:     my $default_form_data=&defaultFormData($symb);
1.200     albertel 4860:     
                   4861:     # do the detection of only doing skipped records first befroe we delete
                   4862:     # them  when doing the corrections reset
1.257     albertel 4863:     if ($env{'form.scantron_options_redo'} ne 'redo_skipped_ready') {
1.200     albertel 4864: 	&reset_skipping_status();
                   4865:     }
1.257     albertel 4866:     if ($env{'form.scantron_options_redo'} eq 'redo_skipped') {
1.200     albertel 4867: 	&remember_current_skipped();
                   4868: 	&scantron_remove_file('skipped');
1.257     albertel 4869: 	$env{'form.scantron_options_redo'}='redo_skipped_ready';
1.200     albertel 4870:     }
                   4871: 
1.257     albertel 4872:     if ($env{'form.scantron_options_ignore'} eq 'ignore_corrections') {
1.200     albertel 4873: 	&check_for_error($r,&scantron_remove_file('corrected'));
                   4874: 	&check_for_error($r,&scantron_remove_file('skipped'));
                   4875: 	&check_for_error($r,&scantron_remove_scan_data());
1.257     albertel 4876: 	$env{'form.scantron_options_ignore'}='done';
1.192     albertel 4877:     }
1.200     albertel 4878: 
1.257     albertel 4879:     if ($env{'form.scantron_corrections'}) {
1.157     albertel 4880: 	&scantron_process_corrections($r);
                   4881:     }
1.191     albertel 4882:     $r->print("<p>Gathering neccessary info.</p>");$r->rflush();
1.157     albertel 4883:     #get the student pick code ready
                   4884:     $r->print(&Apache::loncommon::studentbrowser_javascript());
1.330     albertel 4885:     my $max_bubble=&scantron_get_maxbubble();
1.203     albertel 4886:     my $result=&scantron_form_start($max_bubble).$default_form_data;
1.157     albertel 4887:     $r->print($result);
                   4888:     
1.334     albertel 4889:     my @validate_phases=( 'sequence',
                   4890: 			  'ID',
1.157     albertel 4891: 			  'CODE',
                   4892: 			  'doublebubble',
                   4893: 			  'missingbubbles');
1.257     albertel 4894:     if (!$env{'form.validatepass'}) {
                   4895: 	$env{'form.validatepass'} = 0;
1.157     albertel 4896:     }
1.257     albertel 4897:     my $currentphase=$env{'form.validatepass'};
1.157     albertel 4898: 
                   4899:     my $stop=0;
                   4900:     while (!$stop && $currentphase < scalar(@validate_phases)) {
                   4901: 	$r->print("<p> Validating ".$validate_phases[$currentphase]."</p>");
                   4902: 	$r->rflush();
                   4903: 	my $which="scantron_validate_".$validate_phases[$currentphase];
                   4904: 	{
                   4905: 	    no strict 'refs';
                   4906: 	    ($stop,$currentphase)=&$which($r,$currentphase);
                   4907: 	}
                   4908:     }
                   4909:     if (!$stop) {
1.203     albertel 4910: 	my $warning=&scantron_warning_screen('Start Grading');
                   4911: 	$r->print(<<STUFF);
                   4912: Validation process complete.<br />
                   4913: $warning
                   4914: <input type="submit" name="submit" value="Start Grading" />
                   4915: <input type="hidden" name="command" value="scantron_process" />
                   4916: STUFF
                   4917: 
1.157     albertel 4918:     } else {
                   4919: 	$r->print('<input type="hidden" name="command" value="scantron_validate" />');
                   4920: 	$r->print("<input type='hidden' name='validatepass' value='".$currentphase."' />");
                   4921:     }
                   4922:     if ($stop) {
1.334     albertel 4923: 	if ($validate_phases[$currentphase] eq 'sequence') {
                   4924: 	    $r->print('<input type="submit" name="submit" value="Ignore -> " />');
                   4925: 	    $r->print(' this error <br />');
                   4926: 
                   4927: 	    $r->print(" <p>Or click the 'Grading Menu' button to start over.</p>");
                   4928: 	} else {
                   4929: 	    $r->print('<input type="submit" name="submit" value="Continue ->" />');
                   4930: 	    $r->print(' using corrected info <br />');
                   4931: 	    $r->print("<input type='submit' value='Skip' name='scantron_skip_record' />");
                   4932: 	    $r->print(" this scanline saving it for later.");
                   4933: 	}
1.157     albertel 4934:     }
1.352   ! albertel 4935:     $r->print(" </form><br />".&show_grading_menu_form($symb));
1.157     albertel 4936:     return '';
                   4937: }
                   4938: 
1.200     albertel 4939: sub scantron_remove_file {
1.192     albertel 4940:     my ($which)=@_;
1.257     albertel 4941:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4942:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4943:     my $file='scantron_';
1.200     albertel 4944:     if ($which eq 'corrected' || $which eq 'skipped') {
                   4945: 	$file.=$which.'_';
1.192     albertel 4946:     } else {
                   4947: 	return 'refused';
                   4948:     }
1.257     albertel 4949:     $file.=$env{'form.scantron_selectfile'};
1.200     albertel 4950:     return &Apache::lonnet::removeuserfile($cname,$cdom,$file);
                   4951: }
                   4952: 
                   4953: sub scantron_remove_scan_data {
1.257     albertel 4954:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4955:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.192     albertel 4956:     my @keys=&Apache::lonnet::getkeys('nohist_scantrondata',$cdom,$cname);
                   4957:     my @todelete;
1.257     albertel 4958:     my $filename=$env{'form.scantron_selectfile'};
1.192     albertel 4959:     foreach my $key (@keys) {
                   4960: 	if ($key=~/^\Q$filename\E_/) {
1.257     albertel 4961: 	    if ($env{'form.scantron_options_redo'} eq 'redo_skipped_ready' &&
1.200     albertel 4962: 		$key=~/remember_skipping/) {
                   4963: 		next;
                   4964: 	    }
1.192     albertel 4965: 	    push(@todelete,$key);
                   4966: 	}
                   4967:     }
1.200     albertel 4968:     my $result;
1.192     albertel 4969:     if (@todelete) {
1.200     albertel 4970: 	$result=&Apache::lonnet::del('nohist_scantrondata',\@todelete,$cdom,$cname);
1.192     albertel 4971:     }
                   4972:     return $result;
                   4973: }
                   4974: 
1.157     albertel 4975: sub scantron_getfile {
1.200     albertel 4976:     #FIXME really would prefer a scantron directory
1.257     albertel 4977:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4978:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.157     albertel 4979:     my $lines;
                   4980:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4981: 		       'scantron_orig_'.$env{'form.scantron_selectfile'});
1.157     albertel 4982:     my %scanlines;
                   4983:     $scanlines{'orig'}=[(split("\n",$lines,-1))];
                   4984:     my $temp=$scanlines{'orig'};
                   4985:     $scanlines{'count'}=$#$temp;
                   4986: 
                   4987:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4988: 		       'scantron_corrected_'.$env{'form.scantron_selectfile'});
1.157     albertel 4989:     if ($lines eq '-1') {
                   4990: 	$scanlines{'corrected'}=[];
                   4991:     } else {
                   4992: 	$scanlines{'corrected'}=[(split("\n",$lines,-1))];
                   4993:     }
                   4994:     $lines=&Apache::lonnet::getfile('/uploaded/'.$cdom.'/'.$cname.'/'.
1.257     albertel 4995: 		       'scantron_skipped_'.$env{'form.scantron_selectfile'});
1.157     albertel 4996:     if ($lines eq '-1') {
                   4997: 	$scanlines{'skipped'}=[];
                   4998:     } else {
                   4999: 	$scanlines{'skipped'}=[(split("\n",$lines,-1))];
                   5000:     }
1.175     albertel 5001:     my @tmp=&Apache::lonnet::dump('nohist_scantrondata',$cdom,$cname);
1.157     albertel 5002:     if ($tmp[0] =~ /^(error:|no_such_host)/) { @tmp=(); }
                   5003:     my %scan_data = @tmp;
                   5004:     return (\%scanlines,\%scan_data);
                   5005: }
                   5006: 
                   5007: sub lonnet_putfile {
                   5008:     my ($contents,$filename)=@_;
1.257     albertel 5009:     my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5010:     my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5011:     $env{'form.sillywaytopassafilearound'}=$contents;
1.275     albertel 5012:     &Apache::lonnet::finishuserfileupload($docuname,$docudom,'sillywaytopassafilearound',$filename);
1.157     albertel 5013: 
                   5014: }
                   5015: 
                   5016: sub scantron_putfile {
                   5017:     my ($scanlines,$scan_data) = @_;
1.200     albertel 5018:     #FIXME really would prefer a scantron directory
1.257     albertel 5019:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5020:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.200     albertel 5021:     if ($scanlines) {
                   5022: 	my $prefix='scantron_';
1.157     albertel 5023: # no need to update orig, shouldn't change
                   5024: #   &lonnet_putfile(join("\n",@{$scanlines->{'orig'}}),$prefix.'orig_'.
1.257     albertel 5025: #		    $env{'form.scantron_selectfile'});
1.200     albertel 5026: 	&lonnet_putfile(join("\n",@{$scanlines->{'corrected'}}),
                   5027: 			$prefix.'corrected_'.
1.257     albertel 5028: 			$env{'form.scantron_selectfile'});
1.200     albertel 5029: 	&lonnet_putfile(join("\n",@{$scanlines->{'skipped'}}),
                   5030: 			$prefix.'skipped_'.
1.257     albertel 5031: 			$env{'form.scantron_selectfile'});
1.200     albertel 5032:     }
1.175     albertel 5033:     &Apache::lonnet::put('nohist_scantrondata',$scan_data,$cdom,$cname);
1.157     albertel 5034: }
                   5035: 
                   5036: sub scantron_get_line {
1.200     albertel 5037:     my ($scanlines,$scan_data,$i)=@_;
                   5038:     if (&should_be_skipped($scan_data,$i)) { return undef; }
                   5039:     if ($scanlines->{'skipped'}[$i]) { return undef; }
1.157     albertel 5040:     if ($scanlines->{'corrected'}[$i]) {return $scanlines->{'corrected'}[$i];}
                   5041:     return $scanlines->{'orig'}[$i]; 
                   5042: }
                   5043: 
1.200     albertel 5044: sub get_todo_count {
                   5045:     my ($scanlines,$scan_data)=@_;
                   5046:     my $count=0;
                   5047:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
                   5048: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
                   5049: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5050: 	$count++;
                   5051:     }
                   5052:     return $count;
                   5053: }
                   5054: 
1.157     albertel 5055: sub scantron_put_line {
1.200     albertel 5056:     my ($scanlines,$scan_data,$i,$newline,$skip)=@_;
1.157     albertel 5057:     if ($skip) {
                   5058: 	$scanlines->{'skipped'}[$i]=$newline;
1.200     albertel 5059: 	&allow_skipping($scan_data,$i);
1.157     albertel 5060: 	return;
                   5061:     }
                   5062:     $scanlines->{'corrected'}[$i]=$newline;
                   5063: }
                   5064: 
1.334     albertel 5065: sub scantron_filter_not_exam {
                   5066:     my ($curres)=@_;
                   5067:     
                   5068:     if (ref($curres) && $curres->is_problem() && !$curres->is_exam()) {
                   5069: 	# if the user has asked to not have either hidden
                   5070: 	# or 'randomout' controlled resources to be graded
                   5071: 	# don't include them
                   5072: 	if ($env{'form.scantron_options_hidden'} eq 'ignore_hidden'
                   5073: 	    && $curres->randomout) {
                   5074: 	    return 0;
                   5075: 	}
                   5076: 	return 1;
                   5077:     }
                   5078:     return 0;
                   5079: }
                   5080: 
                   5081: sub scantron_validate_sequence {
                   5082:     my ($r,$currentphase) = @_;
                   5083: 
                   5084:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5085:     my (undef,undef,$sequence)=
                   5086: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
                   5087: 
                   5088:     my $map=$navmap->getResourceByUrl($sequence);
                   5089: 
                   5090:     $r->print('<input type="hidden" name="validate_sequence_exam"
                   5091:                                     value="ignore" />');
                   5092:     if ($env{'form.validate_sequence_exam'} ne 'ignore') {
                   5093: 	my @resources=
                   5094: 	    $navmap->retrieveResources($map,\&scantron_filter_not_exam,1,0);
                   5095: 	if (@resources) {
                   5096: 	    $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>");
                   5097: 	    return (1,$currentphase);
                   5098: 	}
                   5099:     }
                   5100: 
                   5101:     return (0,$currentphase+1);
                   5102: }
                   5103: 
1.157     albertel 5104: sub scantron_validate_ID {
                   5105:     my ($r,$currentphase) = @_;
                   5106:     
                   5107:     #get student info
                   5108:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5109:     my %idmap=&username_to_idmap($classlist);
                   5110: 
                   5111:     #get scantron line setup
1.257     albertel 5112:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5113:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5114: 
                   5115:     my %found=('ids'=>{},'usernames'=>{});
                   5116:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5117: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5118: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5119: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5120: 						 $scan_data);
                   5121: 	my $id=$$scan_record{'scantron.ID'};
                   5122: 	my $found;
                   5123: 	foreach my $checkid (keys(%idmap)) {
                   5124: 	    if (lc($checkid) eq lc($id)) { $found=$checkid;last; }
                   5125: 	}
                   5126: 	if ($found) {
                   5127: 	    my $username=$idmap{$found};
                   5128: 	    if ($found{'ids'}{$found}) {
                   5129: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5130: 					 $line,'duplicateID',$found);
1.194     albertel 5131: 		return(1,$currentphase);
1.157     albertel 5132: 	    } elsif ($found{'usernames'}{$username}) {
                   5133: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5134: 					 $line,'duplicateID',$username);
1.194     albertel 5135: 		return(1,$currentphase);
1.157     albertel 5136: 	    }
1.186     albertel 5137: 	    #FIXME store away line we previously saw the ID on to use above
1.157     albertel 5138: 	    $found{'ids'}{$found}++;
                   5139: 	    $found{'usernames'}{$username}++;
                   5140: 	} else {
                   5141: 	    if ($id =~ /^\s*$/) {
1.158     albertel 5142: 		my $username=&scan_data($scan_data,"$i.user");
1.157     albertel 5143: 		if (defined($username) && $found{'usernames'}{$username}) {
                   5144: 		    &scantron_get_correction($r,$i,$scan_record,
                   5145: 					     \%scantron_config,
                   5146: 					     $line,'duplicateID',$username);
1.194     albertel 5147: 		    return(1,$currentphase);
1.157     albertel 5148: 		} elsif (!defined($username)) {
                   5149: 		    &scantron_get_correction($r,$i,$scan_record,
                   5150: 					     \%scantron_config,
                   5151: 					     $line,'incorrectID');
1.194     albertel 5152: 		    return(1,$currentphase);
1.157     albertel 5153: 		}
                   5154: 		$found{'usernames'}{$username}++;
                   5155: 	    } else {
                   5156: 		&scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5157: 					 $line,'incorrectID');
1.194     albertel 5158: 		return(1,$currentphase);
1.157     albertel 5159: 	    }
                   5160: 	}
                   5161:     }
                   5162: 
                   5163:     return (0,$currentphase+1);
                   5164: }
                   5165: 
                   5166: sub scantron_get_correction {
                   5167:     my ($r,$i,$scan_record,$scan_config,$line,$error,$arg)=@_;
                   5168: 
                   5169: #FIXME in the case of a duplicated ID the previous line, probaly need
                   5170: #to show both the current line and the previous one and allow skipping
                   5171: #the previous one or the current one
                   5172: 
1.161     albertel 5173:     $r->print("<p><b>An error was detected ($error)</b>");
1.333     albertel 5174:     if ( $$scan_record{'scantron.PaperID'} =~ /\S/) {
1.157     albertel 5175: 	$r->print(" for PaperID <tt>".
                   5176: 		  $$scan_record{'scantron.PaperID'}."</tt> \n");
                   5177:     } else {
                   5178: 	$r->print(" in scanline $i <pre>".
                   5179: 		  $line."</pre> \n");
                   5180:     }
1.242     albertel 5181:     my $message="<p>The ID on the form is  <tt>".
                   5182: 	$$scan_record{'scantron.ID'}."</tt><br />\n".
                   5183: 	"The name on the paper is ".
                   5184: 	$$scan_record{'scantron.LastName'}.",".
                   5185: 	$$scan_record{'scantron.FirstName'}."</p>";
                   5186: 
1.157     albertel 5187:     $r->print('<input type="hidden" name="scantron_corrections" value="'.$error.'" />'."\n");
                   5188:     $r->print('<input type="hidden" name="scantron_line" value="'.$i.'" />'."\n");
                   5189:     if ($error =~ /ID$/) {
1.186     albertel 5190: 	if ($error eq 'incorrectID') {
1.157     albertel 5191: 	    $r->print("The encoded ID is not in the classlist</p>\n");
                   5192: 	} elsif ($error eq 'duplicateID') {
                   5193: 	    $r->print("The encoded ID has also been used by a previous paper $arg</p>\n");
                   5194: 	}
1.242     albertel 5195: 	$r->print($message);
1.157     albertel 5196: 	$r->print("<p>How should I handle this? <br /> \n");
                   5197: 	$r->print("\n<ul><li> ");
                   5198: 	#FIXME it would be nice if this sent back the user ID and
                   5199: 	#could do partial userID matches
                   5200: 	$r->print(&Apache::loncommon::selectstudent_link('scantronupload',
                   5201: 				       'scantron_username','scantron_domain'));
                   5202: 	$r->print(": <input type='text' name='scantron_username' value='' />");
                   5203: 	$r->print("\n@".
1.257     albertel 5204: 		 &Apache::loncommon::select_dom_form($env{'request.role.domain'},'scantron_domain'));
1.157     albertel 5205: 
                   5206: 	$r->print('</li>');
1.186     albertel 5207:     } elsif ($error =~ /CODE$/) {
                   5208: 	if ($error eq 'incorrectCODE') {
1.187     albertel 5209: 	    $r->print("</p><p>The encoded CODE is not in the list of possible CODEs</p>\n");
1.186     albertel 5210: 	} elsif ($error eq 'duplicateCODE') {
1.194     albertel 5211: 	    $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 5212: 	}
1.224     albertel 5213: 	$r->print("<p>The CODE on the form is  <tt>'".
                   5214: 		  $$scan_record{'scantron.CODE'}."'</tt><br />\n");
1.242     albertel 5215: 	$r->print($message);
1.186     albertel 5216: 	$r->print("<p>How should I handle this? <br /> \n");
1.187     albertel 5217: 	$r->print("\n<br /> ");
1.194     albertel 5218: 	my $i=0;
1.273     albertel 5219: 	if ($error eq 'incorrectCODE' 
                   5220: 	    && $$scan_record{'scantron.CODE'}=~/\S/ ) {
1.194     albertel 5221: 	    my ($max,$closest)=&scantron_get_closely_matching_CODEs($arg,$$scan_record{'scantron.CODE'});
1.278     albertel 5222: 	    if ($closest > 0) {
                   5223: 		foreach my $testcode (@{$closest}) {
                   5224: 		    my $checked='';
                   5225: 		    if (!$i) { $checked=' checked="on" '; }
                   5226: 		    $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' />");
                   5227: 		    $r->print("\n<br />");
                   5228: 		    $i++;
                   5229: 		}
1.194     albertel 5230: 	    }
                   5231: 	}
1.273     albertel 5232: 	if ($$scan_record{'scantron.CODE'}=~/\S/ ) {
                   5233: 	    my $checked; if (!$i) { $checked=' checked="on" '; }
                   5234: 	    $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>");
                   5235: 	    $r->print("\n<br />");
                   5236: 	}
1.194     albertel 5237: 
1.188     albertel 5238: 	$r->print(<<ENDSCRIPT);
                   5239: <script type="text/javascript">
                   5240: function change_radio(field) {
1.190     albertel 5241:     var slct=document.scantronupload.scantron_CODE_resolution;
1.188     albertel 5242:     var i;
                   5243:     for (i=0;i<slct.length;i++) {
                   5244:         if (slct[i].value==field) { slct[i].checked=true; }
                   5245:     }
                   5246: }
                   5247: </script>
                   5248: ENDSCRIPT
1.187     albertel 5249: 	my $href="/adm/pickcode?".
                   5250: 	   "form=".&Apache::lonnet::escape("scantronupload").
1.257     albertel 5251: 	   "&scantron_format=".&Apache::lonnet::escape($env{'form.scantron_format'}).
                   5252: 	   "&scantron_CODElist=".&Apache::lonnet::escape($env{'form.scantron_CODElist'}).
1.187     albertel 5253: 	   "&curCODE=".&Apache::lonnet::escape($$scan_record{'scantron.CODE'}).
1.257     albertel 5254: 	   "&scantron_selectfile=".&Apache::lonnet::escape($env{'form.scantron_selectfile'});
1.332     albertel 5255: 	if ($env{'form.scantron_CODElist'} =~ /\S/) { 
                   5256: 	    $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')\" />");
                   5257: 	    $r->print("\n<br />");
                   5258: 	}
1.272     albertel 5259: 	$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 5260: 	$r->print("\n<br /><br />");
1.157     albertel 5261:     } elsif ($error eq 'doublebubble') {
                   5262: 	$r->print("<p>There have been multiple bubbles scanned for a some question(s)</p>\n");
                   5263: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5264: 		  join(',',@{$arg}).'" />');
1.242     albertel 5265: 	$r->print($message);
1.157     albertel 5266: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5267: 	foreach my $question (@{$arg}) {
                   5268: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5269: 	    &scantron_bubble_selector($r,$scan_config,$question,split('',$selected));
                   5270: 	}
                   5271:     } elsif ($error eq 'missingbubble') {
                   5272: 	$r->print("<p>There have been <b>no</b> bubbles scanned for some question(s)</p>\n");
1.242     albertel 5273: 	$r->print($message);
1.157     albertel 5274: 	$r->print("<p>Please indicate which bubble should be used for grading</p>");
                   5275: 	$r->print("Some questions have no scanned bubbles\n");
                   5276: 	$r->print('<input type="hidden" name="scantron_questions" value="'.
                   5277: 		  join(',',@{$arg}).'" />');
                   5278: 	foreach my $question (@{$arg}) {
                   5279: 	    my $selected=$$scan_record{"scantron.$question.answer"};
                   5280: 	    &scantron_bubble_selector($r,$scan_config,$question);
                   5281: 	}
                   5282:     } else {
                   5283: 	$r->print("\n<ul>");
                   5284:     }
                   5285:     $r->print("\n</li></ul>");
                   5286: 
                   5287: }
                   5288: 
                   5289: sub scantron_bubble_selector {
                   5290:     my ($r,$scan_config,$quest,@selected)=@_;
                   5291:     my $max=$$scan_config{'Qlength'};
1.274     albertel 5292: 
                   5293:     my $scmode=$$scan_config{'Qon'};
                   5294:     if ($scmode eq 'number' || $scmode eq 'letter') { $max=10; }	     
                   5295: 
1.157     albertel 5296:     my @alphabet=('A'..'Z');
                   5297:     $r->print("<table border='1'><tr><td rowspan='2'>$quest</td>");
                   5298:     for (my $i=0;$i<$max+1;$i++) {
1.274     albertel 5299: 	$r->print("\n".'<td align="center">');
1.157     albertel 5300: 	if ($selected[0] eq $alphabet[$i]) { $r->print('X'); shift(@selected) }
                   5301: 	else { $r->print('&nbsp;'); }
                   5302: 	$r->print('</td>');
                   5303:     }
1.274     albertel 5304:     $r->print('</tr><tr>');
1.157     albertel 5305:     for (my $i=0;$i<$max;$i++) {
1.274     albertel 5306: 	$r->print("\n".
                   5307: 		  '<td><label><input type="radio" name="scantron_correct_Q_'.
1.272     albertel 5308: 		  $quest.'" value="'.$i.'" />'.$alphabet[$i]."</label></td>");
1.157     albertel 5309:     }
1.272     albertel 5310:     $r->print('<td><label><input type="radio" name="scantron_correct_Q_'.
                   5311: 	      $quest.'" value="none" /> No bubble </label></td>');
1.157     albertel 5312:     $r->print('</tr></table>');
                   5313: }
                   5314: 
1.194     albertel 5315: sub num_matches {
                   5316:     my ($orig,$code) = @_;
                   5317:     my @code=split(//,$code);
                   5318:     my @orig=split(//,$orig);
                   5319:     my $same=0;
                   5320:     for (my $i=0;$i<scalar(@code);$i++) {
                   5321: 	if ($code[$i] eq $orig[$i]) { $same++; }
                   5322:     }
                   5323:     return $same;
                   5324: }
                   5325: 
                   5326: sub scantron_get_closely_matching_CODEs {
                   5327:     my ($allcodes,$CODE)=@_;
                   5328:     my @CODEs;
                   5329:     foreach my $testcode (sort(keys(%{$allcodes}))) {
                   5330: 	push(@{$CODEs[&num_matches($CODE,$testcode)]},$testcode);
                   5331:     }
                   5332: 
                   5333:     return ($#CODEs,$CODEs[-1]);
                   5334: }
                   5335: 
                   5336: sub get_codes {
1.280     foxr     5337:     my ($old_name, $cdom, $cnum) = @_;
                   5338:     if (!$old_name) {
                   5339: 	$old_name=$env{'form.scantron_CODElist'};
                   5340:     }
                   5341:     if (!$cdom) {
                   5342: 	$cdom =$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5343:     }
                   5344:     if (!$cnum) {
                   5345: 	$cnum =$env{'course.'.$env{'request.course.id'}.'.num'};
                   5346:     }
1.278     albertel 5347:     my %result=&Apache::lonnet::get('CODEs',[$old_name,"type\0$old_name"],
                   5348: 				    $cdom,$cnum);
                   5349:     my %allcodes;
                   5350:     if ($result{"type\0$old_name"} eq 'number') {
                   5351: 	%allcodes=map {($_,1)} split(',',$result{$old_name});
                   5352:     } else {
                   5353: 	%allcodes=map {(&Apache::lonprintout::num_to_letters($_),1)} split(',',$result{$old_name});
                   5354:     }
1.194     albertel 5355:     return %allcodes;
                   5356: }
                   5357: 
1.157     albertel 5358: sub scantron_validate_CODE {
                   5359:     my ($r,$currentphase) = @_;
1.257     albertel 5360:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.186     albertel 5361:     if ($scantron_config{'CODElocation'} &&
                   5362: 	$scantron_config{'CODEstart'} &&
                   5363: 	$scantron_config{'CODElength'}) {
1.257     albertel 5364: 	if (!defined($env{'form.scantron_CODElist'})) {
1.186     albertel 5365: 	    &FIXME_blow_up()
                   5366: 	}
                   5367:     } else {
                   5368: 	return (0,$currentphase+1);
                   5369:     }
                   5370:     
                   5371:     my %usedCODEs;
                   5372: 
1.194     albertel 5373:     my %allcodes=&get_codes();
1.186     albertel 5374: 
                   5375:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5376:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5377: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.186     albertel 5378: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5379: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5380: 						 $scan_data);
                   5381: 	my $CODE=$$scan_record{'scantron.CODE'};
                   5382: 	my $error=0;
1.224     albertel 5383: 	if (!&Apache::lonnet::validCODE($CODE)) {
                   5384: 	    &scantron_get_correction($r,$i,$scan_record,
                   5385: 				     \%scantron_config,
                   5386: 				     $line,'incorrectCODE',\%allcodes);
                   5387: 	    return(1,$currentphase);
                   5388: 	}
1.221     albertel 5389: 	if (%allcodes && !exists($allcodes{$CODE}) 
                   5390: 	    && !$$scan_record{'scantron.useCODE'}) {
1.186     albertel 5391: 	    &scantron_get_correction($r,$i,$scan_record,
                   5392: 				     \%scantron_config,
1.194     albertel 5393: 				     $line,'incorrectCODE',\%allcodes);
                   5394: 	    return(1,$currentphase);
1.186     albertel 5395: 	}
1.214     albertel 5396: 	if (exists($usedCODEs{$CODE}) 
1.257     albertel 5397: 	    && $env{'form.scantron_CODEunique'} eq 'yes'
1.192     albertel 5398: 	    && !$$scan_record{'scantron.CODE_ignore_dup'}) {
1.186     albertel 5399: 	    &scantron_get_correction($r,$i,$scan_record,
                   5400: 				     \%scantron_config,
1.194     albertel 5401: 				     $line,'duplicateCODE',$usedCODEs{$CODE});
                   5402: 	    return(1,$currentphase);
1.186     albertel 5403: 	}
1.194     albertel 5404: 	push (@{$usedCODEs{$CODE}},$$scan_record{'scantron.PaperID'});
1.186     albertel 5405:     }
1.157     albertel 5406:     return (0,$currentphase+1);
                   5407: }
                   5408: 
                   5409: sub scantron_validate_doublebubble {
                   5410:     my ($r,$currentphase) = @_;
                   5411:     #get student info
                   5412:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5413:     my %idmap=&username_to_idmap($classlist);
                   5414: 
                   5415:     #get scantron line setup
1.257     albertel 5416:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5417:     my ($scanlines,$scan_data)=&scantron_getfile();
                   5418:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5419: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5420: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5421: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5422: 						 $scan_data);
                   5423: 	if (!defined($$scan_record{'scantron.doubleerror'})) { next; }
                   5424: 	&scantron_get_correction($r,$i,$scan_record,\%scantron_config,$line,
                   5425: 				 'doublebubble',
                   5426: 				 $$scan_record{'scantron.doubleerror'});
                   5427:     	return (1,$currentphase);
                   5428:     }
                   5429:     return (0,$currentphase+1);
                   5430: }
                   5431: 
1.330     albertel 5432: sub scantron_get_maxbubble {    
1.257     albertel 5433:     if (defined($env{'form.scantron_maxbubble'}) &&
                   5434: 	$env{'form.scantron_maxbubble'}) {
                   5435: 	return $env{'form.scantron_maxbubble'};
1.191     albertel 5436:     }
1.330     albertel 5437: 
1.191     albertel 5438:     my $navmap=Apache::lonnavmaps::navmap->new();
                   5439:     my (undef,undef,$sequence)=
1.257     albertel 5440: 	&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.330     albertel 5441: 
1.191     albertel 5442:     my $map=$navmap->getResourceByUrl($sequence);
                   5443:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.330     albertel 5444: 
                   5445:     &Apache::lonxml::clear_problem_counter();
                   5446: 
1.191     albertel 5447:     foreach my $resource (@resources) {
1.330     albertel 5448: 	my $result=&Apache::lonnet::ssi($resource->src(),
                   5449: 					('symb' => $resource->symb()));
1.191     albertel 5450:     }
                   5451:     &Apache::lonnet::delenv('scantron\.');
1.330     albertel 5452:     $env{'form.scantron_maxbubble'} =
                   5453: 	&Apache::lonxml::get_problem_counter()-1;
                   5454: 
1.257     albertel 5455:     return $env{'form.scantron_maxbubble'};
1.191     albertel 5456: }
                   5457: 
1.157     albertel 5458: sub scantron_validate_missingbubbles {
                   5459:     my ($r,$currentphase) = @_;
                   5460:     #get student info
                   5461:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5462:     my %idmap=&username_to_idmap($classlist);
                   5463: 
                   5464:     #get scantron line setup
1.257     albertel 5465:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5466:     my ($scanlines,$scan_data)=&scantron_getfile();
1.191     albertel 5467:     my $max_bubble=&scantron_get_maxbubble();
1.157     albertel 5468:     if (!$max_bubble) { $max_bubble=2**31; }
                   5469:     for (my $i=0;$i<=$scanlines->{'count'};$i++) {
1.200     albertel 5470: 	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5471: 	if ($line=~/^[\s\cz]*$/) { next; }
                   5472: 	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5473: 						 $scan_data);
                   5474: 	if (!defined($$scan_record{'scantron.missingerror'})) { next; }
                   5475: 	my @to_correct;
                   5476: 	foreach my $missing (@{$$scan_record{'scantron.missingerror'}}) {
                   5477: 	    if ($missing > $max_bubble) { next; }
                   5478: 	    push(@to_correct,$missing);
                   5479: 	}
                   5480: 	if (@to_correct) {
                   5481: 	    &scantron_get_correction($r,$i,$scan_record,\%scantron_config,
                   5482: 				     $line,'missingbubble',\@to_correct);
                   5483: 	    return (1,$currentphase);
                   5484: 	}
                   5485: 
                   5486:     }
                   5487:     return (0,$currentphase+1);
                   5488: }
                   5489: 
1.82      albertel 5490: sub scantron_process_students {
1.75      albertel 5491:     my ($r) = @_;
1.257     albertel 5492:     my (undef,undef,$sequence)=&Apache::lonnet::decode_symb($env{'form.selectpage'});
1.324     albertel 5493:     my ($symb)=&get_symb($r);
1.81      albertel 5494:     if (!$symb) {return '';}
1.324     albertel 5495:     my $default_form_data=&defaultFormData($symb);
1.82      albertel 5496: 
1.257     albertel 5497:     my %scantron_config=&get_scantron_config($env{'form.scantron_format'});
1.157     albertel 5498:     my ($scanlines,$scan_data)=&scantron_getfile();
1.82      albertel 5499:     my $classlist=&Apache::loncoursedata::get_classlist();
                   5500:     my %idmap=&username_to_idmap($classlist);
1.132     bowersj2 5501:     my $navmap=Apache::lonnavmaps::navmap->new();
1.83      albertel 5502:     my $map=$navmap->getResourceByUrl($sequence);
                   5503:     my @resources=$navmap->retrieveResources($map,\&scantron_filter,1,0);
1.140     albertel 5504: #    $r->print("geto ".scalar(@resources)."<br />");
1.82      albertel 5505:     my $result= <<SCANTRONFORM;
1.81      albertel 5506: <form method="post" enctype="multipart/form-data" action="/adm/grades" name="scantronupload">
                   5507:   <input type="hidden" name="command" value="scantron_configphase" />
                   5508:   $default_form_data
                   5509: SCANTRONFORM
1.82      albertel 5510:     $r->print($result);
                   5511: 
                   5512:     my @delayqueue;
1.140     albertel 5513:     my %completedstudents;
                   5514:     
1.200     albertel 5515:     my $count=&get_todo_count($scanlines,$scan_data);
1.157     albertel 5516:     my %prog_state=&Apache::lonhtmlcommon::Create_PrgWin($r,'Scantron Status',
1.200     albertel 5517:  				    'Scantron Progress',$count,
1.195     albertel 5518: 				    'inline',undef,'scantronupload');
1.140     albertel 5519:     &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,
                   5520: 					  'Processing first student');
                   5521:     my $start=&Time::HiRes::time();
1.158     albertel 5522:     my $i=-1;
1.200     albertel 5523:     my ($uname,$udom,$started);
1.157     albertel 5524:     while ($i<$scanlines->{'count'}) {
                   5525:  	($uname,$udom)=('','');
                   5526:  	$i++;
1.200     albertel 5527:  	my $line=&scantron_get_line($scanlines,$scan_data,$i);
1.157     albertel 5528:  	if ($line=~/^[\s\cz]*$/) { next; }
1.200     albertel 5529: 	if ($started) {
                   5530: 	    &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,
                   5531: 						     'last student');
                   5532: 	}
                   5533: 	$started=1;
1.157     albertel 5534:  	my $scan_record=&scantron_parse_scanline($line,$i,\%scantron_config,
                   5535:  						 $scan_data);
                   5536:  	unless ($uname=&scantron_find_student($scan_record,$scan_data,
                   5537:  					      \%idmap,$i)) {
                   5538:   	    &scantron_add_delay(\@delayqueue,$line,
                   5539:  				'Unable to find a student that matches',1);
                   5540:  	    next;
                   5541:   	}
                   5542:  	if (exists $completedstudents{$uname}) {
                   5543:  	    &scantron_add_delay(\@delayqueue,$line,
                   5544:  				'Student '.$uname.' has multiple sheets',2);
                   5545:  	    next;
                   5546:  	}
                   5547:   	($uname,$udom)=split(/:/,$uname);
1.330     albertel 5548: 
                   5549: 	&Apache::lonxml::clear_problem_counter();
1.157     albertel 5550:   	&Apache::lonnet::appenv(%$scan_record);
1.161     albertel 5551: 	
                   5552: 	my $i=0;
1.83      albertel 5553: 	foreach my $resource (@resources) {
1.85      albertel 5554: 	    $i++;
1.193     albertel 5555: 	    my %form=('submitted'     =>'scantron',
                   5556: 		      'grade_target'  =>'grade',
                   5557: 		      'grade_username'=>$uname,
                   5558: 		      'grade_domain'  =>$udom,
1.257     albertel 5559: 		      'grade_courseid'=>$env{'request.course.id'},
1.193     albertel 5560: 		      'grade_symb'    =>$resource->symb());
                   5561: 	    if (exists($scan_record->{'scantron.CODE'}) &&
                   5562: 		$scan_record->{'scantron.CODE'}) {
                   5563: 		$form{'CODE'}=$scan_record->{'scantron.CODE'};
1.224     albertel 5564: 	    } else {
                   5565: 		$form{'CODE'}='';
1.193     albertel 5566: 	    }
                   5567: 	    my $result=&Apache::lonnet::ssi($resource->src(),%form);
1.227     albertel 5568: 	    if ($result ne '') {
                   5569: 		&Apache::lonnet::logthis("scantron grading error -> $result");
1.257     albertel 5570: 		&Apache::lonnet::logthis("scantron grading error info name $uname domain $udom course $env{'request.course.id'} url ".$resource->src());
1.227     albertel 5571: 	    }
1.213     albertel 5572: 	    if (&Apache::loncommon::connection_aborted($r)) { last; }
1.83      albertel 5573: 	}
1.140     albertel 5574: 	$completedstudents{$uname}={'line'=>$line};
1.213     albertel 5575: 	if (&Apache::loncommon::connection_aborted($r)) { last; }
1.140     albertel 5576:     } continue {
1.330     albertel 5577: 	&Apache::lonxml::clear_problem_counter();
1.83      albertel 5578: 	&Apache::lonnet::delenv('scantron\.');
1.82      albertel 5579:     }
1.140     albertel 5580:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
1.172     albertel 5581: #    my $lasttime = &Time::HiRes::time()-$start;
                   5582: #    $r->print("<p>took $lasttime</p>");
1.140     albertel 5583: 
1.200     albertel 5584:     $r->print("</form>");
1.324     albertel 5585:     $r->print(&show_grading_menu_form($symb));
1.157     albertel 5586:     return '';
1.75      albertel 5587: }
1.157     albertel 5588: 
                   5589: sub scantron_upload_scantron_data {
                   5590:     my ($r)=@_;
1.257     albertel 5591:     $r->print(&Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'}));
1.157     albertel 5592:     my $select_link=&Apache::loncommon::selectcourse_link('rules','courseid',
1.181     albertel 5593: 							  'domainid',
                   5594: 							  'coursename');
1.257     albertel 5595:     my $domsel=&Apache::loncommon::select_dom_form($env{'request.role.domain'},
1.157     albertel 5596: 						   'domainid');
1.324     albertel 5597:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.157     albertel 5598:     $r->print(<<UPLOAD);
                   5599: <script type="text/javascript" language="javascript">
                   5600:     function checkUpload(formname) {
                   5601: 	if (formname.upfile.value == "") {
                   5602: 	    alert("Please use the browse button to select a file from your local directory.");
                   5603: 	    return false;
                   5604: 	}
                   5605: 	formname.submit();
                   5606:     }
                   5607: </script>
                   5608: 
                   5609: <form enctype='multipart/form-data' action='/adm/grades' name='rules' method='post'>
1.162     albertel 5610: $default_form_data
1.181     albertel 5611: <table>
                   5612: <tr><td>$select_link </td></tr>
                   5613: <tr><td>Course ID:   </td><td><input name='courseid' type='text' />  </td></tr>
                   5614: <tr><td>Course Name: </td><td><input name='coursename' type='text' /></td></tr>
                   5615: <tr><td>Domain:      </td><td>$domsel                                </td></tr>
                   5616: <tr><td>File to upload:</td><td><input type="file" name="upfile" size="50" /></td></tr>
                   5617: </table>
1.157     albertel 5618: <input name='command' value='scantronupload_save' type='hidden' />
                   5619: <input type="button" onClick="javascript:checkUpload(this.form);" value="Upload Scantron Data" />
                   5620: </form>
                   5621: UPLOAD
                   5622:     return '';
                   5623: }
                   5624: 
                   5625: sub scantron_upload_scantron_data_save {
                   5626:     my($r)=@_;
1.324     albertel 5627:     my ($symb)=&get_symb($r,1);
1.182     albertel 5628:     my $doanotherupload=
                   5629: 	'<br /><form action="/adm/grades" method="post">'."\n".
                   5630: 	'<input type="hidden" name="command" value="scantronupload" />'."\n".
                   5631: 	'<input type="submit" name="submit" value="Do Another Upload" />'."\n".
                   5632: 	'</form>'."\n";
1.257     albertel 5633:     if (!&Apache::lonnet::allowed('usc',$env{'form.domainid'}) &&
1.162     albertel 5634: 	!&Apache::lonnet::allowed('usc',
1.257     albertel 5635: 			    $env{'form.domainid'}.'_'.$env{'form.courseid'})) {
1.162     albertel 5636: 	$r->print("You are not allowed to upload Scantron data to the requested course.<br />");
1.182     albertel 5637: 	if ($symb) {
1.324     albertel 5638: 	    $r->print(&show_grading_menu_form($symb));
1.182     albertel 5639: 	} else {
                   5640: 	    $r->print($doanotherupload);
                   5641: 	}
1.162     albertel 5642: 	return '';
                   5643:     }
1.257     albertel 5644:     my %coursedata=&Apache::lonnet::coursedescription($env{'form.domainid'}.'_'.$env{'form.courseid'});
1.211     ng       5645:     $r->print("Doing upload to ".$coursedata{'description'}." <br />");
1.257     albertel 5646:     my $fname=$env{'form.upfile.filename'};
1.157     albertel 5647:     #FIXME
                   5648:     #copied from lonnet::userfileupload()
                   5649:     #make that function able to target a specified course
                   5650:     # Replace Windows backslashes by forward slashes
                   5651:     $fname=~s/\\/\//g;
                   5652:     # Get rid of everything but the actual filename
                   5653:     $fname=~s/^.*\/([^\/]+)$/$1/;
                   5654:     # Replace spaces by underscores
                   5655:     $fname=~s/\s+/\_/g;
                   5656:     # Replace all other weird characters by nothing
                   5657:     $fname=~s/[^\w\.\-]//g;
                   5658:     # See if there is anything left
                   5659:     unless ($fname) { return 'error: no uploaded file'; }
1.209     ng       5660:     my $uploadedfile=$fname;
1.157     albertel 5661:     $fname='scantron_orig_'.$fname;
1.257     albertel 5662:     if (length($env{'form.upfile'}) < 2) {
                   5663: 	$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 5664:     } else {
1.275     albertel 5665: 	my $result=&Apache::lonnet::finishuserfileupload($env{'form.courseid'},$env{'form.domainid'},'upfile',$fname);
1.210     albertel 5666: 	if ($result =~ m|^/uploaded/|) {
1.257     albertel 5667: 	    $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 5668: 	} else {
1.257     albertel 5669: 	    $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 5670: 	}
                   5671:     }
1.174     albertel 5672:     if ($symb) {
1.209     ng       5673: 	$r->print(&scantron_selectphase($r,$uploadedfile));
1.174     albertel 5674:     } else {
1.182     albertel 5675: 	$r->print($doanotherupload);
1.174     albertel 5676:     }
1.157     albertel 5677:     return '';
                   5678: }
                   5679: 
1.202     albertel 5680: sub valid_file {
                   5681:     my ($requested_file)=@_;
                   5682:     foreach my $filename (sort(&scantron_filenames())) {
                   5683: 	if ($requested_file eq $filename) { return 1; }
                   5684:     }
                   5685:     return 0;
                   5686: }
                   5687: 
                   5688: sub scantron_download_scantron_data {
                   5689:     my ($r)=@_;
1.324     albertel 5690:     my $default_form_data=&defaultFormData(&get_symb($r,1));
1.257     albertel 5691:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   5692:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   5693:     my $file=$env{'form.scantron_selectfile'};
1.202     albertel 5694:     if (! &valid_file($file)) {
                   5695: 	$r->print(<<ERROR);
                   5696: 	<p>
                   5697: 	    The requested file name was invalid.
                   5698:         </p>
                   5699: ERROR
1.324     albertel 5700: 	$r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5701: 	return;
                   5702:     }
                   5703:     my $orig='/uploaded/'.$cdom.'/'.$cname.'/scantron_orig_'.$file;
                   5704:     my $corrected='/uploaded/'.$cdom.'/'.$cname.'/scantron_corrected_'.$file;
                   5705:     my $skipped='/uploaded/'.$cdom.'/'.$cname.'/scantron_skipped_'.$file;
                   5706:     &Apache::lonnet::allowuploaded('/adm/grades',$orig);
                   5707:     &Apache::lonnet::allowuploaded('/adm/grades',$corrected);
                   5708:     &Apache::lonnet::allowuploaded('/adm/grades',$skipped);
                   5709:     $r->print(<<DOWNLOAD);
                   5710:     <p>
                   5711: 	<a href="$orig">Original</a> file as uploaded by the scantron office.
                   5712:     </p>
                   5713:     <p>
                   5714: 	<a href="$corrected">Corrections</a>, a file of corrected records that were used in grading.
                   5715:     </p>
                   5716:     <p>
                   5717: 	<a href="$skipped">Skipped</a>, a file of records that were skipped.
                   5718:     </p>
                   5719: DOWNLOAD
1.324     albertel 5720:     $r->print(&show_grading_menu_form(&get_symb($r,1)));
1.202     albertel 5721:     return '';
                   5722: }
1.157     albertel 5723: 
1.75      albertel 5724: #-------- end of section for handling grading scantron forms -------
                   5725: #
                   5726: #-------------------------------------------------------------------
                   5727: 
1.72      ng       5728: #-------------------------- Menu interface -------------------------
                   5729: #
                   5730: #--- Show a Grading Menu button - Calls the next routine ---
                   5731: sub show_grading_menu_form {
1.324     albertel 5732:     my ($symb)=@_;
1.125     ng       5733:     my $result.='<br /><form action="/adm/grades" method="post">'."\n".
1.72      ng       5734: 	'<input type="hidden" name="symb" value="'.$symb.'" />'."\n".
1.257     albertel 5735: 	'<input type="hidden" name="saveState"  value="'.$env{'form.saveState'}.'" />'."\n".
1.72      ng       5736: 	'<input type="hidden" name="command" value="gradingmenu" />'."\n".
                   5737: 	'<input type="submit" name="submit" value="Grading Menu" />'."\n".
                   5738: 	'</form>'."\n";
                   5739:     return $result;
                   5740: }
                   5741: 
1.77      ng       5742: # -- Retrieve choices for grading form
                   5743: sub savedState {
                   5744:     my %savedState = ();
1.257     albertel 5745:     if ($env{'form.saveState'}) {
                   5746: 	foreach (split(/:/,$env{'form.saveState'})) {
1.77      ng       5747: 	    my ($key,$value) = split(/=/,$_,2);
                   5748: 	    $savedState{$key} = $value;
                   5749: 	}
                   5750:     }
                   5751:     return \%savedState;
                   5752: }
1.76      ng       5753: 
1.72      ng       5754: #--- Displays the main menu page -------
                   5755: sub gradingmenu {
                   5756:     my ($request) = @_;
1.324     albertel 5757:     my ($symb)=&get_symb($request);
1.72      ng       5758:     if (!$symb) {return '';}
1.76      ng       5759:     my $probTitle = &Apache::lonnet::gettitle($symb);
1.72      ng       5760: 
                   5761:     $request->print(<<GRADINGMENUJS);
                   5762: <script type="text/javascript" language="javascript">
1.116     ng       5763:     function checkChoice(formname,val,cmdx) {
                   5764: 	if (val <= 2) {
                   5765: 	    var cmd = radioSelection(formname.radioChoice);
1.118     ng       5766: 	    var cmdsave = cmd;
1.116     ng       5767: 	} else {
                   5768: 	    cmd = cmdx;
1.118     ng       5769: 	    cmdsave = 'submission';
1.116     ng       5770: 	}
                   5771: 	formname.command.value = cmd;
1.118     ng       5772: 	formname.saveState.value = "saveCmd="+cmdsave+":saveSec="+pullDownSelection(formname.section)+
1.145     albertel 5773: 	    ":saveSub="+pullDownSelection(formname.submitonly)+":saveStatus="+pullDownSelection(formname.Status);
1.116     ng       5774: 	if (val < 5) formname.submit();
                   5775: 	if (val == 5) {
1.72      ng       5776: 	    if (!checkReceiptNo(formname,'notOK')) { return false;}
                   5777: 	    formname.submit();
                   5778: 	}
1.238     albertel 5779: 	if (val < 7) formname.submit();
1.72      ng       5780:     }
                   5781: 
                   5782:     function checkReceiptNo(formname,nospace) {
                   5783: 	var receiptNo = formname.receipt.value;
                   5784: 	var checkOpt = false;
                   5785: 	if (nospace == "OK" && isNaN(receiptNo)) {checkOpt = true;}
                   5786: 	if (nospace == "notOK" && (isNaN(receiptNo) || receiptNo == "")) {checkOpt = true;}
                   5787: 	if (checkOpt) {
                   5788: 	    alert("Please enter a receipt number given by a student in the receipt box.");
                   5789: 	    formname.receipt.value = "";
                   5790: 	    formname.receipt.focus();
                   5791: 	    return false;
                   5792: 	}
                   5793: 	return true;
                   5794:     }
                   5795: </script>
                   5796: GRADINGMENUJS
1.118     ng       5797:     &commonJSfunctions($request);
                   5798:     my $result='<h3>&nbsp;<font color="#339933">Manual Grading/View Submission</font></h3>';
1.324     albertel 5799:     my ($table,undef,$hdgrade) = &showResourceInfo($symb,$probTitle);
1.118     ng       5800:     $result.=$table;
1.76      ng       5801:     my (undef,$sections) = &getclasslist('all','0');
1.77      ng       5802:     my $savedState = &savedState();
1.118     ng       5803:     my $saveCmd = ($$savedState{'saveCmd'} eq '' ? 'submission' : $$savedState{'saveCmd'});
1.77      ng       5804:     my $saveSec = ($$savedState{'saveSec'} eq '' ? 'all' : $$savedState{'saveSec'});
1.118     ng       5805:     my $saveSub = ($$savedState{'saveSub'} eq '' ? 'all' : $$savedState{'saveSub'});
1.77      ng       5806:     my $saveStatus = ($$savedState{'saveStatus'} eq '' ? 'Active' : $$savedState{'saveStatus'});
1.72      ng       5807: 
                   5808:     $result.='<form action="/adm/grades" method="post" name="gradingMenu">'."\n".
                   5809: 	'<input type="hidden" name="symb"        value="'.$symb.'" />'."\n".
                   5810: 	'<input type="hidden" name="handgrade"   value="'.$hdgrade.'" />'."\n".
                   5811: 	'<input type="hidden" name="probTitle"   value="'.$probTitle.'" />'."\n".
1.116     ng       5812: 	'<input type="hidden" name="command"     value="" />'."\n".
1.77      ng       5813: 	'<input type="hidden" name="saveState"   value="" />'."\n".
1.124     ng       5814: 	'<input type="hidden" name="gradingMenu" value="1" />'."\n".
1.72      ng       5815: 	'<input type="hidden" name="showgrading" value="yes" />'."\n";
                   5816: 
1.326     albertel 5817:     $result.='<table width="100%" border="0"><tr><td bgcolor=#777777>'."\n".
                   5818: 	'<table width="100%" border="0"><tr bgcolor="#e6ffff"><td colspan="2">'."\n".
1.72      ng       5819: 	'&nbsp;<b>Select a Grading/Viewing Option</b></td></tr>'."\n".
1.116     ng       5820: 	'<tr bgcolor="#ffffe6" valign="top"><td>'."\n";
                   5821: 
1.326     albertel 5822:     $result.='<table width="100%" border="0">';
1.116     ng       5823:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'."\n".
1.167     sakharuk 5824: 	'&nbsp;'.&mt('Select Section').': <select name="section">'."\n";
1.116     ng       5825:     if (ref($sections)) {
1.155     albertel 5826: 	foreach (sort (@$sections)) {
                   5827: 	    $result.='<option value="'.$_.'" '.
                   5828: 		($saveSec eq $_ ? 'selected="on"':'').'>'.$_.'</option>'."\n";
                   5829: 	}
1.116     ng       5830:     }
1.238     albertel 5831:     $result.= '<option value="all" '.($saveSec eq 'all' ? 'selected="on"' : ''). '>all</option></select> &nbsp; ';
1.116     ng       5832: 
1.167     sakharuk 5833:     $result.=&mt('Student Status').':</b>'.&Apache::lonhtmlcommon::StatusOptions($saveStatus,undef,1,undef);
1.72      ng       5834: 
1.116     ng       5835:     $result.='</td></tr>';
                   5836: 
1.288     albertel 5837:     $result.='<tr bgcolor="#ffffe6"valign="top"><td><label>'.
1.118     ng       5838: 	'<input type="radio" name="radioChoice" value="submission" '.
1.326     albertel 5839: 	($saveCmd eq 'submission' ? 'checked' : '').' /> '.'<b>'.&mt('Current Resource').':</b> '.&mt('For one or more students').
1.288     albertel 5840: 	'</label> <select name="submitonly">'.
1.145     albertel 5841: 	'<option value="yes" '.
1.326     albertel 5842: 	($saveSub eq 'yes' ? 'selected="on"' : '').' />'.&mt('with submissions').'</option>'.
1.301     albertel 5843: 	'<option value="queued" '.
1.326     albertel 5844: 	($saveSub eq 'queued' ? 'selected="on"' : '').' />'.&mt('in grading queue').'</option>'.
1.145     albertel 5845: 	'<option value="graded" '.
1.326     albertel 5846: 	($saveSub eq 'graded' ? 'selected="on"' : '').' />'.&mt('with ungraded submissions').'</option>'.
1.156     albertel 5847: 	'<option value="incorrect" '.
1.326     albertel 5848: 	($saveSub eq 'incorrect' ? 'selected="on"' : '').' />'.&mt('with incorrect submissions').'</option>'.
1.145     albertel 5849: 	'<option value="all" '.
1.326     albertel 5850: 	($saveSub eq 'all' ? 'selected="on"' : '').' />'.&mt('with any status').'</option></select></td></tr>'."\n";
1.72      ng       5851: 
1.116     ng       5852:     $result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.288     albertel 5853: 	'<label><input type="radio" name="radioChoice" value="viewgrades" '.
1.326     albertel 5854: 	($saveCmd eq 'viewgrades' ? 'checked' : '').' /> '.
1.288     albertel 5855: 	'<b>Current Resource:</b> For all students in selected section or course</label></td></tr>'."\n";
1.72      ng       5856: 
1.118     ng       5857:     $result.='<tr bgcolor="#ffffe6" valign="top"><td>'.
1.288     albertel 5858: 	'<label><input type="radio" name="radioChoice" value="pickStudentPage" '.
1.326     albertel 5859: 	($saveCmd eq 'pickStudentPage' ? 'checked' : '').' /> '.
1.288     albertel 5860: 	'The <b>complete</b> set/page/sequence: For one student</label></td></tr>'."\n";
1.46      ng       5861: 
1.116     ng       5862:     $result.='<tr bgcolor="#ffffe6"><td><br />'.
1.126     ng       5863: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'2\');" value="Next->" />'.
1.116     ng       5864: 	'</td></tr></table>'."\n";
                   5865: 
                   5866:     $result.='</td><td valign="top">';
                   5867: 
1.326     albertel 5868:     $result.='<table width="100%" border="0">';
1.116     ng       5869:     $result.='<tr bgcolor="#ffffe6"><td>'.
1.184     www      5870: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'3\',\'csvform\');" value="'.&mt('Upload').'" />'.
                   5871: 	' '.&mt('scores from file').' </td></tr>'."\n";
1.72      ng       5872: 
1.75      albertel 5873:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
1.116     ng       5874: 	'<input type="button" onClick="javascript:checkChoice(this.form,\'4\',\'scantron_selectphase\');'.
1.184     www      5875: 	'" value="'.&mt('Grade').'" /> scantron forms</td></tr>'."\n";
1.75      albertel 5876: 
1.257     albertel 5877:     if ((&Apache::lonnet::allowed('mgr',$env{'request.course.id'})) && ($symb)) {
1.72      ng       5878: 	$result.='<tr bgcolor="#ffffe6"valign="top"><td>'.
1.184     www      5879: 	    '<input type="button" onClick="javascript:checkChoice(this.form,\'5\',\'verify\');" value="'.&mt('Verify').'" />'.
                   5880: 	    ' '.&mt('receipt').': '.
1.257     albertel 5881: 	    &Apache::lonnet::recprefix($env{'request.course.id'}).
1.326     albertel 5882: 	    '-<input type="text" name="receipt" size="4" onChange="javascript:checkReceiptNo(this.form,\'OK\')" />'.
1.72      ng       5883: 	    '</td></tr>'."\n";
                   5884:     } 
1.238     albertel 5885:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5886: 	'<input type="button" onClick="javascript:this.form.action=\'/adm/helper/resettimes.helper\';this.form.submit();'.
                   5887: 	'" value="'.&mt('Manage').'" /> access times.</td></tr>'."\n";
1.279     albertel 5888:     $result.='<tr bgcolor="#ffffe6"valign="top"><td colspan="2">'.
                   5889: 	'<input type="button" onClick="javascript:this.form.command.value=\'codelist\';this.form.action=\'/adm/pickcode\';this.form.submit();'.
                   5890: 	'" value="'.&mt('View').'" /> saved CODEs.</td></tr>'."\n";
1.44      ng       5891: 
1.116     ng       5892:     $result.='</form></td></tr></table>'."\n".
1.72      ng       5893: 	'</td></tr></table>'."\n".
                   5894: 	'</td></tr></table>'."\n";
1.44      ng       5895:     return $result;
1.2       albertel 5896: }
                   5897: 
1.285     albertel 5898: sub reset_perm {
                   5899:     undef(%perm);
                   5900: }
                   5901: 
                   5902: sub init_perm {
                   5903:     &reset_perm();
1.300     albertel 5904:     foreach my $test_perm ('vgr','mgr','opa') {
                   5905: 
                   5906: 	my $scope = $env{'request.course.id'};
                   5907: 	if (!($perm{$test_perm}=&Apache::lonnet::allowed($test_perm,$scope))) {
                   5908: 
                   5909: 	    $scope .= '/'.$env{'request.course.sec'};
                   5910: 	    if ( $perm{$test_perm}=
                   5911: 		 &Apache::lonnet::allowed($test_perm,$scope)) {
                   5912: 		$perm{$test_perm.'_section'}=$env{'request.course.sec'};
                   5913: 	    } else {
                   5914: 		delete($perm{$test_perm});
                   5915: 	    }
1.285     albertel 5916: 	}
                   5917:     }
                   5918: }
                   5919: 
1.1       albertel 5920: sub handler {
1.41      ng       5921:     my $request=$_[0];
1.102     albertel 5922: 
1.285     albertel 5923:     &reset_perm();
1.257     albertel 5924:     if ($env{'browser.mathml'}) {
1.141     www      5925: 	&Apache::loncommon::content_type($request,'text/xml');
1.41      ng       5926:     } else {
1.141     www      5927: 	&Apache::loncommon::content_type($request,'text/html');
1.41      ng       5928:     }
                   5929:     $request->send_http_header;
1.44      ng       5930:     return '' if $request->header_only;
1.41      ng       5931:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
1.324     albertel 5932:     my $symb=&get_symb($request,1);
1.160     albertel 5933:     my @commands=&Apache::loncommon::get_env_multiple('form.command');
                   5934:     my $command=$commands[0];
                   5935:     if ($#commands > 0) {
                   5936: 	&Apache::lonnet::logthis("grades got multiple commands ".join(':',@commands));
                   5937:     }
1.41      ng       5938:     &send_header($request);
1.324     albertel 5939:     if ($symb eq '' && $command eq '') {
1.257     albertel 5940: 	if ($env{'user.adv'}) {
                   5941: 	    if (($env{'form.codeone'}) && ($env{'form.codetwo'}) &&
                   5942: 		($env{'form.codethree'})) {
                   5943: 		my $token=$env{'form.codeone'}.'*'.$env{'form.codetwo'}.'*'.
                   5944: 		    $env{'form.codethree'};
1.41      ng       5945: 		my ($tsymb,$tuname,$tudom,$tcrsid)=
                   5946: 		    &Apache::lonnet::checkin($token);
                   5947: 		if ($tsymb) {
1.137     albertel 5948: 		    my ($map,$id,$url)=&Apache::lonnet::decode_symb($tsymb);
1.41      ng       5949: 		    if (&Apache::lonnet::allowed('mgr',$tcrsid)) {
1.99      albertel 5950: 			$request->print(&Apache::lonnet::ssi_body('/res/'.$url,
                   5951: 					  ('grade_username' => $tuname,
                   5952: 					   'grade_domain' => $tudom,
                   5953: 					   'grade_courseid' => $tcrsid,
                   5954: 					   'grade_symb' => $tsymb)));
1.41      ng       5955: 		    } else {
1.45      ng       5956: 			$request->print('<h3>Not authorized: '.$token.'</h3>');
1.99      albertel 5957: 		    }
1.41      ng       5958: 		} else {
1.45      ng       5959: 		    $request->print('<h3>Not a valid DocID: '.$token.'</h3>');
1.41      ng       5960: 		}
1.14      www      5961: 	    } else {
1.41      ng       5962: 		$request->print(&Apache::lonxml::tokeninputfield());
                   5963: 	    }
                   5964: 	}
                   5965:     } else {
1.285     albertel 5966: 	&init_perm();
1.104     albertel 5967: 	if ($command eq 'submission' && $perm{'vgr'}) {
1.257     albertel 5968: 	    ($env{'form.student'} eq '' ? &listStudents($request) : &submission($request,0,0));
1.103     albertel 5969: 	} elsif ($command eq 'pickStudentPage' && $perm{'vgr'}) {
1.68      ng       5970: 	    &pickStudentPage($request);
1.103     albertel 5971: 	} elsif ($command eq 'displayPage' && $perm{'vgr'}) {
1.68      ng       5972: 	    &displayPage($request);
1.104     albertel 5973: 	} elsif ($command eq 'gradeByPage' && $perm{'mgr'}) {
1.71      ng       5974: 	    &updateGradeByPage($request);
1.104     albertel 5975: 	} elsif ($command eq 'processGroup' && $perm{'vgr'}) {
1.41      ng       5976: 	    &processGroup($request);
1.104     albertel 5977: 	} elsif ($command eq 'gradingmenu' && $perm{'vgr'}) {
1.41      ng       5978: 	    $request->print(&gradingmenu($request));
1.104     albertel 5979: 	} elsif ($command eq 'viewgrades' && $perm{'vgr'}) {
1.41      ng       5980: 	    $request->print(&viewgrades($request));
1.104     albertel 5981: 	} elsif ($command eq 'handgrade' && $perm{'mgr'}) {
1.41      ng       5982: 	    $request->print(&processHandGrade($request));
1.106     albertel 5983: 	} elsif ($command eq 'editgrades' && $perm{'mgr'}) {
1.41      ng       5984: 	    $request->print(&editgrades($request));
1.106     albertel 5985: 	} elsif ($command eq 'verify' && $perm{'vgr'}) {
1.41      ng       5986: 	    $request->print(&verifyreceipt($request));
1.106     albertel 5987: 	} elsif ($command eq 'csvform' && $perm{'mgr'}) {
1.72      ng       5988: 	    $request->print(&upcsvScores_form($request));
1.106     albertel 5989: 	} elsif ($command eq 'csvupload' && $perm{'mgr'}) {
1.41      ng       5990: 	    $request->print(&csvupload($request));
1.106     albertel 5991: 	} elsif ($command eq 'csvuploadmap' && $perm{'mgr'} ) {
1.41      ng       5992: 	    $request->print(&csvuploadmap($request));
1.246     albertel 5993: 	} elsif ($command eq 'csvuploadoptions' && $perm{'mgr'}) {
1.257     albertel 5994: 	    if ($env{'form.associate'} ne 'Reverse Association') {
1.246     albertel 5995: 		$request->print(&csvuploadoptions($request));
1.41      ng       5996: 	    } else {
1.257     albertel 5997: 		if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                   5998: 		    $env{'form.upfile_associate'} = 'reverse';
1.41      ng       5999: 		} else {
1.257     albertel 6000: 		    $env{'form.upfile_associate'} = 'forward';
1.41      ng       6001: 		}
                   6002: 		$request->print(&csvuploadmap($request));
                   6003: 	    }
1.246     albertel 6004: 	} elsif ($command eq 'csvuploadassign' && $perm{'mgr'} ) {
                   6005: 	    $request->print(&csvuploadassign($request));
1.106     albertel 6006: 	} elsif ($command eq 'scantron_selectphase' && $perm{'mgr'}) {
1.75      albertel 6007: 	    $request->print(&scantron_selectphase($request));
1.203     albertel 6008:  	} elsif ($command eq 'scantron_warning' && $perm{'mgr'}) {
                   6009:  	    $request->print(&scantron_do_warning($request));
1.142     albertel 6010: 	} elsif ($command eq 'scantron_validate' && $perm{'mgr'}) {
                   6011: 	    $request->print(&scantron_validate_file($request));
1.106     albertel 6012: 	} elsif ($command eq 'scantron_process' && $perm{'mgr'}) {
1.82      albertel 6013: 	    $request->print(&scantron_process_students($request));
1.157     albertel 6014:  	} elsif ($command eq 'scantronupload' && 
1.257     albertel 6015:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6016: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.162     albertel 6017:  	    $request->print(&scantron_upload_scantron_data($request)); 
1.157     albertel 6018:  	} elsif ($command eq 'scantronupload_save' &&
1.257     albertel 6019:  		 (&Apache::lonnet::allowed('usc',$env{'request.role.domain'})||
                   6020: 		  &Apache::lonnet::allowed('usc',$env{'request.course.id'}))) {
1.157     albertel 6021:  	    $request->print(&scantron_upload_scantron_data_save($request));
1.202     albertel 6022:  	} elsif ($command eq 'scantron_download' &&
1.257     albertel 6023: 		 &Apache::lonnet::allowed('usc',$env{'request.course.id'})) {
1.162     albertel 6024:  	    $request->print(&scantron_download_scantron_data($request));
1.106     albertel 6025: 	} elsif ($command) {
1.157     albertel 6026: 	    $request->print("Access Denied ($command)");
1.26      albertel 6027: 	}
1.2       albertel 6028:     }
1.41      ng       6029:     &send_footer($request);
1.44      ng       6030:     return '';
                   6031: }
                   6032: 
                   6033: sub send_header {
                   6034:     my ($request)= @_;
1.340     albertel 6035:     &Apache::lontexconvert::init_tth();
1.339     albertel 6036:     $request->print(&Apache::loncommon::start_page('Grading'));
1.157     albertel 6037:     $request->rflush();
1.44      ng       6038: }
                   6039: 
                   6040: sub send_footer {
                   6041:     my ($request)= @_;
1.339     albertel 6042:     $request->print(&Apache::loncommon::end_page());
1.1       albertel 6043: }
                   6044: 
                   6045: 1;
                   6046: 
1.13      albertel 6047: __END__;

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