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

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

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