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

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

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